Skip to content

Why String is immutable?

Aparna edited this page Aug 15, 2017 · 4 revisions

String pool

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.

Security

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.

Efficient caching of hashcode

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.

Thread safe

Since String values cannot be changed, it can be shared among multiple threads.

Thus avoids the need of doing synchronization.

Clone this wiki locally