intern()后结果为何是false?


String str2 = new String("str")+new String("01");
String str1 = "str01";
str2.intern();
System.out.println(str2==str1);

来看一眼intern()这个方法
注意这一段:

When the intern method is invoked, if the pool already contains a string equal to this {@code String} object as determined by the {@link #equals(Object)} method, then the string from the pool is returned. Otherwise, this {@code String} object is added to the pool and a reference to this {@code String} object is returned.

翻译过来的意思是:

当intern方法被调用时,如果常量池中已经包含了一个字符串,该字符串等于这个对象,那么池中的字符串将被返回。否则,该对象将被添加到池中,并返回对该对象的引用。

其实,intern()是一个Native方法,底层调用C++的 StringTable::intern方法实现。当通过语句str.intern()调用intern()方法后,JVM 就会在当前类的常量池中查找是否存在与str等值的String,若存在则直接返回常量池中相应Strnig的引用;若不存在,则会在常量池中创建一个等值的String,然后返回这个String在常量池中的引用。因此,只要是等值的String对象,使用intern()方法返回的都是常量池中同一个String引用,所以,这些等值的String对象通过intern()后使用==是可以匹配的。

其实严格来说,上面那段代码在JDK1.6中,会得到两个false;而在JDK1.7及之后中运行,则会得到一个false和一个true。

详细查看:https://blog.csdn.net/jcSongle/article/details/108271921

当str2调用intern的时候,会检查字符串池中是否含有该字符串。