Java中String类型变量存储的不同位置
String类的使用陷阱:
- 1.正常来说,常量与常量的拼接结果还在常量池中
- 2.但是在拼接的过程中,有一个是变量,那么结果就存在于堆中。
- 注意:常量池内不会存在相同的常量内容。
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
String s3 = "hello" + "world";
String s4 = s1 + "world";
String s5 = s1 + s2;
String s6 = (s1 + s2).intern();//该方法返回值是一个字符串,返回的内容就是字符串对象的内容,但是一定取自常量池中
System.out.println(s3 == s4);//false
System.out.println(s3 == s5);//false
System.out.println(s4 == s5);//false
System.out.println(s3 == s6);//true
}
注释即为输出结果,可以用下面的存储位置图解释