String Concatenation Creates New Objects
What you'll learn: You'll understand why every string concatenation operation in Java produces a brand-new String object rather than modifying the original.
Since strings are immutable (as you learned in the previous lesson), any operation that appears to "change" a string must actually create a completely new object. This is especially important to understand with concatenation—the most common string operation.
How Concatenation Works Under the Hood
When you use the + operator or the concat() method on strings, Java doesn't alter the existing string. Instead, it:
- Allocates memory for a new
Stringobject - Copies the contents of the original string(s)
- Appends the new content
- Returns a reference to this brand-new object
The original strings remain unchanged and continue to exist in memory (until garbage collected).
Why This Matters
Consider this code:
String greeting = "Hello";
greeting = greeting + " World";
What actually happens:
"Hello"is created andgreetingpoints to it- A new
Stringobject"Hello World"is created greetingnow points to the new object- The original
"Hello"object remains in memory, unchanged
The Performance Impact
If you concatenate strings in a loop, you're creating many temporary objects:
String result = "";
for (int i = 0; i < 1000; i++) {
result = result + i; // Creates 1000 new String objects!
}
Each iteration creates a new String, copies all previous content, and adds the new number. This is inefficient for repeated concatenations.
Key Takeaway: String concatenation with + or concat() always creates new String objects due to immutability—the original strings are never modified. This has important implications for performance when concatenating repeatedly.