有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java string中的intern方法与string CONNECT不同

我发现java string中的intern方法与string CONNECT不同。我使用的是JDK 1.8.045

public class LocalTest {

public static void main(String[] args) {

       String s1 = new String("hell") + new String("o");
       String s2 = s1.intern();
       System.out.println("s1 == s2? " + (s1 == s2));

    }
}
//s1 == s2? true

但当使用以下命令时,输出是错误的

public class LocalTest {

    public static void main(String[] args) {

           String s1 = new String("hello");
           String s2 = s1.intern();
           System.out.println("s1 == s2? " + (s1 == s2));

    }

}//s1 == s2? false

我知道JVM中有一些优化,但我不确定它在哪里

谢谢


共 (1) 个答案

  1. # 1 楼答案

    在第一种情况下,值为"hello"的字符串在JVM中的任何位置都不存在,直到您通过连接创建一个字符串,因此当您调用intern()时,新创建的字符串被添加到字符串池并返回,其引用保存在s2

    然而,在第二种情况下,"hello"已经在字符串池中,因为所有字符串常量都是空的。创建一个新对象以保存到s1,但由于池已经有一个副本,因此当调用intern()时,现有池副本将返回并保存在s2,这意味着s1s2不引用同一对象