Why String is immutable in Java?

UPDATED: 23 December 2014
String objects are cached in String Pool and shared between multiple thread so it will lead to risk of value changed by one thread will affect value of other thread.

Example
/**
 * Find "abc" in String Pool or create new Object.
 * Say its reference is "R"
 */        
String str = "abc";
/**
 * Find "abc" in String Pool or create new Object.
 * Its already available in String Pool [Reference "R"].
 * This will point the same value in String Pool
 */
String str1 = "abc";
/**
 * Find "abcxyz" in String Pool or create new Object.
 * Now str is pointing only "abcxyz" in String Pool and "str1" is pointing to "abc".
 */
str = str + "xyz";

Graphical Representation

Why String is immutable in Java
Initial State
Why String is immutable in Java
After modification of str
Now consider what happen if String is mutable. When we change value of str by str = str + "xyz". It will also change value of str1.

This is why creator[Lee Boynton, Arthur van Hoff taken from class file] of String class marked String class as final. To make sure no one can override behaviour of String class.

Why String is immutable or final in Java?
As explained in example you can understand the reason behind the immutability of String. To understand it with real world example like...

#1 String is used in simple HelloWorld program and also used in complex program of space so it has to maintain its value.
#2 String is used to pass values between method.
#3 String is used with many other programs like File(IO operation), Network Program, etc...

This is one of the popular Interview question and asked in any interview of java for fresher of experienced. If I missed something important please do share your comments.

0 comments :