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.
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.
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
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…