5

Why String is Immutable in JAVA? What exactly does it mean?

 2 years ago
source link: https://dev.to/tishaag098/why-string-is-immutable-in-java-what-exactly-does-it-mean-59ki
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Cover image for Why String is Immutable in JAVA? What exactly does it mean?
Tisha Agarwal

Posted on Feb 14

Why String is Immutable in JAVA? What exactly does it mean?

So recently I came across the question, why are Strings Immutable in java?
Before discussing on this, I would first like to tell What are Immutable strings?

Immutable simply means unmodifiable or unchangeable. Once String object is created its data or state can't be changed but a new String object is created.

Before going through this article, I recommend to first know about String Constant Pool

This is how String works:

String str = new String("Tisha");

Enter fullscreen mode

Exit fullscreen mode

This, as usual, creates a string containing "Tisha" and assigns it a reference str.

  str = str.concat(" Agarwal");

Enter fullscreen mode

Exit fullscreen mode

This appends a string " Agarwal" to str. But wait, how is this possible, since String objects are immutable? Well to your surprise, it is.
When the above statement is executed, the VM takes the value of String str, i.e. "Tisha" and appends " Agarwal", giving us the value "Tisha Agarwal". Now, since Strings are immutable, the VM can’t assign this value to str, so it creates a new String object, gives it a value "Tisha Agarwal", and gives it a reference str.

Why are strings Immutable?

Let's understand this with the help of an example:

String chocolate1="KitKat";
String chocolate2="KitKat";
String chocolate3="KitKat";

So what's happening?
In this a object of KitKat is created inside String Constant pool and all three variables chocolate1 , chocolate2 , chocolate3 are pointing to it.

Now if we change cholocate3 to MilkyBar
chocolate3=MilkyBar;

Suppose if the string were mutable then without creating a new object the value of chocolate3 would have changed from KitKat to MilkyBar.But don't you think this would also change the value of chocolate1 and chocolate2from KitKat to MilkyBar as shown in the above diagram, these 3 were pointing to the same object.

So, that's why Strings are Immutable,
from the above example, now the chocolate3 will create a different object and will point to it.

Point to Remember

  • Strings are Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple persons there is always a risk, where one person's action would affect all other persons.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK