Why string is immutable in java

Let’s learn why string is immutable in java.

Why string is immutable in java

String is immutable in java because String objects are cached in string constant pool.

String object once created cannot be changed i.e, when object is assigned to variable we cannot update the reference.

If string object is changed then it creates a new string object.

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";
      System.out.println(str);
      str = str.concat(" world");
      System.out.println(str);
      str = str.concat(" java");
      System.out.println(str);
   }
}


Output:

Hello
Hello world
Hello world java


Also read – nested classes in java