String Concatenation

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Strings in Java are Immutable. Every time you concatenate strings using +, a brand new String object is created in memory.
  • Using + inside a loop creates massive memory overhead and triggers excessive Garbage Collection.
  • Use StringBuilder for appending strings inside loops to ensure high performance and low memory footprint.

Concept

Because String is immutable, evaluating "a" + "b" actually creates a third string "ab".
If you do this in a loop 10,000 times, you are creating 10,000 intermediate, useless String objects that the Garbage Collector must immediately destroy.

StringBuilder solves this by maintaining a mutable internal char[] array. When you call .append(), it simply inserts the new characters into the existing array, resizing it only when necessary. No intermediate objects are created.

Note: Since Java 9, the compiler uses InvokeDynamic and StringConcatFactory to heavily optimize simple + concatenations on a single line. However, it still cannot optimize + across loop iterations.

Examples

public class StringConcatDemo {
    
    // ❌ TERRIBLE PERFORMANCE
    public String buildCsvSlow(List<String> items) {
        String result = "";
        for (String item : items) {
            // Creates a NEW String object on every single iteration!
            // O(N^2) time complexity because it has to copy the entire string every time.
            result += item + ","; 
        }
        return result;
    }
    
    // ✅ HIGH PERFORMANCE
    public String buildCsvFast(List<String> items) {
        // Initializes a mutable buffer
        StringBuilder sb = new StringBuilder(); 
        for (String item : items) {
            // Simply adds characters to the existing array.
            // O(N) time complexity.
            sb.append(item).append(","); 
        }
        return sb.toString();
    }
}

Interview Questions

Q: What is the difference between StringBuilder and StringBuffer?
A: Both perform the same mutable string building logic. However, StringBuffer is completely synchronized (thread-safe), which adds a performance penalty due to locking overhead. StringBuilder is not synchronized and is significantly faster. Since string concatenation is almost always done as a local variable within a single thread, you should always use StringBuilder.

Q: Should you replace String fullName = firstName + " " + lastName; with StringBuilder?
A: No! For simple, single-line concatenations, the modern Java compiler automatically optimizes this into highly efficient bytecode (using StringConcatFactory). Writing new StringBuilder().append(first).append(" ").append(last).toString() for a single line just makes your code harder to read with zero performance benefit. You only strictly need StringBuilder when building strings dynamically inside a loop.