Difference Between StringBuffer and StringBuilder in Java
StringBuffer and StringBuilder are Java's two classes for text that changes. They share the same methods, so the real difference is synchronization, and that decides which one suits your code.
StringBuffer arrived in Java 1.0 with synchronized methods. StringBuilder was added in Java 5 as an unsynchronized alternative for the common case where only one thread edits the text.
1. What Are StringBuffer and StringBuilder?
Both hold a sequence of characters that you can change in place. Methods such as append() modify the same object and return it, so calls can be chained.
A String is immutable, so every change creates a new object. When text is built piece by piece, a mutable buffer avoids those temporary objects. Typical uses are reports, log lines, CSV rows and toString() output.
2. StringBuffer vs StringBuilder: Key Differences
| Feature | StringBuffer | StringBuilder |
|---|---|---|
| Introduced | Java 1.0 | Java 5 |
| Synchronization | Public methods are synchronized | None |
| Thread safety | Each method call is safe across threads | Needs external locking when shared |
| Performance | Locking cost on every call; its size depends on the JVM | Usually faster in single-threaded code |
| Mutability | Mutable | Mutable |
| Recommended use | One buffer that several threads append to | Single-thread or thread-confined text building |
3. Class Hierarchy Diagram
Swipe sideways to see the whole diagram.
Object(class): the root class.AbstractStringBuilder(abstract, package-private): holds the storage and most method logic. It is internal to the JDK, so the Javadoc showsObjectas the direct superclass.CharSequence(interface): read-only character access, so either class works where aCharSequenceis expected.Appendable(interface): the generalappend()contract.Serializable,Comparable<T>(interfaces): both classes are serializable and, since Java 11, comparable by content.
4. Example 1: Editing a Parcel Label with Both Classes
A courier app edits a shipping label with the same calls on both classes.
public class ParcelLabel {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer("PKG-4471 | BLR to DEL");
StringBuilder builder = new StringBuilder("PKG-4471 | BLR to DEL");
// The same chain of calls compiles and behaves the same on both classes
buffer.insert(0, "EXPRESS ") // add a prefix at index 0
.replace(19, 22, "HYD") // reroute: BLR becomes HYD
.append(" | 2.5 kg") // add the weight at the end
.delete(3, 7); // shorten EXPRESS to EXP
builder.insert(0, "EXPRESS ")
.replace(19, 22, "HYD")
.append(" | 2.5 kg")
.delete(3, 7);
System.out.println("StringBuffer : " + buffer);
System.out.println("StringBuilder : " + builder);
System.out.println("Same text : " + buffer.toString().contentEquals(builder));
System.out.println("equals() : " + buffer.equals(builder));
// reverse() also changes the object in place
StringBuilder lockerCode = new StringBuilder("A7K-K7A");
String before = lockerCode.toString();
System.out.println("Symmetric code: " + before.equals(lockerCode.reverse().toString()));
}
}
StringBuffer : EXP PKG-4471 | HYD to DEL | 2.5 kg StringBuilder : EXP PKG-4471 | HYD to DEL | 2.5 kg Same text : true equals() : false Symmetric code: true
How the code works
insert(0, …)adds a prefix,replace(19, 22, "HYD")swaps indexes 19 to 21,append()adds to the end anddelete(3, 7)removes indexes 3 to 6. End indexes are exclusive.contentEquals()compares characters (true).equals()is not overridden, so it compares references (false).reverse()also works in place.
5. Example 2: Building an Invoice Report in a Loop
The builder is a local variable, so only one thread touches it. repeat() needs Java 21 or later.
import java.util.List;
public class InvoiceReport {
record Line(String item, int qty, int paise) { }
public static void main(String[] args) {
List<Line> lines = List.of(
new Line("USB-C cable", 2, 34_900),
new Line("Laptop stand", 1, 129_900),
new Line("Desk lamp", 3, 79_950));
// Size the builder once: 3 lines of about 30 characters each
StringBuilder report = new StringBuilder(128);
long total = 0;
for (Line l : lines) {
long amount = (long) l.qty() * l.paise();
total += amount;
report.append(String.format("%-14s x%d %10s%n", l.item(), l.qty(), rupees(amount)));
}
report.repeat('-', 28).append(System.lineSeparator()); // Java 21+
report.append(String.format("%-17s %10s", "TOTAL", rupees(total)));
System.out.println(report);
System.out.println();
System.out.println("new StringBuilder() capacity: " + new StringBuilder().capacity());
System.out.println("new StringBuilder(128) capacity: " + new StringBuilder(128).capacity());
System.out.println("new StringBuffer(\"INV\") capacity: " + new StringBuffer("INV").capacity());
}
static String rupees(long paise) {
return String.format("%d.%02d", paise / 100, paise % 100);
}
}
USB-C cable x2 698.00
Laptop stand x1 1299.00
Desk lamp x3 2398.50
----------------------------
TOTAL 4395.50
new StringBuilder() capacity: 16
new StringBuilder(128) capacity: 128
new StringBuffer("INV") capacity: 19
How the code works
new StringBuilder(128)reserves room for the whole report, so the buffer does not grow during the loop.- Each iteration appends a formatted line, and
repeat('-', 28)adds a separator without a loop. Amounts are whole paise, avoiding rounding errors. - The last lines show initial capacities: 16 by default, the requested size, and 16 plus the text length.
6. Example 3: Writing an Audit Trail from Two Threads
Two threads record login events: first into a shared StringBuffer, then into separate StringBuilders.
public class AuditTrail {
static final int EVENTS_PER_THREAD = 5_000;
static final String EVENT = "LOGIN;"; // 6 characters per event
public static void main(String[] args) throws InterruptedException {
// 1. One StringBuffer shared by two threads
StringBuffer shared = new StringBuffer();
Runnable writer = () -> {
for (int i = 0; i < EVENTS_PER_THREAD; i++) {
shared.append(EVENT); // each call is synchronized
}
};
runTwice(writer);
System.out.println("Shared StringBuffer events : " + shared.length() / EVENT.length());
// 2. One StringBuilder per thread, combined afterwards
StringBuilder partA = new StringBuilder();
StringBuilder partB = new StringBuilder();
Thread a = new Thread(() -> fill(partA));
Thread b = new Thread(() -> fill(partB));
a.start(); b.start();
a.join(); b.join(); // join() makes the results visible
StringBuilder merged = new StringBuilder(partA.length() + partB.length())
.append(partA).append(partB);
System.out.println("Confined StringBuilders : " + merged.length() / EVENT.length());
}
static void fill(StringBuilder own) {
for (int i = 0; i < EVENTS_PER_THREAD; i++) {
own.append(EVENT); // no other thread touches 'own'
}
}
static void runTwice(Runnable task) throws InterruptedException {
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start(); t2.start();
t1.join(); t2.join();
}
}
Shared StringBuffer events : 10000 Confined StringBuilders : 10000
How the code works
- Each
append()on the sharedStringBufferis synchronized, so no event is lost. - In the second part each thread owns its
StringBuilder, so no locking is needed. join()waits for both threads and makes their content visible to the main thread.
Sharing one StringBuilder instead gives unpredictable results: in five JDK 25 test runs of 40,000 appends, the final length ranged from 22,214 to 29,255.
7. Important Features and Characteristics
- Mutability: one object changes in place, and
setLength(0)clears it for reuse. - Synchronization:
StringBuffersynchronizes each method call;StringBuildernever locks. - Capacity: storage grows automatically.
ensureCapacity()pre-sizes it andtrimToSize()may shrink it; the growth rule is an implementation detail.
8. Changes from Java 5 to Java 25
| Version | Change |
|---|---|
| Java 11 | Both implement Comparable; compareTo() compares content. |
| Java 21 | repeat() appends a character or text several times. |
| Java 25 | CharSequence.getChars() became an interface default method; both classes already had it. |
9. Advantages and Limitations
| Class | Advantages | Limitations |
|---|---|---|
StringBuffer | Single calls are safe on a shared instance. | Locks even in single-threaded code; multi-step operations are not atomic. |
StringBuilder | No locking overhead. | Unsafe to share without external synchronization. |
10. Constructors
Both classes have the same four constructors:
CharSequence sku = "SKU-19";
StringBuilder empty = new StringBuilder(); // empty, capacity 16
StringBuilder sized = new StringBuilder(256); // empty, capacity 256
StringBuilder fromStr = new StringBuilder("Order #"); // capacity 16 + 7
StringBuilder fromSeq = new StringBuilder(sku); // copies any CharSequence
The same lines work with StringBuffer. A negative capacity throws NegativeArraySizeException.
11. Common Methods
| Method | Purpose |
|---|---|
append(x) | Adds any value's text at the end. |
insert(offset, x) | Inserts text at a position. |
delete(start, end), deleteCharAt(i) | Removes a range or one character. |
replace(start, end, str) | Replaces a range. |
reverse() | Reverses the sequence; surrogate pairs stay intact. |
repeat(cs, count), repeat(codePoint, count) | Appends repeated text (Java 21+). |
setLength(n) | Truncates, or pads with \u0000. |
capacity(), ensureCapacity(n), trimToSize() | Manage storage. |
charAt(i), setCharAt(i, ch), indexOf(str) | Read, change and search. |
toString() | Returns a new String. |
12. When to Use StringBuffer vs StringBuilder
- Choose
StringBuilderfor local variables, loops,toString()methods and any object one thread uses at a time, including text built inside a virtual-thread task. - Choose
StringBufferwhen several threads append independent pieces to one instance, or an existing API requires it.
Synchronized methods make each call atomic, not a sequence of calls. A check followed by an append needs one lock around both:
synchronized (auditLog) { // auditLog is a shared StringBuffer
if (auditLog.length() < MAX_LOG_CHARS) {
auditLog.append(event);
}
}
Without it, another thread can append between the check and your append.
13. Common Mistakes and Best Practices
- Treating
StringBufferas fully thread-safe. Only single calls are protected. - Using
StringBufferby habit. Single-threaded code gains nothing from its locking. - Using
+=in a loop. Each iteration creates a newString; append to one builder instead. - Comparing with
equals(). UsecontentEquals()orcompareTo()(Java 11+). - Guessing about speed. Measure with a tool such as JMH when it matters.
14. Summary
- Both classes are mutable, final and share the same methods.
StringBuffer(Java 1.0) synchronizes its methods;StringBuilder(Java 5) does not.- Use
StringBuilderfor single-threaded or thread-confined code. - Use
StringBufferfor one buffer that several threads append to. - Multi-step operations still need an explicit lock.
- Neither overrides
equals(); compare content instead.