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

String Concatenation Creates New Objects

Learn that operations like + or concat() produce new String instances rather than modifying existing ones.

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:

  1. Allocates memory for a new String object
  2. Copies the contents of the original string(s)
  3. Appends the new content
  4. 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 and greeting points to it
  • A new String object "Hello World" is created
  • greeting now 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.