连接字符串和整个字符串之间的比较 returns false;
Comparison between concatenated String and whole String returns false;
下面的 return 是如何“false”的?
String a = "123";
a = a + "456";
String b = "123456";
System.out.println((a == b));
据我了解,
- 字符串“123”在字符串池中创建并分配给'a'
- 在池中创建字符串“456”,并在池中进一步创建“123456”,'a' 开始引用它。
- 当'b'为值“123456”创建时; JVM 会在字符串池中发现一个现有的字符串“123456”,'b' 也会引用它。
因此它应该 return 正确!
我哪里错了?
这一行:a = a + "456";
将在堆中创建一个新对象(您正在串联)并将其分配给 a
,这就是您得到 false 的原因。您可以调用 intern
方法(将字符串从堆放到池中):a.intern() == b
然后它将是 true
.
在你的例子中,
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.
下面的 return 是如何“false”的?
String a = "123";
a = a + "456";
String b = "123456";
System.out.println((a == b));
据我了解,
- 字符串“123”在字符串池中创建并分配给'a'
- 在池中创建字符串“456”,并在池中进一步创建“123456”,'a' 开始引用它。
- 当'b'为值“123456”创建时; JVM 会在字符串池中发现一个现有的字符串“123456”,'b' 也会引用它。
因此它应该 return 正确!
我哪里错了?
这一行:a = a + "456";
将在堆中创建一个新对象(您正在串联)并将其分配给 a
,这就是您得到 false 的原因。您可以调用 intern
方法(将字符串从堆放到池中):a.intern() == b
然后它将是 true
.
在你的例子中,
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.