Java 字符串#实习生对实习生的结果感到困惑

Java 字符串#实习生对实习生的结果感到困惑,java,string,jvm,Java,String,Jvm,打印: public class Main { public static void main(String[] args) { String a = new String("11") ; a.intern(); String b = "11"; System.out.println(a == b); // false String c = new String("2")

打印:

public class Main {
    public static void main(String[] args) {
        String a = new String("11") ;
        a.intern();
        String b = "11";
        System.out.println(a == b);                  // false

        String c = new String("2") + new String("2");
        c.intern();
        String d = "22";
        System.out.println(c == d);                  // true
    }
}

我在jkd 1.8上运行它。我很困惑为什么第二个println会产生结果。

A
String
literal总是在第一次出现时自动插入。代码中的
字符串
文本为“11”和“2”

另一方面,由于
字符串
串联而创建的
字符串
不会自动插入

false
true
因此
a!=b

String a = new String("11"); // interns the String literal "11", and creates a
                             // different String instance referenced by a
a.intern(); // doesn't add a to the String pool, since "11" is already in 
            // the String pool
String b = "11"; // "11" returns the canonical instance already in the pool,
                 // which is != a
因此
c==d

以上所有内容摘自
intern
的Javadoc:

返回字符串对象的规范表示形式

最初为空的字符串池由类字符串私下维护

调用intern方法时,如果池中已包含一个与equals(object)方法确定的字符串对象相等的字符串,则返回池中的字符串否则,此字符串对象将添加到池中,并返回对此字符串对象的引用。

因此,对于任意两个字符串s和t,s.intern()==t.intern()为真当且仅当s.equals(t)为真时

所有的文本字符串和字符串值常量表达式都是内部的。字符串文本在Java的第3.10.5节中定义™ 语言规范


你从未使用过“intern”的结果,你的代码应该做什么?@azro我检查字符串常量池位置的新差异。它移动到了堆中。所以我想知道intern()方法之后,堆中是否创建了另一个字符串对象。字符串始终在堆内存中。这就是定义,因为规范将“堆内存”定义为在其中创建所有Java对象的内存。@H.William为了让自己相信解释是正确的,请将
d
的声明移到
c
之前<代码>错误将被打印()。这可以用作…
String c = new String("2") + new String("2"); // interns the String "2", creates 2 
                                              // more Strings having the same value,
                                              // and creates an additional String
                                              // whose value is "22", which is not
                                              // interned yet
c.intern(); // c is added to the String pool as the canonical instance whose value
            // is "22"
String d = "22"; // "22" returns the canonical instance already in the pool,
                 // which is == c