Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interning strings in Java

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");
    }
}
like image 695
Tiny Avatar asked Dec 19 '22 22:12

Tiny


1 Answers

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.

like image 187
Dawood ibn Kareem Avatar answered Dec 22 '22 10:12

Dawood ibn Kareem