String Methods Return New Instances
What you'll learn: You'll understand why every String method that appears to "modify" a string actually returns a brand-new String object instead.
The Core Idea
Because Strings are immutable (unchangeable), methods like toUpperCase(), substring(), replace(), and trim() cannot alter the original String. Instead, they construct and return entirely new String objects containing the modified text. The original String remains exactly as it was.
Why This Matters
This behavior is a direct consequence of immutability. Think of a String like a printed photograph: you can't change what's on it. If you want a different version—say, a cropped version or one with adjusted brightness—you must create a new photograph. The original stays in its frame, untouched.
String original = "hello";
String upper = original.toUpperCase();
System.out.println(original); // "hello" - unchanged!
System.out.println(upper); // "HELLO" - new object
Common Methods That Return New Instances
toUpperCase()/toLowerCase(): Returns a new String with case changedsubstring(int start): Returns a new String containing a portion of the originalreplace(char old, char new): Returns a new String with replacements appliedtrim(): Returns a new String with whitespace removed from endsconcat(String str): Returns a new String combining both
The original String is never modified. If you don't assign the result to a variable, the new String is simply discarded.
String text = " Java ";
text.trim(); // ⚠️ MISTAKE: Result ignored!
System.out.println(text); // " Java " - still has spaces
text = text.trim(); // ✅ CORRECT: Assign to capture new instance
System.out.println(text); // "Java"
Key Takeaway: All String transformation methods return new String objects—the original is never mutated. Always capture the returned value if you need the modified version.