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");
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:
So what's happening?
In this a object of
KitKat is created inside String Constant pool and all three variables
chocolate3 are pointing to it.
Now if we change cholocate3 to MilkyBar
Suppose if the string were mutable then without creating a new object the value of
chocolate3 would have changed from
MilkyBar.But don't you think this would also change the value of
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.
Top comments (2)
A couple of minor additional details:
The action of caching Strings in a shared pool is technically called interning string literals where "to intern" means "to cache in a pool that the String class stores internally" and "string literal" means "a unique instance of a String (like "Hello")."
I'm not sure if I am misreading the last line but the reason for interning string literals is explicitly to optimize for safely sharing String values in a given JVM. There should be no possible negative side effects as a result.
JSR 3.10.5 is a great reference for more detail.
Also it's important to point out the HashCode Caching, because String is also used in hash implementations (HashMap, HashSet).
String immutability guarantees that their value won't change.