Skip to content
UniCircle
EasyConceptualStrings

String vs StringBuilder vs StringBuffer

Question JAVA-STR-021

Compare String, StringBuilder and StringBuffer. Which should you use to build a string in a loop?

Show the explanation
StringStringBuilderStringBuffer
Mutablenoyesyes
Thread-safeyes (immutable)noyes (synchronized methods)
Speed for repeated editsslow (copies)fastestslower than StringBuilder

Building a string with += in a loop creates a new String each time and copies everything so far — O(n²) characters copied in total. Use StringBuilder:

Java
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) sb.append(i).append(i < 5 ? "," : "");
String csv = sb.toString();          // "1,2,3,4,5"

StringBuffer is the older, synchronized version; you rarely need it, because a builder is usually confined to one method and one thread. For simple joins, String.join(",", list) or Collectors.joining are even clearer. (A single expression like a + b + c is fine — the compiler optimises it.)

Original UniCircle question. Last reviewed 22 Oct 2026.