在堆中创建的字符串与在字符串常量池中创建的字符串。为什么 Line3 返回 False 而 Line2 和 Line4 返回 True? [重复]

问题描述 投票:0回答:1

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

java string object
1个回答
0
投票

只有字符串文字会自动存储在字符串常量池中。

以下是字符串文字:

"Hello " + "world"

以下内容不是字符串文字:

String world = "world";
"Hello " + world

这在Java语言规范中有具体规定:

长字符串文字总是可以分解成更短的片段 使用字符串写为(可能带括号的)表达式 连接运算符 +

© www.soinside.com 2019 - 2024. All rights reserved.