Differentiate between String, StringBuffer, and StringBuilder classes with focus on mutability, performance, and thread safety.
Answer:-
Here is a clear and concise comparison between String, StringBuffer, and StringBuilder in Java based on mutability, performance, and thread safety:
1. String
Feature | Description |
---|---|
Mutability | Immutable — once created, the content cannot be changed. Any modification results in a new object. |
Thread Safety | Thread-safe by nature (since it is immutable). |
Performance | Slow when performing multiple modifications (creates new objects). |
Use Case | When the string content does not change frequently. |
Example:
String s = "Java"; s = s.concat(" Programming"); // creates a new object System.out.println(s); // Output: Java Programming
2. StringBuffer
Feature | Description |
---|---|
Mutability | Mutable — content can be changed using methods like append() , insert() , etc. |
Thread Safety | Thread-safe — all methods are synchronized. |
Performance | Slower than StringBuilder due to synchronization. |
Use Case | Suitable for multi-threaded environments where string content changes frequently. |
Example:
StringBuffer sb = new StringBuffer("Java"); sb.append(" Programming"); System.out.println(sb); // Output: Java Programming
3. StringBuilder
Feature | Description |
---|---|
Mutability | Mutable — behaves like StringBuffer. |
Thread Safety | Not thread-safe — methods are not synchronized. |
Performance | Faster than StringBuffer (no overhead of synchronization). |
Use Case | Best for single-threaded applications with frequent string modifications. |
Example:
StringBuilder sb = new StringBuilder("Java"); sb.append(" Programming"); System.out.println(sb); // Output: Java Programming
Summary Table
Feature | String | StringBuffer | StringBuilder |
---|---|---|---|
Mutability | Immutable | Mutable | Mutable |
Thread Safety | Yes | Yes (synchronized) | No |
Performance | Slow | Moderate | Fast |
Recommended For | Constant data | Multi-threaded apps | Single-threaded apps |