-
Notifications
You must be signed in to change notification settings - Fork 0
Why String is immutable?
String pool is a special storage area in Java Heap. When a String is created and if it already exists in the pool, the reference of the existing pool is returned, instead of creating a new object and returning a new object and returning its reference.
For example: if we create a String with a value "newString", then it will see if already exists in the String pool, it it exists, it will return that rather than creating a new string and return its reference. If we change the value of a String, the value at the reference is not changed, rather the reference is changed to point to the particular string.
If string is not immutable, changing the string would affect the other strings that point to that reference.
For different applications, String is used to store various details like username/password, connection parameters like host/port etc. If String is mutable, then these details can be easily changed which will be a security threat.
In Java, hashcode of strings are frequently used. So if Strings are immutable, the hash code will remain same and it can be cached.
Hence avoids the need in recalculation of hash code whenever it is used.
Since String values cannot be changed, it can be shared among multiple threads.
Thus avoids the need of doing synchronization.