As per the following How Java String pool works when String concatenation? conversation,
String a = "hello world!";
String b = "hello" + " world!";
boolean compare = (a == b);
The compare
should be true which is correct.
However, I've the following code
String s1 = "This is";
String s2 = " a new String";
String s3 = s1 + s2;
String s4 = "This is a new String";
On comparing System.out.printf("s3 == s4:%s\n", s3 == s4);//always false
It is always false. My understanding is that on concatenation of s1
& s2
, s3
will create a string in pool and when s4
is created it will point to the same pool location. But this is not the case. I've tried this with different JDKs including 7, 8 and 14 and the results are consistent.
This is how the behaviour regarding pooling strings is specified in the Java Language Specification (emphasis mine):
[...]
Moreover, a string literal always refers to the same instance of class
String
. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the methodString.intern
.
Only constant expressions of type String
are pooled. "This is a new String"
, and "hello" + " world!"
are constant expressions. The compiler can evaluate these expressions at compile time. s1 + s2
is not a constant expression.
So when executing s1 + s2
, a new string is created. But note that another string, which just so happens to have the same characters as the new string, is in the string pool, because you used a string literal to initialise s4
.