Thursday 22 November 2012

String Memory, String Pool



String memory

If you use the new keyword, a new String object will be created. Note that objects are always on the heap - the string pool is not a separate memory area that is separate from the heap.

The string pool is like a cache. If you do this:

String s = "abc";
String p = "abc";
 
then the Java compiler is smart enough to make just one String object, and s and p will both be referring to that same String object. If you do this:

String s = new String("abc");
 
then there will be one String object in the pool, the one that represents the literal "abc", and there will be a separate String object, not in the pool, that contains a copy of the content of the pooled object. Since String is immutable in Java, you're not gaining anything by doing this; calling new String("literal") never makes sense in Java and is unnecessarily inefficient.

Note that you can call intern() on a String object. This will put the String object in the pool if it is not already there, and return the reference to the pooled string. (If it was already in the pool, it just returns a reference to the object that was already there). See the API documentation for that method for more info.



 in java for String there is a special consideration, if you are creating a String class object like
String s="jai"
than this will go to string pool and if are again want the same string like
String s2="jai"
than no other object of String class is created now reference variable s2 will refer to "jai"
this is done because String objects are immutable.
and you can check it by == test like
if(s==s2)
this will give the true value and execute if condition.


means when you do any modification on them than another object of String class is created and the reference of that class is gone.like
String s="jai"
s=s.concat(" hai");
now is referring to jai hai and reference to jai string is gone and this object is stored is sting pool. for further use.
like in future we need that object than the new object is not created and by JVM the reference of that object is given to that reference variable.

and if you are creating a object by new operator than always new object is created .
e.g.
String s2="jai".
String s=new String ("jai");
 and now you are doing the == test than this will give false and if condition will not execute.
if(s2==s)
{
//code
}
this will not execute.