Home » Core Java » Demo Program On String Immutability

Demo Program On String Immutability

String is an immutable object i.e. once created it can not be modified. If you modify a String, then JVM would create a different String object and would leave the original String object intact.

Let’s take a demo program to understand String immutability.

public class DemoProgram1 {
     public static void main(String[] args) {
         String str = "Hello%World%";
         str.replaceAll("%World%", "_ABC");
         System.out.println(str); 
     }
}

The Output of the above program is as below:

Hello%World%

Had String been not immutable , then the output would have been
Hello_ABC

Since, String is immutable , hence when you try to replace here %World% , then JVM creates a new String leaving the original String intact. And Hence, the output is as above discussed.