StringBuffer & StringBuilder
As we learned in the previous section, String objects are immutable. If your application involves heavy string manipulation (like in a loop), using String will create thousands of abandoned objects in the memory, severely impacting performance.
To solve this, Java provides two classes in the java.lang package for Mutable (modifiable) sequences of characters:
StringBufferStringBuilder
1. The StringBuffer Class
StringBuffer was introduced in Java 1.0. It is used to create mutable string objects.
- Mutable: When you use methods like
append(),insert(), ordelete(), it modifies the same object in memory without creating a new one. - Thread-Safe:
StringBufferis synchronized. This means multiple threads cannot call its methods simultaneously. It is safe for use in multithreaded environments.
Example: Using StringBuffer
public class LabStringBuffer1 {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
// Modifies the original object directly
sb.append(" Java");
System.out.println(sb); // Prints "Hello Java"
// Insert text at a specific index
sb.insert(5, " Beautiful");
System.out.println(sb); // Prints "Hello Beautiful Java"
// Reverse the string
sb.reverse();
System.out.println(sb);
}
}
2. The StringBuilder Class
StringBuilder was introduced later in Java 1.5. It works exactly like StringBuffer and has the exact same API (methods).
- Mutable: Like
StringBuffer, it modifies the same object in memory. - Not Thread-Safe:
StringBuilderis not synchronized. This means multiple threads can access it simultaneously. Because it doesn't carry the overhead of synchronization, it is significantly faster thanStringBuffer.
Example: Using StringBuilder
public class LabStringBuilder1 {
public static void main(String args[]) {
StringBuilder sb = new StringBuilder("Learn");
sb.append(" Java");
System.out.println(sb); // Prints "Learn Java"
sb.replace(0, 5, "Master"); // Replaces index 0 to 4
System.out.println(sb); // Prints "Master Java"
}
}
Comparison: String vs StringBuffer vs StringBuilder
Choosing between these three classes depends on two factors: Mutability and Thread Safety.
| Feature | String | StringBuffer | StringBuilder |
|---|---|---|---|
| Mutability | Immutable (Unchangeable) | Mutable (Changeable) | Mutable (Changeable) |
| Thread-Safety | Yes (Because it's immutable) | Yes (Methods are synchronized) | No (Not synchronized) |
| Performance | Fast (if not modified) | Slow (due to locking overhead) | Fastest (no locking overhead) |
| Use Case | Data that rarely changes (Keys, URLs) | Heavy modification in a Multithreaded environment | Heavy modification in a Single-threaded environment |
[!TIP] Rule of Thumb:
- If your string is not going to change, use
String.- If your string will change frequently and you are in a single-threaded environment, use
StringBuilder(Preferred 99% of the time).- If your string will change frequently and you are in a multi-threaded environment, use
StringBuffer.