Tuesday 18 February 2014

What is String Pool in Java ? Why String pool needed ?

In Java, String handling is based on a concept called string interning. I computer science, String Interning is a method of storing only a single copy of each distinct string value which must be immutable.

This single copy of each string is called "intern" and the distinct values are stored in a string pool. This method of string interning is supported by some modern object-oriented programming languages including Python, Ruby,Java, .NET, Smalltalk etc. 

String interning makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created.

String Pool

String pool a special memory area with in heap where all string literals are stored.When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created and existing string has additional reference.

String  s1 =  "Hello";   //This statement will keep a string literal in String pool on heap.

String s2 = "Hello";  

When this statement is executed, JVM has again encountered a string literal, so JVM will check the pool to see if an an identical string literal already exist. In this case match is found, hence s2 will have same reference as of S1.  With this, "Hello" string literal has multiple references.
   
String s3= s1; //same reference

 

Now what will happen when String objects are created using new operator ?
 
String s4 = new String("Hello"); //String object created using new

String s5 =  new String("Hello");
As new operator always creates object on heap. In both these cases,each statement creates two String objects one in non pool area on heap and "Hello" string literal is also placed in pool also but only one reference is returned.


why String pool ?

String pool is used to make efficient use of memory and to speed up string related operations like String comparison. As applications grows, it's very common for String literals to occupy large
amounts of a program's memory, and there is often a lot of redundancy within the universe of String literals for a program. To make Java more memory efficient, the JVM sets aside a special area of memory called the "String constant pool."




 

 

No comments:

Post a Comment