Wednesday 14 February 2018

Why Java declared String as immutable?

The Strings in java are immutable because they are stored in the "String Pool". The basic property of String pool is not to allow the "duplicate strings". 

i.e. if we declare,

String s1="abc"; 
String s2= "abc";

instead of 2 String objects only one String object will be created in String pool as content of both the Strings are equal. Ofcourse, this saves lot of memory at runtime. 

But because of this, there might be possibility that client1 changes the object referred by abc and client2, would get the modified String. So, to avoid this String objects are immutable in Java.

Another reason of why String class is immutable could die due to HashMap.

Since Strings are very popular as HashMap key, it's important for them to be immutable so that they can retrieve the value object which was stored in HashMap. Mutable String would produce two different hashcodes at the time of insertion and retrieval if contents of String was modified after insertion, potentially losing the value object in the map.

At the same time, String was made final so that no one can compromise invariant of String class e.g. Immutability, Caching, hashcode calculation etc by extending and overriding behaviors. 


No comments:

Post a Comment

Attend Online Java Certification Training and excel your career

Hello Java Developer,  Are you staying at home and worried about your future? Do not waste the time in worrying. International certifi...