As I have understood, whenever we create a String
literal, the pool is checked for any existing String
with the same value. If it exists, a reference to the same is returned. Otherwise a new literal is created.
From this, I understand that pool only contains non-duplicate String
literals.
But I am confused by the output of the following code:
String str1 = "Hello World";
String str2 = "Hello";
String str3 = str2+" World";
System.out.println(str3);
System.out.println(((str1 == str3) ? "equal":"unequal"));`
Since str3
is evaluating to "Hello World"
which already exists in the pool pointed to by str1
, a reference to the same should be assigned to str3
and hence str1
and str3
should be equal.
But the code is showing them as unequal. Would appreciate if someone can explain.