Card 07/ 09

ComparisonDifficulty: Intermediate1 min

String, StringBuilder and StringBuffer on Three Axes

Three types that all hold text. Two of them can be changed in place, and the difference between those two is a decision somebody made in 1996 and a decision somebody made in 2004.

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.