虽然intern()方法都是指返回字符串常量池中字符串对象引用,但是在不同的JDK版本中,字符串常量池的位置不同,决定了字符串常量池是否会与堆中的字符串共享问题。
不同JDK版本的字符串常量共享的区别
import org.junit.Test;
public class StringInternTest {
@Test
public void testl() {
String s = "ab";
String s1 = new String("a") + new String("b");
String s2 = s1.intern();
System.out.println(s1 == s);//JDK6、JDK7和JDK8:false
System.out.println(s2 == s);//JDK7和JDK7和JDK8:true
}
@Test
public void test2() {
String s1 = new String("a") + new String("b");
String s2 = s1.intern();
String s = "ab";
System.out.println(s1 == s);//JDK6:false JDK7和JDK8:true
System.out.println(s2 == s);//JDK6:true JDK7和JDK8:true
}
}
JDK 6版本test1()和test2()方法的内存示意图,如下所示:

JDK 7、JDK 8版本test1()和test2()方法的内存示意图,如下所示:

JDK7以后,先放入堆中的字符串会和字符串常量池的地址共享
790

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



