Sobes.tech
Junior

What is the problem with string concatenation in Java?

sobes.tech AI

Answer from AI

String concatenation using the + operator in Java can be inefficient, especially in loops or when working with a large number of strings. Each + operation creates a new String object, leading to excessive memory allocation and garbage collection.

Example:

// Inefficient
String result = "";
for (int i = 0; i < 100; i++) {
    result += "string" + i; // Each iteration creates a new String object
}

More efficient approaches:

  • StringBuilder: A mutable class for building strings. Suitable for single-threaded scenarios.
// Efficient in single-threaded scenarios
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
    sb.append("string").append(i);
}
String result = sb.toString();
  • StringBuffer: Thread-safe counterpart of StringBuilder. Has overhead due to synchronization.

In modern Java versions, the compiler can automatically optimize concatenation with + in simple cases using StringBuilder behind the scenes. However, explicit use of StringBuilder or StringBuffer is recommended for better performance in loops and when working with large data volumes.