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.
EDIT:
The whole code:
package test;
public final class Test
{
public static void main(String... args)
{
String str11="my";
String str12="string";
String concat11=str11+str12;
concat11.intern();
System.out.println(concat11=="mystring");
String str1="str";
String str2="ing";
String concat1=str1+str2;
concat1.intern();
System.out.println(concat1=="string");
}
}
If you run both of these snippets in the same program, then concat1.intern()
will add concat1
to the pool of interned strings. But concat11.intern()
won't add anything to the pool, because "string"
is already in the pool (from str2
). So your last comparison is comparing concat11
to str2
- and these are not the same object.
From the Javadoc at http://docs.oracle.com/javase/6/docs/api/index.html?java/lang/String.html
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With