String vs StringBuilder vs StringBuffer
All three are used to work with text, but they differ mainly in mutability and thread safety.
| Feature | String |
StringBuilder |
StringBuffer |
|---|---|---|---|
| Mutable? | No | Yes | Yes |
| Thread-safe? | Yes* | No | Yes |
| Performance | Good for fixed text | Fast for modifications | Slower than Builder |
| Best for | Fixed text | Frequent changes, single thread | Frequent changes, multiple threads |
Stringis immutable, which makes it safe to share, but "thread-safe" isn't quite the same concept as synchronized mutable classes.
1. String
String is immutable — once created, its value cannot be changed.
String name = "John";
name = name + " Doe";
System.out.println(name);
When you modify it, Java creates a new String instead of changing the original.
Use when:
The text doesn't need frequent modification.
Examples:
String name = "Moxit";
String country = "India";
String message = "Hello World";
2. StringBuilder
StringBuilder is mutable, so you can modify the same object.
StringBuilder text = new StringBuilder("Hello");
text.append(" World");
text.append("!");
System.out.println(text);
Output:
Hello World!
It is generally faster than StringBuffer because it doesn't use synchronization.
Use when:
You frequently modify text in a single-threaded situation.
For example:
StringBuilder result = new StringBuilder();
for (int i = 1; i <= 5; i++) {
result.append(i);
}
System.out.println(result);
3. StringBuffer
StringBuffer is also mutable, but its methods are synchronized, making it suitable when multiple threads may access the same object.
StringBuffer text = new StringBuffer("Hello");
text.append(" World");
System.out.println(text);
Use when:
You need a mutable string that is shared between multiple threads.
Easy Way to Remember
String
↓
Immutable
↓
Fixed text
StringBuilder
↓
Mutable + faster
↓
Single-threaded modifications
StringBuffer
↓
Mutable + synchronized
↓
Multi-threaded modifications
One-line rule
Fixed text → String | Frequently changing text → StringBuilder | Changing text shared across threads → StringBuffer