String类型

- String类型用final修饰,不可被其他类继承。
- String底层使用byte[]存储,且用final修饰,该类描述的字符串内容是个常量不可更改,因此可以被共享使用
如:String str1 = “abc”; 其中"abc"这个字符串是个常量不可改变。
str1 = “123”; - 将“123”字符串的地址赋值给变量str1。改变str1的指向并没有改变指向的内容
常量池的概念
由于String类型描述的字符串内容是常量不可改变,因此Java虚拟机将首次出现的字符串放入常量池中,若后续代码中出现了相同字符串内容则直接使用池中已有的字符串对象而无需申请内存及创建对象,从而提高了性能。
例子:
关于创建对象
public class StringTest {
public static void main(String[] args) {
String s1="abc";
String s2=new String("def");
}
}
对于String s1=“abc”;存在一个字面量,创建了一个对象,放在常量池中。
对于String s2=new String(“def”); 创建了两个对象,一个在常量池中,一个在堆区中。
关于比较
public class StringTest {
public static void main(String[] args) {
String s3="world";//放在常量池
String s4="world";//放在常量池
String s5=new String("world");//放在堆区
String s6=new String("world");//放在堆区
System.out.println(s3==s4);//true,比较地址
System.out.println(s3.equals(s4));//true,比较内容
System.out.println(s5==s6);//false,比较地址
System.out.println(s5.equals(s6));//true,比较内容
System.out.println(s4==s6);//false,比较地址
System.out.println(s4.equals(s6));//true,比较内容
}
}
结果为

关于常量优化
public class StringTest {
public static void main(String[] args) {
String s7="world";
String s8="wor"+"ld";//常量优化机制
String s9="wor";
String s10=s9+"ld";//对象没有优化机制
System.out.println("s7==s8:"+(s7==s8));//true,比较地址
System.out.println("s7==s10:"+(s7==s10));//false,比较地址
}
}
结果为

本文详细解析了Java中的String类型,探讨了其不可变性、内存存储方式以及常量池的概念。通过实例展示了String对象的创建与比较,解释了常量优化机制如何提高性能。此外,还讲解了字符串比较时的地址与内容差异,帮助理解Java内存管理机制。
1091

被折叠的 条评论
为什么被折叠?



