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
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
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
After append: Java Rocks
After insert: Java Language Rocks
Reversed: skcoR egaugnaL avaJ
After delete: Java Rocks
StringBuffer: Safe Buffer6. 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
1. What is the primary reason StringBuilder exists alongside String?
2. Which class's methods are synchronized (thread-safe)?
3. Why is StringBuilder generally preferred over StringBuffer in single-threaded code?
4. What does sb.append("a").append("b") rely on to work syntactically?
5. How do you convert a StringBuilder into an immutable String?
Was this page helpful?
You May Also Like
Strings in Java
Understand Java's String class, its immutability, the string constant pool, and why == should never be used to compare string content.
Common String Methods in Java
A practical reference to the most frequently used Java String methods, including comparison, searching, splitting, and case-conversion operations.
Arrays in Java
Learn how Java arrays store fixed-size, homogeneous collections of elements on the heap, including declaration, default values, and common runtime errors.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics