๐ Difference Between String, StringBuffer, and StringBuilder in Java
When working with text data in Java, developers often encounter three important classes: String, StringBuffer, and StringBuilder. Though they seem similar, they behave differently in terms of memory usage, performance, and thread safety.
๐ 1. What is String?
String is an immutable class in Java. This means once a string object is created, it cannot be changed.
String s = "Hello";
s = s + " World";
System.out.println(s); // Output: Hello World
✅ Key Points:
- Immutable
- Thread-safe
- Not suitable for frequent modifications
๐ 2. What is StringBuffer?
StringBuffer is a mutable class and thread-safe (synchronized). It allows modification of content without creating new objects.
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
✅ Key Points:
- Mutable
- Thread-safe (synchronized)
- Slower than StringBuilder
๐ 3. What is StringBuilder?
StringBuilder is similar to StringBuffer, but it's not thread-safe. It's faster and preferred for single-threaded applications.
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
✅ Key Points:
- Mutable
- Not thread-safe
- Faster than StringBuffer
๐ Comparison Table
| Feature | String | StringBuffer | StringBuilder |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread-safe | Yes | Yes | No |
| Performance | Slowest | Medium | Fastest |
| Synchronization | Not needed | Yes | No |
| Use Case | Fixed text | Multi-threaded | Single-threaded |
๐ฏ Conclusion
Understanding the differences between these three classes is essential for writing optimized and clean Java code.
- Use String when the text won't change.
- Use StringBuffer in multi-threaded applications.
- Use StringBuilder for high-performance, single-threaded text manipulation.
Comments
Post a Comment