Java String Pool

What will the following lines of code print?

1  String a = "abc";
2  String b = "abc";
3  System.out.println(a == b);
4  String c = new String("abc");
5  String d = new String("abc");
6  System.out.println(c == d);

In order to test for equality between two objects, you must use the equals method.  Otherwise, if you test the equality between two variables that point to objects, you’re comparing the value it stores; in this case the address that reference the objects.  As a result, both println statements should both return false, right?  Why does the first println statement (line 3) print true?

It turns out that variables a and b both point to the same object.  This is because both variables reference string literal objects.  A string literal is instead stored in a special area of the Java PermGen heap space called the String Pool.  The String Pool acts as a cache for string literals; If you create a string literal that already exists in the String Pool, Java is smart enough to use the existing reference.

On line 1, when I set the variable a to the literal “abc”, it will store that value in the String Pool.  When I do the same again for variable b, on line 2, it will find the same value in the String Pool and use the reference to the existing object.  Not only does this save memory, but the values of the variables a and b are both equal since they reference the same object.

On the other hand, if we create a String using the new operator (line 4), we will first find the “abc” reference that exists in the String Pool.  This reference will be passed into the String constructor to instantiate a completely new object that now lives in the Java heap space.  After we create two instances of the String object using the new operator (line 5), we have two completely separate instances of the String object.  Therefore the variables c and d reference two completely separate variables.

As you can see, it almost always never makes sense to use the new String(String) constructor.  If for whatever reason you must use this constructor, you may use the String.intern() method to place the object in the String Pool. This method will then return the  reference to the object that lives in the String Pool.

Given what you have just learned, what will the following lines of code print?

System.out.println(c.intern() == d.intern());
System.out.println("a" + "bc" == "ab" + "c");
System.out.println("abcd" == "abc" + "d");

Leave a Reply

Your email address will not be published. Required fields are marked *