Interning strings in Java
- by Tiny
The following segment of code interns a string.
String str1="my";
String str2="string";
String concat1=str1+str2;
concat1.intern();
System.out.println(concat1=="mystring");
The expression concat1=="mystring" returns true because concat1 has been interned.
If the given string mystring is changed to string as shown in the following snippet.
String str11="str";
String str12="ing";
String concat11=str11+str12;
concat11.intern();
System.out.println(concat11=="string");
The comparison expression concat11=="string" returns false. The string held by concat11 doesn't seem to be interned. What am I overlooking here?
I have tested on Java 7, update 11.