String vs StringBuilder in Java — Which Should You Use?

Java Strings are immutable, so repeated concatenation creates many objects; StringBuilder mutates a buffer in place for far better performance in loops.

Published September 22, 2026

String in Java is immutable — every concatenation (+ or concat()) creates a brand-new String object rather than modifying the original. StringBuilder is mutable — it maintains an internal resizable buffer that can be appended to in place without creating a new object each time.

Common causes

  • String immutability exists for good reasons (thread safety, safe use as a hash map key, string interning), but it means repeated concatenation in a loop creates and discards many intermediate String objects

How to fix it

  • Use StringBuilder whenever building a string incrementally inside a loop — .append() modifies the same buffer instead of allocating a new object each iteration
  • Use plain String concatenation for a small, fixed number of simple concatenations outside of loops, where the compiler can often optimize it automatically
  • Call .toString() once at the end to get the final immutable String from a StringBuilder

Example

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append(i).append(",");
}
String result = sb.toString();

FAQ

Does the Java compiler already optimize + concatenation?

For simple, fixed concatenations within a single statement, yes — javac typically compiles them into a single StringBuilder chain automatically. It does not, however, optimize concatenation happening across multiple iterations of a loop.

More Java articles