In Java, strings are essential for handling text data. Java provides three main classes for working with strings: String, StringBuffer, and StringBuilder. Each has distinct features and use cases.
1. String:
- Definition:
Stringis an immutable class that represents a sequence of characters. Once aStringobject is created, it cannot be modified.
- Features:
- Immutable: Any modification creates a new object.
- Thread-safe: Immutable objects are inherently thread-safe.
- Stored in the string pool for memory optimization.
- Example:
public class StringExample {
public static void main(String[] args) {
String str = "Hello";
String str2 = str.concat(" World");
System.out.println("Original String: " + str); // Output: Hello
System.out.println("Modified String: " + str2); // Output: Hello World
}
}
2. StringBuffer:
- Definition:
StringBufferis a mutable class for creating and modifying strings. It is thread-safe, meaning all methods are synchronized.
- Features:
- Mutable: Can be modified without creating new objects.
- Thread-safe: Suitable for multi-threaded environments.
- Slightly slower due to synchronization overhead.
- Example:
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println("Modified StringBuffer: " + sb); // Output: Hello World
}
}
3. StringBuilder:
- Definition:
StringBuilderis similar toStringBufferbut is not thread-safe. It is faster and preferred in single-threaded environments.
- Features:
- Mutable: Can be modified without creating new objects.
- Non-thread-safe: Not synchronized.
- Faster than
StringBuffer.
- Example:
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println("Modified StringBuilder: " + sb); // Output: Hello World
}
}
Key Differences:
| Feature | String | StringBuffer | StringBuilder |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread-Safe | Yes | Yes | No |
| Performance | Slower (due to immutability) | Slower (due to synchronization) | Faster (no synchronization) |
| Use Case | When immutability is required. | Multi-threaded environments. | Single-threaded environments. |
When to Use Which?
- String:
- Use when you need immutable strings, such as for constants or security-sensitive data.
- StringBuffer:
- Use in multi-threaded environments where thread safety is crucial.
- StringBuilder:
- Use in single-threaded applications where performance is a priority.