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 is immutable, so every change creates a new object; StringBuilder is mutable and edits one buffer in place. Use StringBuilder when you build text in a loop.

The concept

Because Strings never change, s += x copies the whole string each time. In a loop of n steps that is O(n²) work and lots of garbage.

StringBuilder keeps a growable char array and appends in amortised constant time. Convert to a String once at the end with toString().

What each loop allocates

String s: "a" → "ab" → "abc" → "abcd" (4 objects)
StringBuilder: [a][b][c][d] one buffer, one toString()

Practical examples

Slow: concatenation in a loop

String s = "";
for (int i = 0; i < 10000; i++) s += i;

Fast: StringBuilder

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) sb.append(i);
String s = sb.toString();

Handy methods

sb.insert(0, ">> ").reverse().setLength(5);

Joining collections

String csv = String.join(",", List.of("a", "b", "c"));

Common mistakes

  • Using + in loops for large text.
  • Sharing a StringBuilder between threads (use StringBuffer or avoid sharing).
  • Forgetting the compiler already optimises simple a + b + c expressions.

Key takeaways

  • String = immutable, StringBuilder = mutable.
  • Use StringBuilder in loops.
  • Single-line concatenation is fine.

FAQ

StringBuilder vs StringBuffer?

StringBuffer is synchronised and slower; use StringBuilder unless threads share it.

Why are Strings immutable?

For safety, caching of hash codes, the string pool and thread-safety.

More Java articles