Core Java Fundamentals ยท Strings & Objects

Java Strings: Creation and Immutability

A deep dive into how Java strings are created, stored in memory, and why they are immutable.

StringDemo.java

public class StringDemo {
    public static void main(String[] args) {
        // Part 1: String Creation
        String s1 = "Java";
        String s2 = "Java";
        String s3 = new String("Java");

        System.out.println("--- Creation & Comparison ---");
        System.out.println("s1 == s2: " + (s1 == s2));
        System.out.println("s1 == s3: " + (s1 == s3));
        System.out.println("s1.equals(s3): " + s1.equals(s3));

        // Part 2: Immutability
        String s4 = "Hello";
        System.out.println("\n--- Immutability ---");
        s4.concat(" World");
        System.out.println("s4 after concat (no assignment): " + s4);

        s4 = s4.concat(" World");
        System.out.println("s4 after concat (with assignment): " + s4);
    }
}

Step by step

  1. We declare a String variable s1 and assign it a string literal "Java". The JVM checks the String Constant Pool (SCP). Since "Java" is not there, it gets created in the SCP, and s1 now refers to it.
  2. Next, we declare s2 and assign it the same literal "Java". The JVM checks the SCP, finds "Java" already exists, and makes s2 refer to the *same* memory location as s1. No new string is created.
  3. Here, we use the new keyword. This forces the JVM to create a new String object on the Heap, even though "Java" is already in the SCP. So, s3 refers to a completely different object than s1 and s2.
  4. Printing a separator to the console for clarity.
  5. The == operator compares memory ides (references). Since s1 and s2 point to the exact same object in the SCP, this evaluates to true.
  6. Now we compare s1 (in SCP) with s3 (in Heap). Since they are two different objects in different memory locations, the == operator returns false.
  7. The .equals() method compares the actual character sequence of the strings. Since both s1 and s3 contain "Java", this returns true. This is the correct way to compare string content.
  8. We create a new string s4 with the value "Hello". This demonstrates the concept of immutability.
  9. Printing another separator to the console.
  10. This is the key to immutability. s4.concat(" World") creates a brand new string "Hello World" in memory, but the result is not assigned to any variable. The original string s4 remains unchanged.
  11. When we print s4, we see its value is still "Hello", proving that the previous concat operation did not modify s4.
  12. To actually change the value associated with s4, we must re-assign the result of the concat operation back to s4. Now, s4 points to the new "Hello World" string object.
  13. Finally, we print s4 again. This time it shows the new value "Hello World" because its reference was updated in the previous step.