Search This Blog

Why is String immutable ?

Immutable classes are classes whose objects can't be modified once they are created.

1. Immutable String ensures that there is no security threat to Java classes when       used as a parameter for many Java classes like class loading mechanism, network connection, opening files, etc.
2. String pool is a special storage area in Java heap where String objects are typically stored. When a String is created and if the String already exists in the pool, the reference to the existing String will be returned instead of creating a new String.
3.  The hashcode of String is frequently used in Java. Being immutable ensures that the hashcode of the String is cached, not created every time and will always be the same, which makes it more efficient when used as key in HashMap.

No comments:

Post a Comment