经典面试题
String str1 = new String("11");
System.out.println(str1.intern() == str1); // false
String str = new String("1") + new String("1");
System.out.println(str.intern() == str); // true
为什么上面两道题,intern()返回的结果不一致?
在jdk1.7以前,字符串常量池存在于方法区中
此时我们调用intern(),他最终会返回该字符串在常量池中的地址(首先判断常量池中是否存在,如果存在直接返回常量池中字符串的地址,不存在则在常量池中新建该字符串并将新建地址返回)。
在jdk1.7及以后,字符串常量池存在于堆空间内
此时调用intern()时,他会先查看堆空间中是否存在该字符串,如果存在,常量池直接引用堆空间中该字符串的地址,不存在才会在常量池中新建地址并且返回。