00:00

Difference Between StringBuffer and StringBuilder in Java

Last updated:

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

FeatureStringBufferStringBuilder
IntroducedJava 1.0Java 5
SynchronizationPublic methods are synchronizedNone
Thread safetyEach method call is safe across threadsNeeds external locking when shared
PerformanceLocking cost on every call; its size depends on the JVMUsually faster in single-threaded code
MutabilityMutableMutable
Recommended useOne buffer that several threads append toSingle-thread or thread-confined text building

3. Class Hierarchy Diagram

StringBuffer and StringBuilder class hierarchyStringBuffer and StringBuilder are final classes that extend the package-private AbstractStringBuilder, which extends Object and implements Appendable and CharSequence. Both classes also implement Serializable and Comparable (since Java 11).«interface» · java.langAppendableappend(…)«class» · java.langObject«interface» · java.langCharSequencelength(), charAt(int)getChars(…) «default» †† since Java 25«interface» · java.ioSerializable«abstract» · package-privateAbstractStringBuildershared storage + capacityappend, insert, delete, …«interface» · java.langComparable<T>compareTo(T) †† since Java 11«final class» · Java 1.0StringBuffersynchronized methods«final class» · Java 5StringBuilderno synchronizationextendsimplementsinterfaceabstract classclass

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 shows Object as the direct superclass.
  • CharSequence (interface): read-only character access, so either class works where a CharSequence is expected.
  • Appendable (interface): the general append() 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.

ParcelLabel.java
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()));
    }
}
Output
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

  1. insert(0, …) adds a prefix, replace(19, 22, "HYD") swaps indexes 19 to 21, append() adds to the end and delete(3, 7) removes indexes 3 to 6. End indexes are exclusive.
  2. contentEquals() compares characters (true). equals() is not overridden, so it compares references (false).
  3. 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.

InvoiceReport.java
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);
    }
}
Output
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

  1. new StringBuilder(128) reserves room for the whole report, so the buffer does not grow during the loop.
  2. Each iteration appends a formatted line, and repeat('-', 28) adds a separator without a loop. Amounts are whole paise, avoiding rounding errors.
  3. 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.

AuditTrail.java
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();
    }
}
Output
Shared StringBuffer events : 10000
Confined StringBuilders    : 10000

How the code works

  1. Each append() on the shared StringBuffer is synchronized, so no event is lost.
  2. In the second part each thread owns its StringBuilder, so no locking is needed.
  3. 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: StringBuffer synchronizes each method call; StringBuilder never locks.
  • Capacity: storage grows automatically. ensureCapacity() pre-sizes it and trimToSize() may shrink it; the growth rule is an implementation detail.

8. Changes from Java 5 to Java 25

VersionChange
Java 11Both implement Comparable; compareTo() compares content.
Java 21repeat() appends a character or text several times.
Java 25CharSequence.getChars() became an interface default method; both classes already had it.

9. Advantages and Limitations

ClassAdvantagesLimitations
StringBufferSingle calls are safe on a shared instance.Locks even in single-threaded code; multi-step operations are not atomic.
StringBuilderNo locking overhead.Unsafe to share without external synchronization.

10. Constructors

Both classes have the same four constructors:

Constructors.java
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

MethodPurpose
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 StringBuilder for local variables, loops, toString() methods and any object one thread uses at a time, including text built inside a virtual-thread task.
  • Choose StringBuffer when 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:

BoundedAuditLog.java
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 StringBuffer as fully thread-safe. Only single calls are protected.
  • Using StringBuffer by habit. Single-threaded code gains nothing from its locking.
  • Using += in a loop. Each iteration creates a new String; append to one builder instead.
  • Comparing with equals(). Use contentEquals() or compareTo() (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 StringBuilder for single-threaded or thread-confined code.
  • Use StringBuffer for one buffer that several threads append to.
  • Multi-step operations still need an explicit lock.
  • Neither overrides equals(); compare content instead.

Related Tutorials

15. References