Difference between String, StringBuffer and StringBuilder in Java
Certainly! Below is a comprehensive comparison between String
, StringBuffer
, and StringBuilder
in Java, highlighting their differences and providing examples for each.
1. String:
- Immutability:
String
objects are immutable, meaning their values cannot be changed after creation.
- Performance:
- Concatenating strings using the
+
operator creates new objects, which can be inefficient for frequent modifications in loops.
- Concatenating strings using the
Example:
Example
String str1 = "Hello";
String str2 = " World";
// Creates new objects, not efficient in loops
String result = str1 + str2;
2. StringBuffer:
- Mutability:
StringBuffer
objects are mutable, allowing modifications of their content.
- Performance:
- Efficient for concatenating strings in loops due to its mutable nature.
Example:
Example
StringBuffer buffer = new StringBuffer("Hello");
// Modifies the same StringBuffer object, efficient in loops
buffer.append(" World");
3. StringBuilder:
- Mutability:
StringBuilder
objects are mutable, similar toStringBuffer
.
- Performance:
- Faster than
StringBuffer
in single-threaded environments due to lack of synchronization.
- Faster than
Example:
Example
StringBuilder builder = new StringBuilder("Hello");
// Modifies the same StringBuilder object, efficient in loops (faster than StringBuffer)
builder.append(" World");
Comparison Table:
Aspect | String | StringBuffer | StringBuilder |
---|---|---|---|
Immutability | Immutable | Mutable | Mutable |
Thread Safety | n/a | Synchronized, thread-safe | Not synchronized, not thread-safe |
Performance | Moderate (concatenation creates new objects) | Efficient for single-threaded use, but slower due to synchronization | Very efficient, especially in single-threaded use |
Usage | When content should not change frequently | When thread safety is required | When thread safety is not required, and performance is crucial |
Example Demonstrating Differences:
Example
/*
* Author: Zameer Ali Mohil
* */
public class StringExample {
public static void main(String[] args) {
// String Example
String str1 = "Hello";
String str2 = " World";
// Inefficient for frequent modifications
String result = str1 + str2;
// StringBuffer Example
StringBuffer buffer = new StringBuffer("Hello");
// Efficient for frequent modifications in loops
buffer.append(" World");
// StringBuilder Example
StringBuilder builder = new StringBuilder("Hello");
// Efficient for frequent modifications in loops (faster than StringBuffer)
builder.append(" World");
}
}
In the example above, String
concatenation results in the creation of new objects, which can be inefficient in loops. On the other hand, StringBuffer
and StringBuilder
are efficient for frequent modifications, with StringBuilder
being faster in single-threaded scenarios due to lack of synchronization. The choice between them depends on the specific requirements of the application.