String vs StringBuilder vs StringBuffer in Java
7 min readUpdated
All three hold text, but they behave differently when the text changes. String never changes, StringBuilder changes in place and is fast, and StringBuffer is the older, synchronized version. Here is when to use which.
The short answer
- Use String for text that does not change: names, messages, keys.
- Use StringBuilder to build text step by step, especially in loops.
- You almost never need StringBuffer; it is a synchronized
StringBuilderkept for old code.
| String | StringBuilder | StringBuffer | |
|---|---|---|---|
| Can change after creation | No (immutable) | Yes | Yes |
| Thread safe | Yes (because immutable) | No | Yes (synchronized methods) |
| Speed when building text | Slow in loops (new object every time) | Fast | A little slower than StringBuilder |
| Since | Java 1.0 | Java 5 | Java 1.0 |
equals() compares content | Yes | No (reference) | No (reference) |
| Typical use | Most text | Building text in a loop | Legacy code |
String is immutable
Methods such as toUpperCase(), replace() and concat() never change the string; they return a new one. If you ignore the return value, nothing happens.
public class Immutable {
public static void main(String[] args) {
String name = "java";
name.toUpperCase(); // result thrown away
System.out.println(name);
name = name.toUpperCase(); // keep the new string
System.out.println(name);
StringBuilder sb = new StringBuilder("java");
sb.append(" 21").insert(0, "I use ");
System.out.println(sb); // the same object, changed in place
}
}Output
java JAVA I use java 21
Why += in a loop is slow
Each s += x on a String creates a new string and copies all the characters so far. In a loop of n steps that is about n²/2 character copies. StringBuilder keeps one growing buffer, so the same loop is linear.
public class BuildText {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
if (sb.length() > 0) sb.append(", ");
sb.append(i * i);
}
System.out.println(sb.toString());
// For joining a list there is an even simpler way:
System.out.println(String.join(" | ", "red", "green", "blue"));
}
}Output
1, 4, 9, 16, 25 red | green | blue
For a single line such as "Hello " + name + "!", plain + is fine: the compiler already turns it into efficient code. The problem is only += inside loops.
Useful StringBuilder methods
| Method | What it does |
|---|---|
append(x) | Adds x at the end (any type) |
insert(i, x) | Inserts x at index i |
delete(start, end) / deleteCharAt(i) | Removes characters |
reverse() | Reverses the text in place |
setCharAt(i, c) | Replaces one character |
setLength(0) | Clears it for reuse |
toString() | Returns the final String |
Why String is immutable
- String pool: literals can be shared safely because no one can change them.
- Security: a file path or URL checked once cannot be changed afterwards.
- Hash keys: the hash code is computed once and cached, which makes strings fast
HashMapkeys. - Thread safety: strings can be shared between threads with no locking.
Common mistakes
- Calling
name.trim()orname.replace(...)without assigning the result. - Comparing a
StringBuilderwithequals(). It compares references; calltoString()first, orcompareTo()(Java 11+). - Using
StringBufferin new code "to be safe". If several threads really build one text together, rethink the design. - Building SQL with string concatenation. Use
PreparedStatementparameters instead.
Frequently asked questions
Which is faster, StringBuilder or StringBuffer?
StringBuilder, because its methods are not synchronized. The difference is small, but there is no reason to pay it in single-threaded code.
Is StringBuilder thread safe?
No. If several threads change the same StringBuilder, the result can be corrupted. In practice, build text in one thread and share the finished String.
Why is String immutable in Java?
So that strings can be shared safely in the string pool and between threads, used as stable HashMap keys, and trusted after security checks.
Learn it step by step
Practise this, step by step
Short lessons with quizzes, practice and interview questions, from your first program to job-ready.