100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Java

StringBuilder and StringBuffer in Java

Compare Java's mutable string alternatives StringBuilder and StringBuffer, their key methods, and when to choose each for performance and thread safety.

Arrays & StringsIntermediate9 min readJul 7, 2026
Analogies

1. Introduction

Because String is immutable, repeatedly building or editing text with + concatenation creates many throwaway objects, which is wasteful. Java provides StringBuilder and StringBuffer as mutable alternatives designed specifically for efficient, in-place text building.

🏏

Cricket analogy: Rebuilding a full scorecard from scratch after every single run scored would be absurd—like discarding and rewriting the whole ledger—so scorers keep a running, editable tally instead, just as StringBuilder edits text in place rather than creating throwaway Strings.

Both classes offer the same core API (append, insert, delete, reverse, and more), but they differ in one crucial aspect: thread safety. Choosing the right one depends on whether the buffer is shared across multiple threads.

🏏

Cricket analogy: Both a paper scorebook and an official digital scoring app let you append runs, insert a correction, or delete a no-ball entry, but only the digital app locks itself so two scorers at different stadiums can't corrupt the same online scorecard simultaneously, mirroring StringBuffer's thread safety.

2. Syntax

java
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(", ").append("World");
sb.insert(0, ">> ");
sb.reverse();
sb.delete(0, 3);
String result = sb.toString();

StringBuffer buf = new StringBuffer("Thread-safe");
buf.append("!");

3. Explanation

StringBuilder maintains an internal, resizable character array (buffer) that is modified directly by methods like append() and insert(), avoiding the creation of a new object on every change. StringBuffer provides the identical method set, but its methods are declared 'synchronized', meaning only one thread can execute a mutating method on a given instance at a time.

🏏

Cricket analogy: StringBuilder is like a scorer's single notebook where each ball's run is appended directly into the existing page without starting a new notebook, while StringBuffer is the same notebook but with a rule that only one scorer can write in it at a time, like a shared stadium scoreboard.

This synchronization makes StringBuffer safe to share across multiple threads without external locking, but the locking overhead makes it measurably slower than StringBuilder in single-threaded code, which is by far the more common case.

🏏

Cricket analogy: A shared digital scoreboard visible to two commentary boxes needs locking so updates don't clash, like StringBuffer, but a single scorer's personal notebook needs no such locking and updates faster, like StringBuilder.

Rule of thumb: use StringBuilder by default for local, single-threaded string building (the vast majority of cases, e.g., inside a loop building a report string). Reach for StringBuffer only when the same buffer instance is genuinely shared and mutated by multiple threads concurrently.

Exam trap: StringBuilder/StringBuffer are mutable, so unlike String, calling append() modifies the SAME object rather than returning a new one — sb.append("x") changes sb in place and also returns 'this' for chaining, which is why calls like sb.append("a").append("b") work.

4. Example

java
public class StringBuilderDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java");
        sb.append(" Rocks");
        System.out.println("After append: " + sb);

        sb.insert(4, " Language");
        System.out.println("After insert: " + sb);

        sb.reverse();
        System.out.println("Reversed: " + sb);

        sb.reverse(); // put it back
        sb.delete(4, 13);
        System.out.println("After delete: " + sb);

        StringBuffer buf = new StringBuffer("Safe");
        buf.append(" Buffer");
        System.out.println("StringBuffer: " + buf);
    }
}

5. Output

text
After append: Java Rocks
After insert: Java Language Rocks
Reversed: skcoR egaugnaL avaJ
After delete: Java Rocks
StringBuffer: Safe Buffer

6. Key Takeaways

  • StringBuilder and StringBuffer are mutable alternatives to the immutable String class.
  • StringBuilder is NOT synchronized — faster, but not safe for concurrent modification by multiple threads.
  • StringBuffer IS synchronized (thread-safe) — safer for shared use, but slower due to locking overhead.
  • Common methods: append(), insert(), delete(), reverse(), and toString() to convert back to an immutable String.
  • Mutating methods modify the same object in place and return 'this', enabling method chaining.
  • Default to StringBuilder for single-threaded code; use StringBuffer only for genuine cross-thread sharing.

Practice what you learned

Was this page helpful?

Topics covered

#Java#JavaProgrammingStudyNotes#Programming#StringBuilderAndStringBufferInJava#StringBuilder#StringBuffer#Syntax#Explanation#StudyNotes#SkillVeris