Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 14, 2022 08:32 pm GMT

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");

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

  str = str.concat(" Agarwal");

immutable

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 cant 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";

image2

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.

Image3

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.

Original Link: https://dev.to/tishaag098/why-string-is-immutable-in-java-what-exactly-does-it-mean-59ki

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To