4

当我使用双引号将 2 个字符串(+) 运算符连接并与具有相同值的其他字符串文字进行比较时,结果为true .. 但是当我连接 2 个字符串变量并比较时给出 false ?为什么会这样?

据我所知,当我们使用 (+) 运算符连接字符串时,JVM 会返回 new StringBuilder(string...).toString(),它会在堆内存中创建一个新的 String 实例,并在 String pool 中创建一个引用。如果这是真的,它如何在一种情况下返回而在另一种情况下返回假?

第一种情况:

    String string1 = "wel";
    String string2 = "come";
    string1 = string1 + string2; //welcome

    String string3 = "welcome";
    System.out.println(string3 == string1); // this returns false but have same hashcode

第二种情况:

    String string4 = "wel" + "come";
    String string5 = "wel" + "come";
    System.out.println(string4 == string5); // this returns true

有人可以帮我吗?

4

2 回答 2

4

请关注评论。

 string1 = string1 + string2; //StringBuilder(string...).toString() which creates a new instance in heap..

 String string3 = "welcome"; // It is not in heap. 

所以string3 == string1 false

  String string4 = "wel" + "come"; //Evaluated at compile time

  String string5 = "wel" + "come"; //Evaluated at compile time and reffering to previous literal

string4 == string5也是 _true

于 2013-10-21T14:28:18.920 回答
1

As per my knowledge when we concat strings with (+) operator JVM returns new StringBuilder(string...).toString() which creates a new String instance in heap memory

Correct, unless both operands are literals, in which case a single string constant is created at compile time and pooled.

and one reference in String pool.

False. The only things in the String pool are String constants and String.intern() return values.

if that is true

It isn't.

how is it returning true in one scenario and false in other?

Because your premiss is incorrect.

于 2013-10-22T00:56:25.553 回答