Friday 24 June 2011

Strings and String Literal Pool

Strings are immutable


String objects are immutable objects i.e. a string object cannot be changed once it is created. For example in the below code string object is not changed instead a new string object is created on concatenation. So whenever some operations are performed on the String objects a new string object is created.

String s  = "Java ";
s = s.concat("Blog");


String Literal Pool


Whenever a class is loaded, java virtual machine checks for all the string literals in the class and for all the literals it finds whether they are already on the heap, if not a new instance is created on the heap and a reference is stored in the string literal pool. Subsequently any reference to that string literal in the program is replaced with the reference from the string literal pool. 

For example in the below code 

String s1 = "Blog";
String s2 = "Blog";
1. s1.equals(s2) : true
2. s1==s2 : true

the first statement returns true and so the second statement because the second time a new string object is not created instead it is referenced from the String literal pool.


But, in the below code 


String s1 = "Blog";
String s2 = new String("Blog");
1. s1.equals(s2) : true
2. s1 == s2 : false

second statement returned false because java virtual machine is bound to create a new string object no matter it was there in the String Literal Pool. So, avoid using new  when creating a string literal otherwise new string objects are created unnecessarily.

No comments:

Post a Comment