Friday 11 March 2016

Why String is immutable in java?

A very well known fact about java's String is that it is immutable. It means that once a String object is created it cannot be modified. Let's understand how?
For example,
String mobile = "Samsung";

Here we can see that a new String object with name Samsung is created and this object is referenced by variable named mobile.
And this object would be stored in a String constant pool

Now change the above example as shown below,
String mobile = "Samsung" + "Duos";
Again a new object is created with name SamsungDuos and is stored in the pool. And mobile variable now has reference to SamsungDuos instead of Samsung. But Samsung object still remains in the pool but with no reference.

Note : We have both Samsung and SamsungDuos object in the String Constant Pool.

-------------------------------------------------------------------------------------------------------------------------
Suppose you again write, say
String company = "Samsung"; && 
String handset = "SamsungDuos";
This time as the Samsung and Samsung Duos object already exist in the pool so the same object would be used instead of creating new object. company would  have reference to Samsung object and Samsung Duos to handset respectively.

Note : Samsung Duos object is now referred by both mobile and handset variable. 
--------------------------------------------------------------------------------------------------------------------------

Think you have got the concept. Then have a look at the below given scenario :
String s1 = "Sita";
s1 += "Ram";
System.out.println(s1);
The above code works. So can you make out what's happening here?
  • At the beginning s1 = "Sita" and in the second line s1 = "SitaRam". So, Is the original String modified? Is the immutability rule violated?
  • And the answer is simply no. Remember what I said in the beginning. Same applies here as well. When you write 
  • s1 = "Sita", a new object Sita is getting created and stored in the constant String pool. And your s1 refers to this String object.
      When you concat Sita with Ram (s1 += "Ram";) at the same time a new String object is created and your variable s1 now refers to this object.
So overall concept is the string object is not getting modified rather when concatenation occurs a new object is created and the old reference changes to new one. Thus String object remains immutable throughout the journey after creation.


Another Example:


Java Radar



Advantages of String's immutability :

  • Existing object in the heap is referred by number of variables thus saving lot of memory space and relieving java from the task of creating new object again and again if it already exists in constant memory pool (clearly explained above). 
  • Due to immutable nature, the hash code of the String doesn't change and thus can be cached easily.
  • Due to immutable nature, String objects are naturally thread safe.



You may also want to know about :


5 comments:

  1. So if you have concatenated, and if, when concatenation occurs a new object is created and the old reference changes to new one. Is there a way to access the original object? if s1 references "SitaRam", is the immutable "Sita" accessible in anyway?

    ReplyDelete
    Replies
    1. In the screenshot that I have attached in Another Example section of the article, there you can find that "Sita" is still accessible with s1 variable.
      For better understanding, see this explanation as well which is just above the screenshot example in the article:
      String s1 = "Sita";
      s1 += "Ram";
      System.out.println(s1);

      here s1 after concat changes to "SitaRam" but not in the screenshot example.
      If still any doubt persist, we can discuss further.

      Delete
  2. I have a query:

    String s1 = "Sita";
    s1 += "Ram";
    System.out.println(s1);

    Considering the previous lines, if I decide to change the value of the variable s1:

    String s1 = "Sita";
    s1 += "Ram";
    s1 = "Simon";
    System.out.println(s1);

    Is this considered a good practice? The Program runs, so... Am I adding Simon to the String constant pool or just changing the value? What happend to Sita and SitaRam?

    Im sorry I find all of this a bit confusing. Thanks for your time, love your articles.

    ReplyDelete
  3. System.out.println("s1 + " new string "+ s2);
    Cloud you please explain...
    How many object we be created on
    string constant pool

    ReplyDelete

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.