Card 07/ 09

ComparisonDifficulty: Intermediate1 min

String vs StringBuilder vs StringBuffer

Three types that hold text; two can change in place, and one of those two is rarely what you want.

String holds text that never changes. StringBuilder holds text you can append to in place, which is what you use to assemble text in a loop. StringBuffer does the same with every method synchronised, locked so that only one thread (one of several paths of execution running at once in a program) can use it at a time, so two threads can share it safely.

The three text types on mutability, thread safety and when to use each
TypeCan be changed in placeSafe across threadsReach for it when
StringNoYes, because nothing can change itThe text is a value you pass around
StringBuilderYesNoYou are assembling text in a loop or a method
StringBufferYesYes, every method is synchronisedTwo threads genuinely share one builder
java
StringBuilder row = new StringBuilder();
for (String value : values) {
    row.append(value).append(",");
}
String result = row.toString();

append writes into a character array the builder already owns, growing it in jumps when it runs out. Nothing is copied per pass, so a thousand appends cost about a thousand times one append rather than a thousand squared.

The decision rule. Use String for text you hold and hand around. Use StringBuilder the moment you are assembling text in a loop. Use StringBuffer only when two threads append to the same builder, which is rare enough that meeting it should make you check the design first.