连接String和整个String之间的比较返回false;

时间:2017-11-24 06:39:38

标签: java string object equals

以下内容如何返回“ false ”?

    String a = "123";
    a = a + "456";
    String b = "123456";
    System.out.println((a == b));

据我了解,

  1. 字符串“123”在字符串池中创建并分配给“a”
  2. 在池中创建字符串“456”,并在池中创建“123456”,“a”开始引用它。
  3. 为值“123456”创建“b”时; JVM会在字符串池中发现现有的字符串“123456”,而“b”也会引用它。
  4. 因此它应该返回true!

    我哪里错了?

2 个答案:

答案 0 :(得分:3)

这一行:a = a + "456";将在堆中创建一个新对象(你正在连接)并将其分配给a,这就是你弄错的原因。您可以调用intern方法(将字符串从堆放到池中):a.intern() == b然后它将是true

答案 1 :(得分:1)

在您的示例中,

String a = "123"; //a reference to "123" in string pool
a = a + "456"; // Here as you are concatenating using + operator which create a new String object in heap and now a is referencing a string object in heap instead of a string literal in string pool. 
String b = "123456"; // here b is referencing to string pool for "123456"
System.out.println((a == b)); // This will return false because for the value "123456" a is referencing to heap and b to string pool. Because == operator compare reference rather then values it will return false.

For more details you can read this page