Interning strings in Java
Posted
by
Tiny
on Stack Overflow
See other posts from Stack Overflow
or by Tiny
Published on 2013-10-20T21:50:51Z
Indexed on
2013/10/20
21:53 UTC
Read the original article
Hit count: 313
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.
© Stack Overflow or respective owner