What is immutable String Object?

What is immutable String Object?

Immutable String Object



We have heard lot of times that String objects are immutable, but what really immutability means?
When we create String object and assign some value to it, it is frozen, we cannot change that value again. So we call it as immutable objects as its value never changes. Now let’s explain immutability property of String object with an example

Suppose we have String object
String test = “test”;
















And we need to concatenate the String with “more ”
 test.concat(“ more”);



















But if we try to print the above statement using system out then it will print only “test” , as we cannot change the value of the String object, but we can change the value of reference variable.

String testMore = test.concat(“ more”);


















So if we try to print testMore it will print the correct string we want. But in above case there are 3 objects gets created one is for “test”, one is for “ more” and one is for “test more”.

String immutability and String Constant Pool



String Constant Pool :



As we all know String literals occupy large portion of memory. To achieve more memory efficiency , Java Virtual Machine has special area of memory called the “String constant pool”.

What does String Constant Pool do?



Whenever we create a String object, it gets placed in String Constant Pool. So again when compiler finds the String, it checks it in the String Constant Pool, if compiler finds it in the String constant pool, then the reference of new String object is directed to the existing String object, so here in this case existing string as just additional reference. If new String object doesn’t found in String Constant Pool , then it creates new String literal object and places it in String Constant Pool.

Why immutability property better for String Constant Pool?



As we seen above String literal in String Constant Pool can have multiple references, so if any one of the changes then it can affect all the reference. Because of immutability the String literal remains always constant.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment