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:
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.
String Related Posts
- How to make Immutable Class in Java
- Core Java Interview Questions
- String Class in Java
- Why String is Immutable and Final in Java
- Convert String to Integer to String in Java with Example
- Convert Double to String to Double in Java with Example
- Convert Date to String in Java with Example
- Differences between String, StringBuffer and StringBuilder in Java
- Differences StringBuffer and StringBuilder
- How to Compare two Strings in Java
- Difference between hashCode() and equals() methods in Java
- Java – String substring() Method
- Difference between wait() and sleep()