Why String is Immutable and Final in Java

In java, string objects are immutable because String objects are cached in String pool. Immutable simply means unmodifiable or unchangeable means once string object is created its data or state can't be changed but a new string object is created. JVM has string pool which shared between multiple clients so there is always risk of modification by one client can affect all other clients.

It is very important and popular question of java interview, why String is immutable in Java? it is one of the most frequently asked String Interview questions in Java, String class very important class of java and there lots of uses, string class has many benefits because immutable object.

String Pooling requirement
Suppose one client has a string object with value "java" if this client changes the value of String "java" to "JAVA" then all other clients will also see that changed value. As we know JVM provide String pool system to cache the string value for performance reason this risk was avoided by making String class Immutable.

The following code will create only one string object in the heap.
String str1 = "java";
String str2 = "java";
Here is how it looks:

Why String is Immutable

If a string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

Hashing Requirement i.e. caching HashCode
One more thing about string class, it is final class so that no one can override or inherit of String class e.g. Immutability, Caching, hashcode calculation etc by extending and overriding behaviors. Another reason of why String class is immutable could die due to HashMap.

In the HashMap, we can use string as Key of map, even it is very popular to use as key of HashMap. So it is one more reason of string immutablity because we can retrieve the value object which was stored in HashMap via key any where. Since HashMap works in the principle of hashing, which requires same has value to function properly. If suppose string is a Mutable class then String would produce two different hashcodes at the time of insertion and retrieval if contents of String was modified after insertion, potentially losing the value object in the map.

String use in Security
There lots of cases where we use String class widely as a parameter for many java classes, e.g. database connection setting, network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to a serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause a security problem in Reflection too, as the parameters are strings.