Course contentsShow
← Java
Lesson 2174 of 2,87043. String Handling in DepthFree lesson

String Methods Return New Instances

Examine how methods like toUpperCase, substring, and replace always return new String objects.

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 changed
  • substring(int start): Returns a new String containing a portion of the original
  • replace(char old, char new): Returns a new String with replacements applied
  • trim(): Returns a new String with whitespace removed from ends
  • concat(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.