There is code as following:
String s = new String(\"1\");
s.intern();
String s2 = \"1\";
System.out.println(s == s2);
String s3 = new String(\"1\")+new
Here's what's happening:
String s1 = new String("1");
s1.intern();
String s2 = "1";
"1"
(passed into the String
constructor) is interned at address A.s1
is created at address B because it is not a literal or constant expression.intern()
has no effect. String "1"
is already interned, and the result of the operation is not assigned back to s1
.s2
with value "1"
is retrieved from the string pool, so points to address A.Result: Strings s1
and s2
point to different addresses.
String s3 = new String("1") + new String("1");
s3.intern();
String s4 = "11";
s3
is created at address C.intern()
adds the string with value "11"
at address C to the string pool.s4
with value "11"
is retrieved from the string pool, so points to address C.Result: Strings s3
and s4
point to the same address.
String "1"
is interned before the call to intern()
is made, by virtue of its presence in the s1 = new String("1")
constructor call.
Changing that constructor call to s1 = new String(new char[]{'1'})
will make the comparison of s1 == s2
evaluate to true because both will now refer to the string that was explicitly interned by calling s1.intern()
.
(I used the code from this answer to get information about the strings' memory locations.)