by BehindJava

Why String is Immutable or Final in Java

Home » java » Why String is Immutable or Final in Java

In object-oriented programming, the immutable string or objects are that cannot be modified, Once it is created. But we can only change the reference to the object.

We restrict to change the object itself. The String is immutable in Java because of the security, synchronization and concurrency, caching, and class loading. The reason of making string final is to destroy the immutability and to not allow others to extend it.

The String objects are cached in the String pool, and it makes the String immutable. The cached String literals are accessed by multiple clients. So, there is always a risk, where action performs by one client affects all other clients.

For example, if one client performs an action and changes the string value from Pressure to PRESSURE, all remaining clients will also read that value. For the performance reason, caching of String objects was important, so to remove that risk, we have to make the String Immutable.

The string is immutable means that we cannot change the object itself, but we can change the reference to the object. The string is made final to not allow others to extend it and destroy its immutability.

  • Security Parameters are typically represented as String in network connections, database connection URLs, usernames/passwords, etc. If it was mutable, these parameters could be changed easily.
  • Synchronization and Concurrency making String immutable automatically makes them thread safe thereby solving the synchronization issues.
  • Caching when compiler optimizes our String objects, it seems that if two objects have the same value (a =” test”, and b =” test”) and thus we need only one string object (for both a and b, these two will point to the same object).
  • Class loading String is used as arguments for class loading. If mutable, it could result in the wrong class being loaded (because mutable objects change their state).


public class StringImmutableDemo {
   public static void main(String[] args) {
      String st1 = "Behind";
      String st2 = "Java";
      System.out.println("The hascode of st1 = " + st1.hashCode());
      System.out.println("The hascode of st2 = " + st2.hashCode());
      st1 = st1 + st2;
      System.out.println("The Hashcode after st1 is changed : "+ st1.hashCode());


The hascode of st1 = -594386763
The hascode of st2 = 77292912
The Hashcode after st1 is changed : 962735579