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.