Java代码
class Other {
static String hello = "Hello World";
}
public class Main {
public static void main(String[] args) {
String hello = "Hello World", world = "World";
System.out.println(Other.hello == hello); // Line1
System.out.println(hello == ("Hello " + "World")); // Line2
System.out.println(hello == ("Hello " + world)); // Line3
System.out.println(hello == ("Hello " + world).intern()); // Line4
System.out.println(Integer.toHexString(hello.hashCode()));
System.out.println(Integer.toHexString(("Hello " + "World").hashCode()));
System.out.println(Integer.toHexString(("Hello " + world).hashCode()));
System.out.println(Integer.toHexString(("Hello " + world).intern().hashCode()));
}
}
我期望 Line3 返回 true,但它返回 false。请帮助我。
输出 真 真 假 真 42628b2 42628b2 42628b2 42628b2
只有字符串文字会自动存储在字符串常量池中。
以下是字符串文字:
"Hello " + "world"
以下内容不是字符串文字:
String world = "world";
"Hello " + world
这在Java语言规范中有具体规定:
长字符串文字总是可以分解成更短的片段 使用字符串写为(可能带括号的)表达式 连接运算符 +
为什么
"Hello " + world
不在字符串常量池中?只是因为 JLS 这么说。这就是语言设计者决定的。