Rajinder Menu

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.


No comments:

Post a Comment