字符串池相关的概念,但令人困惑

时间:2014-10-23 11:49:20

标签: java string

考虑以下带注释的代码

public class Demo
{
    public static void main(String aa[])
    {
        String hello="Hello",lo="lo",hel="Hel";
        System.out.println(other.hello=="Hel"+lo); // returns false because new strings are created
        System.out.println(other.hello==hel+lo); // returns false, same reason i think. Comment if i am not correct
        System.out.println(other.hello=="Hel"+"lo"); // returns true, how ?
    }
}
class other
{
    static String hello="Hello";
}

第一个打印为false,因为在比较之前创建了新的字符串(如果我错了,请纠正我)。 由于我认为的原因,第二次也打印错误。但第三个声明打印为真。如何发生这种情况或背后的原因是什么?

3 个答案:

答案 0 :(得分:3)

这个表达式:

"Hel"+"lo"

constant expression,这意味着它在编译时被评估。因此,表达式具有与显式字符串文字

完全相同的处理
"Hello"

,BTW,只是常量表达的另一个例子。引用JLS §15.28

  

String类型的常量表达式始终是" interned"以便使用String.intern方法共享唯一实例。

答案 1 :(得分:0)

程序中的每个字符串都有一个匹配的键。

如果在连接之后创建了一个与已经存在的字符串文字相匹配的字符串,那么它们都是相同的并且指向相同的值。

答案 2 :(得分:0)

回答内联

public static void main(String aa[])
    {
        String hello="Hello",lo="lo",hel="Hel";
        System.out.println(other.hello=="Hel"+lo); // returns false because new string is created
        System.out.println(other.hello==hel+lo); // returns false, same reason. Right
        System.out.println(other.hello=="Hel"+"lo"); // returns true, because "hel" + "lo" will be resolved to "hello" during compile time. So, Since "Hello" has already been added to the String constants pool, the reference to the same will be used here.
    }