Why String is immutable or final in Java?

Though there could be many possible answer for this question and only designer of String class can answer this , I think below two does make sense

1)Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. “Test” has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say

String A = “Test”
String B = “Test”

Now String B called “Test”.toUpperCase() which change the same object into “TEST” , so A will also be “TEST” which is not desirable.

2)String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.

In case if String is not immutable , this would lead serious security threat , I mean some one can access to any file for which he has authorization and then can change the file name either deliberately or accidentally and gain access of those file. This is some time asked as Why Char array is better than String for Storing password in Java in interviews as well.

3)Since String is immutable it can safely shared between many threads ,which is very important for multi threaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don’t need to synchronize String operation externally. Another important point to note about String is memory leak caused by SubString, which is not a thread related issues but something to be aware of.

4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java.  This one is also suggested by  Jaroslav Sedlacek in comments below. In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.

5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.
Had String been mutable, a request to load “java.io.Writer” could have been changed to load “mil.vogoon.DiskErasingWriter”

I believe there could be some more very convincing reasons also , Please post those reasons as comments and I will include those on this post.

I think above reason holds good for another java interview questions “Why String is final in Java”  also to be immutable you have to be final so that your subclass doesn’t break immutability.  what do you guys think ?

Source : http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html#ixzz2IlmuOgOu

 

 

Advertisements

2 thoughts on “Why String is immutable or final in Java?

  1. Hello JUGs.. ,
    Nice reach n deep article.

    In the 4 you have describe….
    “In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.”

    Suddenly, a confusion/Que aries that..1) Immutable mins final then through out the application can we access this variable(modifiers require) using it’s own hash code ? coz no one can change valus of it.

    2) like in HashMap functionality we have thousand of data so it have consumed heavily space…ok it’s RIGHT ?
    So, when we using “String” as a “Key” in HashMap as mention in first line”no one can change its contents”, A UNIQUE hashcode should generate for that KEY and it point it’s value …………
    So we can(must) access a value Which is override in hash map…(?)
    Can we ?, Why ?, immutability impact on it why or why not ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s