What Immutability Means for Strings
You'll learn why Java String objects cannot be changed once they're created and what this means for your code.
The Core Idea
In Java, immutability means that once a String object is created in memory, its character sequence is permanently fixed. You cannot modify, add, remove, or replace any characters in that specific object. When you appear to "change" a string, Java is actually creating a brand new String object with the modified content—the original remains untouched.
Why This Matters
Think of a String like a sealed envelope with a message inside. Once sealed, you can't open it and change the message. If you want different text, you must create a new envelope with the new message. The old envelope still exists unchanged.
String original = "Hello";
String modified = original.concat(" World");
// "Hello" still exists in memory unchanged
// "Hello World" is a completely separate new String object
System.out.println(original); // Still prints "Hello"
System.out.println(modified); // Prints "Hello World"
The Memory Implication
Every operation that appears to modify a string—concat(), toUpperCase(), replace(), substring()—returns a new String object. The original string's character data never changes in memory. This is safe for multi-threaded environments and enables string pooling optimizations, but it also means excessive string modifications can create many temporary objects.
String s = "Java";
s.toUpperCase(); // Creates new String, but result is lost
System.out.println(s); // Still prints "Java"
s = s.toUpperCase(); // Now s references the new "JAVA" object
System.out.println(s); // Prints "JAVA"
Key Takeaway: Strings in Java are immutable—once created, their character data cannot be changed; all "modification" operations create and return new String objects instead.