Thursday, July 28, 2016

Why string is immutable in java

Strings are immutable; their values cannot be changed after they have been created, while StringBuffer and StringBuilder are mutable.

Java Developers decide Strings are immutable due to the following aspect design, efficiency, security, Class loading and Synchronization.

Design Strings are created in a special memory area in java heap known as "String constant pool". While you creating new String variable it searches the pool to check whether it is already exist. If it is exist, then return reference of the existing String object. If the String is not immutable, changing the String with one reference will lead to the wrong value for the other references.

Security String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. so String is not immutable, a connection or file would be changed and lead to serious security threat. Mutable strings could cause security problem in Reflection too, as the parameters are strings.

Efficiency The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cached without worrying the changes. That means, there is no need to calculate hashcode every time it is used.

Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).

Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.

The String class is a final class.

According to the Java API Documentation the String class declaration is:

public final class String extends Object
implements Serializable, Comparable, CharSequence

Declaring a class as final means that the class cannot be extended by another class. You cannot create a subclass from a final class.
   
Imagine, if Strings are not final, you can create a subclass and instantiate two objects from different classes that can look alike and be seen as Strings but are actually different. This can cause several problems in so many levels.

No comments:

Post a Comment