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");

The Output of the above program is as below:


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

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.