String is immutable or final in Java

String is immutable or final in Java?

One of the Interviewers favourite question, How String plays an important role in every program, similarly in every interview questions on String will be there 🙂 😉 .

Let’s check the reasons behind why String is immutable of final.

  • Security: String is used in many places like in loading Java classes i.e. to load the JDBC driver

Class.forName (“com.mysql.jdbc.Driver”), if String is mutable then attacker can load his own class instead of Driver class which exposes your data.

For opening a new database connection, String is used to store database URL, opening a file by passing name of file, opening network connection, if String is not immutable, a connection or file would be changed and lead to serious security threat.

  • String Pool:String Pool is a special storage used to store Strings in Java Heap Memory. When a new String is created if it exists in pool it will return its reference else it will create new String in pool and returns the corresponding reference.

String s = “Test”;

String s1 = “Test”; following will create only one string object in heap memory. If String is mutable changing the string with one reference will lead to the wrong value for the other references.

  • Performance: Most frequently, we will use the hashcode of string in Java. For example HashMap, 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 is more efficient.
  • Thread Safe: Being immutable String can be shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java i.e. Strings are implicitly thread safe.

Let’s see the disadvantages

Since String is immutable, it creates temporary objects difficult for Garbage collection. Though Strings are separately stored in separate pool called String pool, if we create String using constructor i.e. new String() it will not store in String pool. On average Java application generates too much garbage. String pool is located in PermGen Space of Java Heap, which is very limited as compared to Java Heap. Having too many String literals will quickly fill this space, resulting in java.lang.OutOfMemoryError: PermGen Space. But from Java 7 onwards, they have moved String pool to normal heap space, which is much much larger than PermGen space.

There is another disadvantage of making String final, as it limits its extensibility, we cannot extend String to provide more functionality.

Leave a Reply

Your email address will not be published. Required fields are marked *