Sunday, March 8, 2009

String Literals

I remember my struggle to understand the concept of String Literals and the difference between "==" and .equals() difference during my SCJP exam. There were many questions related to this in almost all the sample questions i went through.
Say there is a string literal, String sL= "Hello";
Another String object created using "new" keyword, String sO=new String("World");
There is a difference in the way a string literal and a string object is stored and processed by JVM.
JVM keeps a list of unique string literals in heap memory. When a string literal is assigned to a variable, JVM checks whether this literal is already there in its list of interned strings and adds it only if it does not exist in this list in heap. If it does exist, the reference variable sL would be assigned the location of this already existing literal value, thereby reducing duplication of literal values.
If we execute say a 100 times String sL1 ="hello";...............String sL100="hello";
There would be only one hello literal stored in heap, and all the 100 reference variables from sL1 to sL100 would be referring to this single literal.

In case of a string object created using a "new" keyword, there is no checking or list involved. It simply creates a string object with the value given with new keyword. It does not bother if there are identical values.
if we execute String sO1=new String(World)...........String sO100=new String("world");
There will be 100 string objs with content value "World"; assigned to each of the 100 references.

Here comes the use of "==" and .equals()
"==" checks if the references point to the same memory location (as in the case of literal references) and .equals() ckecks if the content values in the comparing objects are identical.

But all said we can still make the String objects avoid creating duplicate String objects using the method String.intern(). This would make the string objects to behave like literals by forcing a check for duplicate String objects having same value.

No comments:

Post a Comment