Card 07/ 09
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.
| Type | Can be changed in place | Safe across threads | Reach for it when |
|---|---|---|---|
String | No | Yes, because nothing can change it | The text is a value you pass around |
StringBuilder | Yes | No | You are assembling text in a loop or a method |
StringBuffer | Yes | Yes, every method is synchronised | Two threads genuinely share one builder |
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.
← → move through sections and cards