public class test{
public static void main(String[] args) {
String s3 = new String("hello") ;
String intern3 = s3.intern();
String s4 = "hello";
System.out.println(s3 == intern3);
System.out.println(s3 == s4);
}
}
false
false
如上代码在jdk 1.8测试,出现false,当时很纳闷,不是1.7之后intern在常量池存储的是堆上的引用吗?
经过仔细思考,发现错误在哪里,当new的时候,在常量池里存储的是字符串,而s3.inern方法首先查找常量池
是否有“hello”,由于创建时在字符串常量池已经有"hello"的字符串了,所以inern3返回的是常量池的“hello”地址。
什么时候返回堆上的引用呢,看下面的例子
public class test{
public static void main(String[] args) {
String s3 = new String("hello") + new String("hello");
String intern3 = s3.intern();
String s4 = "hellohello";
System.out.println(s3 == s4);
}
}
true
为什么现在返回true,因为s3没有在常量池存储自己的字符串字面量,使用Intern方法后,字符串常量池存放堆上的引用,所以再
创建字符串,返回的是堆上的引用,所以返回true。