JDK1.8环境下:
调用intern会检查该字符串是否存在池中,有且和该字符串不相同(equals方法判断)则返回该字符串常量的引用,否则创建该常量并返回引用
API:
if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
new产生的对象不放入池中
String s1 = new String("a") + new String("a"); //s1指向堆中对象
s1.intern();//s1池中无“aa”,加入到常量池中
String s2 = "aa";// 因为池中有“aa”所以直接将将引用给s2
System.out.println(s1 == s2);//true 所以s1和s2的地址相等
String s1 = new String("a") + new String("a"); //s1指向堆中对象
String s2 = "aa";// 池中无“aa”,加入到常量池中
s1.intern();//池中有"aa"返回引用,但是没有意义
System.out.println(s1 == s2);//false 所以s1和s2的地址不相等
单个newString()和上面一样,同理
String s1 = new String("a"); //s1指向堆中对象
s1.intern();//s1池中无“a”,加入到常量池中
String s2 = "a";// 因为池中有“a”所以直接将将引用给s2
System.out.println(s1 == s2);//true 所以s1和s2的地址相等
String s1 = new String("a"); //s1指向堆中对象
String s2 = "a";// 池中无“a”,加入到常量池中
s1.intern();//池中有"aa"返回引用,但是没有意义
System.out.println(s1 == s2);//false 所以s1和s2的地址不相等
问题来了??
String s=new StringBuilder("aa").append("bb").toString();
String s2=new StringBuilder("aa").toString();
System.out.println(s.intern()==s);//true
System.out.println(s2.intern()==s2);//false