This is to add an illustration to Eran's great answer. The following assumes "aa"
is not interned prior to the execution of the code (implicitly or not):
String s1 = new String("a") + new String("a");
s1.intern();
String s2 = "aa";
System.out.println(s1 == s2); //true
String s3 = new String("a") + new String("a"); //same text
s3.intern();
System.out.println(s3 == s2); //false
Both s1
and s3
have the same text ("aa"
), so the difference in actual text doesn't make the difference. The second call to .intern()
simply didn't result in s3
being put in the pool (because the pool already contained the text "aa"
, which was the result of s1.intern()
), explaining why ==
returns false between s3
and s2
.
In short, it means that "11"
was interned prior to the execution of your test3()
method.
And for an additional test, move String s2 = "aa";
to the beginning of the code (both comparisons return false
, for the same reason - although this may be version or implementation-dependant)