Friday 4 November 2016

Java Source World: Why Strings are Immutable in Java


Why Strings are Immutable in Java


String pool is a special storage area in method area. 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 str1 = "Java Source World";


            String str2 = "Java Source World";




Here is how it works,  str1 and str2 are string reference variables.                        

  
                                                                             
                                                                                              Fig:  String object on heap.


If string is not immutable, changing string with one reference will lead to the wrong value for the other references.


Caching hashcode:


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. This is more efficient.


Security:


String is widely used as parameter for many java classes.ex: network connection, opening files, etc. If were strings not immutable, a connection or file would be changed and lead to serious security thread. the method thought it was connecting to one machine, but was not.mutable strings could cause security problem in reflection too,as the parameters are strings.


Immutable objects are naturally thread safe:


Because immutable objects cannot be changed, they can be shared among multiple threads freely.this eliminate the requirements of doing synchronization.

In summary, string is designed to be immutable for the sake of efficiency and security. This is also the reason why immutable classes are preferred in general.




You may like the fallowing posts:
How Hashmap works in java


                                                                              Java Source World                   A Java quick reference blog

No comments:

Post a Comment