以下内容如何返回“ false ”?
String a = "123";
a = a + "456";
String b = "123456";
System.out.println((a == b));
据我了解,
因此它应该返回true!
我哪里错了?
答案 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.