Monday, 5 February 2018

Why String is Immutable or Final in Java



The string is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client.
                        For example, if one client changes the value of String "Test" to "TEST", all other clients will also see that value as explained in the first example. Since caching of String objects was important from performance reason this risk was avoided by making String class Immutable. 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. 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. Since HashMap works in the principle of hashing, which requires same has value to function properly. 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.

If you are an Indian cricket fan, you may be able to correlate with my next sentence. The string is VVS Laxman of Java, i.e. very very special class. I have not seen a single Java program which is written without using String. That's why a solid understanding of String is very important for a Java developer.

                                            Important and popularity of String as data type, transfer object and mediator has also made it popular in Java interviews. Why String is immutable in Java is one of the most frequently asked String Interview questions in Java, which starts with discussion of,  what is String, how String in Java is different than String in C and C++, and then shifted towards what is immutable object in Java , what are the benefits of immutable object, why do you use them and which scenarios should you use them. This question sometimes also asked, "Why String is final in Java".


On a similar note, if you are preparing for Java interviews, I would suggest you take a loot at the Java Programming interview exposed book, an excellent resource for senior and mid-level Java programmer.

Why String is Final in Java
                             As I said, there could be many possible answers to this question, and the only designer of String class can answer it with confidence. I was expecting some clue in Joshua Bloch's Effective Java book, but he also didn't mention it. I think following two reasons make a lot of sense on why String class is made Immutable or final in Java: 1) Imagine String pool 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.

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 a string for opening database connection, you can open any file in Java by passing the name of the file as argument to File I/O classes.
3)Since String is immutable it can safely share between many threads which is very important for multithreaded 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 the 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 invocations.


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"

No comments:

Post a Comment