There are 5 different reasons why String class is made as immutable in Java.
1. String Pool
String literals are stored in a special space which is called String Pool in heap space. Variables that refer to the same object on String Pool would get affected if the String literals were mutable.
For example, let’s say there are two reference variables that are pointing to the same String object.
String str1 = "Hello World";
String str2 = "Hello World";
If String was mutable, str1 would have been able to update the "Hello World" into other words like "HELLO WORLD" , which would directly affect the str2 without noticing.
As String was immutable, the String Pool was able to provide the same objects every time.
2. Security
String has been widely being used for URL paths, database links, file paths, and so on. If String was mutable, user who passed the authentication would have been able to change the paths or network connections which could cause serious security threats.
3. Class Loading Mechanism
As Java’s class loading mechanism heavily depends on String, if String was mutable, the packages or classes names that we use to load libraries/classes would have been vulnerable to the attackers. For example, a request to load standard Java classes like java.io.Reader could have been changed to a malicious classes like com.unknown.DataStolenReader.
4. Multithreading Benefits
For multi-threading and concurrency, the String class should be immutable so that the synchronization can be kept.
5. Optimization and Performance
As String is immutable, the hashcode of the String which depends on the content would be the same on multiple invocations. Therefore, hash based Maps like Hashtable or HashMap uses String as a type of key and whenever the key is called, it caches the returned value which improves the performance.

Leave a comment