Java Reference ยท java.lang
The StringBuffer class
Reference for Java StringBuffer: the synchronized twin of StringBuilder, what its locking really protects, and when to prefer StringBuilder.
StringBuffer is the original mutable string class, available since Java 1.0. It has the same methods as StringBuilder: append, insert, delete, replace, reverse and so on. The difference is that every public method is synchronized, so two threads can call methods on the same buffer without corrupting its internal array.
StringBuilder arrived in Java 5 as the unsynchronized replacement, and it is what you should use almost everywhere. A buffer's locking only protects each individual call; most code that shares a text accumulator across threads needs more than that.
StringBuffer buf = new StringBuffer("log:"); buf.append(" started").append(' ').append(1);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public final class StringBuffer implements Appendable, CharSequence, Comparable<StringBuffer>, java.io.Serializable
| Member | Description |
|---|---|
new StringBuffer(), (int capacity), (String), (CharSequence) |
Same constructors as StringBuilder; default capacity 16. |
append, insert, delete, deleteCharAt, replace, reverse |
Modify the content; each call is synchronized and returns the buffer. |
charAt, length, indexOf, substring, setCharAt, setLength |
Access and edit. |
toString() |
Returns a new String (cached internally until the next change). |
Throws: StringIndexOutOfBoundsException for invalid indexes, like StringBuilder.
Usage notes
- Prefer
StringBuilder. In single-threaded code (almost all code) the locking is wasted work. Local variables are never shared, so a buffer assigned to a local is pointless. - Per-call safety only.
if (buf.length() > 0) buf.deleteCharAt(0);is two calls and another thread can run in between. For compound operations, hold your own lock or use a different design. - Typical modern alternatives: a
ConcurrentLinkedQueue<String>or per-thread builders merged at the end, a logging framework, or aPrintWriterwrapped in a lock. - Where you still meet it: older APIs, such as the
StringBufferoverloads ofMatcher.appendReplacement()andappendTail()(Java 9 addedStringBuilderversions),java.text.Formatmethods likeformat(Object, StringBuffer, FieldPosition), and legacy code. - Equality: like
StringBuilder, it does not overrideequals()orhashCode(). Compare withtoString().equals(...)orcompareTo()(Java 11). - Performance: uncontended locks are cheap on modern JVMs (and often elided), but the class is still measurably slower than
StringBuilderin tight loops. - Thread safety does not apply to the result. Once
toString()returns, you have an immutableString.