Why is string immutable in java

Let’s learn why is string immutable in java.

Why is string immutable in java

String is immutable means String once created its data can’t be changed.

String s = new String("HelloWorld");

If we create String object ‘s’ (as shown above) it creates two objects one in heap area (since “new” keyword is used) and another in String constant pool.

Since we using string literal “HelloWorld” another literal object is created in String constant pool which is referred internally by JVM through reference variable.

Now if we change object value using concat() method,

s.concat(" java");

Here we are changing string object from “HelloWorld” to “java”. But the original value will not be changed. Instead new object is created (in heap area) and its value will be “HelloWorld java”.

Meanwhile string literal object “java” will be created in String constant pool. Hence String object is immutable.

Advantage of String immutable is performance, security, caching and synchronization. Let’s see an example on why string is immutable in java.

public class ImmutableStringExample
   public static void main(String[] args)
      // string literal
      String str = "Hello";
      str = str.concat(" world");
      str = str.concat(" java");


Hello world
Hello world java

Also read – nested classes in java