Question
StringBuilder vs StringBuffer in Java: Differences and Performance
Question
In Java, what is the main difference between StringBuffer and StringBuilder?
Are there any performance considerations when choosing one over the other?
Short Answer
By the end of this page, you will understand how StringBuilder and StringBuffer work in Java, why both exist, what thread safety means in this context, and how their performance differs. You will also learn when to use each one in real programs.
Concept
StringBuilder and StringBuffer are both mutable sequence classes in Java. They are used when you need to build or modify strings efficiently.
Java String objects are immutable, which means once a string is created, it cannot be changed. If you repeatedly combine strings with +, Java often creates many temporary objects. That can be inefficient in loops or repeated text-building tasks.
That is where StringBuilder and StringBuffer help.
Core difference
The main difference is thread safety:
StringBufferis synchronized, so it is thread-safe.StringBuilderis not synchronized, so it is not thread-safe.
Because StringBuffer adds synchronization, it usually has more overhead. In single-threaded code, StringBuilder is typically faster.
Why this matters
In real programming, choosing between them depends on whether multiple threads may modify the same object at the same time.
- If only one thread uses the object,
StringBuilderis usually the right choice. - If multiple threads share and modify the same mutable character sequence,
StringBufferprovides built-in synchronization.
In practice, StringBuilder is more commonly used because many string-building tasks happen inside a method or request where the object is not shared across threads.
Mental Model
Think of both classes as editable notepads:
StringBuilderis a regular notepad on your desk. It is quick and easy to write on, but if several people try to write on it at the same time, the result may become messy.StringBufferis the same notepad, but with a rule: only one person can write at a time. That makes it safer for shared use, but slower because people must wait their turn.
So the trade-off is simple:
- Speed:
StringBuilder - Safety for shared access:
StringBuffer
Syntax and Examples
Both classes have very similar APIs.
Basic syntax
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString();
StringBuffer sbf = new StringBuffer();
sbf.append("Hello");
sbf.append(" ");
sbf.append("World");
String result = sbf.toString();
Example with StringBuilder
public class Main {
public static void main(String[] args) {
StringBuilder builder = new ();
builder.append();
builder.append();
builder.append();
System.out.println(builder.toString());
}
}
Step by Step Execution
Consider this example:
StringBuilder builder = new StringBuilder();
builder.append("A");
builder.append("B");
builder.append("C");
String result = builder.toString();
Step by step:
new StringBuilder()creates an empty mutable character container.append("A")addsAto the container.- Current content:
A
- Current content:
append("B")addsBto the end.- Current content:
AB
- Current content:
append("C")addsCto the end.- Current content:
ABC
- Current content:
toString()creates a regular immutableStringcontaining .
Real World Use Cases
Here are common situations where StringBuilder or StringBuffer is useful:
Building API responses or messages
StringBuilder message = new StringBuilder();
message.append("User: ").append(username).append(" logged in at ").append(time);
Generating CSV or text files
StringBuilder csv = new StringBuilder();
csv.append("id,name\n");
csv.append("1,Alice\n");
csv.append("2,Bob\n");
Building SQL or dynamic queries carefully
StringBuilder query = new StringBuilder("SELECT * FROM users WHERE 1=1");
if (activeOnly) {
query.append(" AND active = true");
}
Creating logs efficiently inside loops
();
( ; i < ; i++) {
log.append().append(i).append();
}
Real Codebase Usage
In real Java codebases, developers usually follow these patterns:
Use StringBuilder for local string construction
Inside a method, if the object is created and used only there, StringBuilder is the usual choice.
public String formatName(String firstName, String lastName) {
StringBuilder builder = new StringBuilder();
builder.append(lastName).append(", ").append(firstName);
return builder.toString();
}
Use chaining for readability
String result = new StringBuilder()
.append("Total: ")
.append(42)
.append(" items")
.toString();
Pre-size when large output is expected
If you know the text will be large, you can reduce resizing overhead.
StringBuilder builder = new StringBuilder();
Common Mistakes
1. Thinking StringBuffer is always better because it is thread-safe
Thread safety is useful only when the same object is actually shared between threads.
If the buffer is local to one method, StringBuilder is usually the better default.
2. Using StringBuilder in shared mutable multithreaded code
Broken example:
public class SharedText {
private static StringBuilder builder = new StringBuilder();
public static void addText(String text) {
builder.append(text);
}
}
If multiple threads call addText, the result may be corrupted or unpredictable.
3. Assuming + is always bad
For small, simple concatenations, + is often perfectly fine and more readable.
String firstName + + lastName;
Comparisons
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Thread-safe | Yes, because immutable | No | Yes |
| Synchronized methods | No | No | Yes |
| Usually faster for repeated modification | No | Yes | Usually slower than StringBuilder |
| Best use case | Fixed text values | Single-threaded string building | Shared mutable string building |
StringBuilder vs StringBuffer
Cheat Sheet
Quick rule
- Use
StringBuilderby default for repeated string modification. - Use
StringBufferonly when the same mutable buffer must be shared safely across threads.
Core difference
StringBuilder builder = new StringBuilder(); // not synchronized
StringBuffer buffer = new StringBuffer(); // synchronized
Common methods
append()
insert()
delete()
reverse()
length()
capacity()
toString()
Example
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" ").append("Java");
String result = sb.toString();
Performance rule
FAQ
What is the main difference between StringBuilder and StringBuffer in Java?
StringBuffer is synchronized and thread-safe. StringBuilder is not synchronized and is usually faster.
Is StringBuilder faster than StringBuffer?
Yes, in most single-threaded cases StringBuilder is faster because it does not pay synchronization cost.
When should I use StringBuffer?
Use it when multiple threads must safely modify the same mutable character sequence.
Should I always use StringBuilder instead of String?
No. For simple one-off concatenations, regular String with + is often clearer and perfectly acceptable.
Is StringBuilder thread-safe if each thread creates its own instance?
Yes. If each thread uses its own separate instance, there is no shared mutable state problem.
Why are strings immutable in Java?
Immutability improves safety, predictability, and makes strings easier to share and optimize.
Mini Project
Description
Build a small Java utility that generates a formatted order summary. This project demonstrates why StringBuilder is useful when combining many pieces of text into one final output.
Goal
Create a method that builds a multi-line receipt string efficiently using StringBuilder.
Requirements
[ "Create a method that accepts a customer name and a list of item names.", "Build a multi-line receipt using StringBuilder.", "Include a header, each item on its own line, and a total item count.", "Return the final result as a String." ]
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.