-1

How is the following returning 'false'?

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

From what I understand,

  1. String "123" is created in string pool and assigned to 'a'
  2. String "456" created in pool and further "123456" created in the pool and 'a' starts referencing it.
  3. When 'b' is created for the value "123456"; JVM would discover an existing String "123456" in String pool and 'b' will also refer it.

Hence it should return true!

Where am I going wrong?

SMagic
  • 317
  • 2
  • 10

2 Answers2

2

This line: a = a + "456"; will create a new object in a heap (you are concatenating) and assign it to a, that's why you get false. You can call intern method (which place string from heap to pool): a.intern() == b and then it will be true.

Ibrokhim Kholmatov
  • 1,079
  • 2
  • 13
  • 16
1

Here in your example ,

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

Satish Kumar
  • 110
  • 1
  • 11