Monthly Archives: March 2015

String Literal versus String Object

Strings are a special type of object in Java. Unlike C++, Strings in Java are character arrays and not necessarily end with a newline character.

So, what is a String literal ?

String a=”abcd”;

When this happens, a pool in the heap is created and “abcd” is stored in it. a now refers to that location in string pool.

String b=”abcd”;

When we write this line, b will refer to the same location in the string pool as a is referring.

Hence the following code would return true, as == checks for content equality and equals checks for object equality.

if (a==b && a.equals(b))

return true;


return false;

Now what happens when we use the new keyword.

String c=new String(“abcd”);

This creates a new object and a separate place not referring to the string pool.

Hence the following code returns false as a and c and not the equal objects.

if (a==c && a.equals(c))

return true;


return false;

Happy coding..  🙂