Rajinder Menu

Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

String Pool in Java



String pool is a pool of string literals which is maintained by java.lang.String class. This pool contains distinct String literals with no two String literals having same value.

Thus a string literal having value “myfriend” can’t exist twice in String pool. There would be only one String literal in a String pool whose value can be “myfriend”.

The main purpose of the presence of String pool is to save memory and increase performance by preventing the creation of  new String objects for those String literals in your code that are already present in the String pool. Thus String pool contains String literals (aka references to String objects) which get shared at many places in your code.


Note that any String literal in your code represents a reference to a String object having same value as the corresponding String literal has.

When we say String pool is pool of String literals it actually means  it is a pool of references, not the pool of  String objects themselves. String objects themselves are on the heap.

How String pool works?
What happens is that whenever a String literal is encountered in your program, then instead of creating a new String object for that literal, JVM first check whether there is any String literal with the same value already exists in String pool. If there is a string literal with the same value already present in the pool, then instead of creating new String object for that encountered String literal in your code, String literal from the pool is used. If there does not exists any string literal with the same value in the pool then a new String object is created, its reference is stored into the string pool and returned.

Consider this program:

public class PoolDemo{
    public static void main(String[] args){

       String firstString = "Hello"; 
       String secondString = "Hello";
       System.out.println(“Hello”);
    }
}

In the above program there are three occurrences of string literal “Hello”. Each occurrence of “Hello” represents an object of String class.

Now suppose String pool does not have any string literal with value “Hello” in it.

Had there not been the string pool, then there would be three different objects of String class containing same value occupying their own memory, like:



But with string pool all three occurrences of “Hello” will point to the same single String object, not the three distinct objects.

When first time “Hello” is referenced in String firstString = "Hello";, JVM will check whether there is already any String literal in the pool with value “Hello”. As we have assumed our string pool does not contain literal “Hello”, a new String object will be created with value “Hello” and its reference is stored into the pool. The reference to this newly created object is returned and assigned to firstString.

When you reference “Hello” second time in String secondString = "Hello"; then again JVM will check the string pool. As now there is already a string literal with same value (“Hello”) present there (just added before), so no new String object is created but the reference to already present object is shared and assigned to secondString .

Same thing happens when you reference the “Hello” third time in System.out.print(“Hello”);, no new object created but reference to “Hello” in String pool is shared.

Now all three occurrences of “Hello” points to single “Hello” object in String pool.



As instead of three different objects now there is only one String object with value “Hello”, it saves memory.

Whether firstString and secondString in above program points to same String object or not can be checked as:

public class PoolDemo{
 public static void main(String[] args){

 String firstString = "Hello";
 String secondString = "Hello";

 //Following line will print true     
 System.out.println(firstString==secondString);
 }
}

firstString == secondString giving result as true means that both firstString  and secondString refer to same String object.

Not every String object goes to String pool…

 String objects can be created in two ways:

1)   String first=”Hello”;

2)   String other=new String(“Hello”);

String objects created by “new”never goes to string pool. Therefore first is pointing to a String object whose reference is in the String pool while other is pointing to String object whose reference does not lie in the String pool.


We can check this by:

public class PoolDemo{
    public static void main(String[] args){

       String first = "Hello"; 
       String other = new String("Hello");

       //Following line will print false
       System.out.println(first==other);
    }
}

first==other comes out false this means that first and other do not point to the same object.

Though strings created “new” do not go to pool, you can store their references in pool by using intern() method of String class.
Interned String means String literal that resides in String pool.

String created as String s=”Hello”; are automatically interned.

While strings created by “new” needs to be explicitly interned if you want them to get stored in string pool

public class PoolDemo{

    public static void main(String[] args){

        String anObject = new String("abc");
        String otherObject =anObject.intern();
 
       //Following line will print false
       System.out.println( anObject == otherObject);
     }
}

anObject does  not represent a String object whose reference is in the String pool. While otherObject represents a String object whose reference is in String pool with same value “abc”. 

Both are different objects as you can see from the result of anObject == otherObject which print false.



Now take this example.

For example:

public class PoolDemo{

    public static void main(String[] args){

       String first = "Hello"; 
       String second = new String("Hello");
       String third=second.intern();

       //Following line will print true
       System.out.println(first==third);
    }

}

second does not represent a String object of pool while first represent a String object in pool. When we called second.intern() what happened is that JVM will try to create a new String object having value “Hello” to store in String pool. But there already presents a String literal there with the same value created by
 String first = "Hello";. So instead of creating new String object it will return the reference of that object from String pool and store it in third. Thus both first and third now points to same object as shown below:




I would like to know your comments and if you liked the article then please share it on social networking buttons.



You may like:
 String Pool is possible due to String immutabilty





String Pool is possible due to String Immutability



String pool in java became possible due to the immutability of the String. The purpose of String pool is to reduce the creation of new String objects in code and this is achieved by sharing the String literals in the String pool at different places in the code. If String were to be mutable, change to a particular String literal at one place would be seen at all other places where this String literal is being used. Thus change at one place would spoil the other parts of code.

If you have not gone through the String pool you may refer String Pool.

Consider this example:

public class StringImmutabilty{
    public static void main(String s[]){
        
        String myName="Humpty Dumpty";
        String yourName="Humpty Dumpty";

        System.out.println("My name is :"+myName);
        System.out.println("Your name is also :"+yourName);
        
        System.out.println("I AM GOING TO CHANGE MY NAME :");

        //Now myName changes to “Dumpty Dumpty”
        myName=myName.replace("Humpty","Dumpty");

        System.out.println("AFTER CHANGE");
        System.out.println("My name is :"+myName);
        System.out.println("Your name is :"+yourName);

    }

}

Output:

My name is :Humpty Dumpty
Your name is also :Humpty Dumpty
I AM GOING TO CHANGE MY NAME :
AFTER CHANGE
My name is :Dumpty Dumpty
Your name is :Humpty Dumpty

In the above code myName and yourName both have same value as String literals so both point to same String object whose reference lies in String pool as shown in following figure:


Now myName has been changed to “Dumpty Dumpty” by

myName=myName.replace("Humpty","Dumpty");


If String were to be mutable, it would also change the value of yourName which is not desirable as we do not want to change yourName.

Since String is immutable it would not change the value of yourName, instead it will create a new String object with value “Dumpty Dumpty” and put its reference in myName as shown in following figure:



Thus due to the String immutability changes at one place to the shared String literal in String pool do not effect other places where there String literal is also being used.



I would like to know your comments and if you liked the article then please share it on social networking buttons.