String vs StringBuffer vs StringBuilder in Java: Key Differences and Usage
String is immutable, meaning its value cannot change after creation. StringBuffer and StringBuilder are mutable and allow modification, but StringBuffer is thread-safe while StringBuilder is faster but not synchronized.Quick Comparison
Here is a quick comparison of String, StringBuffer, and StringBuilder based on key factors.
| Feature | String | StringBuffer | StringBuilder |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread Safety | Not thread-safe | Thread-safe (synchronized) | Not thread-safe |
| Performance | Slower for modifications | Slower than StringBuilder due to synchronization | Faster than StringBuffer, good for single-thread |
| Use Case | Fixed text, constants | Multi-threaded environment | Single-threaded environment |
| Introduced In | Java 1.0 | Java 1.0 | Java 1.5 |
Key Differences
String objects are immutable, which means once created, their value cannot be changed. Any modification creates a new String object, which can be costly in loops or frequent changes.
StringBuffer is mutable and synchronized, making it safe to use in multi-threaded programs where multiple threads might modify the same string data. However, synchronization adds overhead, making it slower than StringBuilder.
StringBuilder is also mutable but not synchronized, so it is faster and preferred in single-threaded scenarios where thread safety is not a concern. It was introduced in Java 5 to improve performance over StringBuffer when synchronization is unnecessary.
Code Comparison
This example shows how to append text using StringBuffer.
public class StringBufferExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); System.out.println(sb.toString()); } }
StringBuilder Equivalent
The same task using StringBuilder is simpler and faster in single-threaded use.
public class StringBuilderExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); System.out.println(sb.toString()); } }
When to Use Which
Choose String when your text does not change, like constants or fixed messages. Use StringBuffer if you need to modify strings in a multi-threaded environment where safety matters. Opt for StringBuilder when you want fast string modifications in a single-threaded context, such as building strings in loops.
Key Takeaways
String for immutable text that does not change.StringBuffer for thread-safe mutable strings in multi-threaded programs.StringBuilder for faster mutable strings in single-threaded scenarios.StringBuilder.