Compare String, StringBuilder and StringBuffer. Which should you use to build a string in a loop?
Show the explanation
| String | StringBuilder | StringBuffer | |
|---|---|---|---|
| Mutable | no | yes | yes |
| Thread-safe | yes (immutable) | no | yes (synchronized methods) |
| Speed for repeated edits | slow (copies) | fastest | slower 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:
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.
