Video in progress

Junior ☕ Core Java

What is the difference between String, StringBuilder and StringBuffer?

String is immutable. StringBuilder is mutable and fast, but not thread-safe. StringBuffer is mutable and synchronized, so it's slower; today it's hardly used.

📖 Answer

Building text in a loop:

// bad: a new String on every iteration
String csv = "";
for (String name : names) csv += name + ",";

// good
StringBuilder sb = new StringBuilder();
for (String name : names) sb.append(name).append(',');
String csv2 = sb.toString();

With 10 thousand elements the first one slows down noticeably, because the whole text is copied every time.

What to use when:

  • a simple concatenation on one line ("Salom, " + name): String; the compiler optimizes it on its own;
  • a loop or step-by-step assembly: StringBuilder;
  • StringBuffer: only if an old API requires it. Several threads writing to one builder is usually a design mistake.

The simplest way to join a list with a separator is String.join(",", names).