Leaderboard1

Leaderboard2

Wednesday, May 28, 2014

Why String is Immutable in Java ?

As Java developer, we all know that String is an immutable class. But very few knows that why String is immutable. As String is used vastly in Java application, as parameter in network connection, database url, serialization etc, so for security reasons, memory saving, it's made immutable.

1. String Pool

String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

The following code will create only one string object in the heap.

String string1 = "abcd";
String string2 = "abcd";

2. Cashing String hash code


Being immutable, String provides a constant hashCode. As String is widely used as a key in HashMap, so being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes. That means, there is no need to calculate hashcode every time it is used. This is more efficient.

3. Security

String us used as a parameter in many places, database connections, file opening etc, so mutable Strings cam create huge problems. To support class loading mechanism in which String is used as arguments. String being mutable results in wrong class being loaded.

Please post comments !

No comments:

Post a Comment