About NewTechnoBuzz
Contact Us

Monday, July 14, 2014

Why String is immutable or final in Java?

There is hardly any java Interview, where no questions is asked from String. This is one of the most popular String Interview questions in Java, which starts with discussion of,
  • What is String?
  • What are immutable objects in Java?
  • What are the benefits of immutable object?
  • And, Why do you use it and in which scenarios do you use it.
Sometimes, it is also asked as "Why String is final in Java". In order to answer these questions, a Java programmer must have a solid understanding of How String works, what are special features of this class and some key fundamentals.

Reasons of Why String is final or Immutable in Java

Though true reasons of why String class was made final is best known to Java designers. I think following reasons also suggest Why String is Final or Immutable in Java.

  • String Pool

    Java designer knows that String will be the most used data type in all kind of Java applications and that's why they wanted to optimize it the from start. One of the key step was to store String literals in String pool. The primary goal of doing this was to reduce temporary String object by sharing them and while sharing, their values should not be changed and that was possible only to make them immutable. You can not share a mutable object with two parties which are unknown to each other.
    Let's take an hypothetical example, where two reference variables are pointing to same String object:
    String str1 = "Hello World";
    String str2 = "Hello World";
    Now, if str2 changes the object from "Hello World" to "Hi World", then the reference variable also got value str2 = "Hi World", which it doesn't even know about it. By making String immutable, this sharing of String literal was possible. In short, the key idea of String pool can not be implemented without making String final or Immutable in Java.
  • Security

    Java provides a secure environment at every level of service and String is critical in maintaining that whole security stuff. String has been widely used as parameter for many Java classes, e.g. for opening network connection, for reading files and directory in Java and for opening database connection. If String was not immutable then it can pose serious security issues like
    • A user might have granted to access a particular file in system, but after authentication he/she can change the PATH to something else, this can cause serious security issues.
    • While connecting to database or any other machine in network, mutating String value can pose security threats.
    • Mutable strings could also cause security problem in Reflection as well, as the parameters are strings.
  • Multithreading

    Since String is immutable it can safely be shared among many threads ,which is very important in multithreaded programming environment and to avoid any synchronization issues in Java. Immutability also makes String instance thread-safe, 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.
  • Optimization and Performance

    Now when you make a class Immutable, you know in advance that, this class is not going to change once created. This guarantee performance optimization e.g. caching because being immutable in Java, it caches its hashcode, and do not calculate every time we call hashcode method of String. This results in good performance gain, given String is heavily used in hash based Maps e.g. Hashtable and HashMap. Caching of hashcode was not possible without making it immutable and final, as it depends upon content of String itself.
  • Class Loading Mechanism

    It is heavily used in class loading mechanism. So if been not Immutable, an attacker can take advantage of this fact and a request to load standard Java classes e.g. java.io.BufferReader can be changed to malicious class com.unknown.CustomDataStolenReader. By keeping String final and immutable, we can at least be sure that JVM is loading correct classes.

Cons of String being Immutable or Final in Java

We have gone through the pros of String being immutable in java, but there are some cons also. In this section, we'll look at some of the cons also if you don't handle it properly.

Since String is immutable, it generates lots of temporary use and throw object, which creates pressure for Garbage collector. Java designer has already thought about it and storing String literals in pool is their solution to reduce String garbage.But still you have to be careful to create String objects. Also, on an average a Java application generates too much garbage. As String pool is located in PermGen Space of Java Heap, which is very limited as compared to Java Heap and having too many String literals will quickly fill this space, resulting in java.lang.OutOfMemoryError: PermGen Space.

We have gone through the pros of String being immutable in java. But, I believe there can be some more convincing reasons as well.
Please post those reasons as comments and I will include those on this post.

Free Search Engine Submission