String vs StringBuilder vs StringBuffer in Java
Difference Between String, StringBuilder, and StringBuffer in Java
If you're learning Java, one of the most common interview questions is the difference between String, StringBuilder, and StringBuffer.
This is one of the most frequently asked topics in Java interviews.
Written by Shivkumar Udas – Engineering student sharing practical Java guides for beginners.
๐ก What is String in Java?
String is an immutable class in Java, which means its value cannot be changed after creation.
String str = "Java";
str.concat(" Programming"); // new object created
Key Point: Every modification creates a new object.
๐ก What is StringBuilder?
StringBuilder is a mutable class, meaning its value can be changed without creating a new object.
StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");
System.out.println(sb);
Key Point: Faster and efficient for modifications.
๐ก What is StringBuffer?
StringBuffer is similar to StringBuilder but is thread-safe.
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
System.out.println(sb);
Key Point: Thread-safe but slower than StringBuilder.
๐ Difference Between String, StringBuilder, and StringBuffer
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Performance | Slow | Fast | Moderate |
| Thread Safety | No | No | Yes |
| Usage | Simple strings | Frequent modifications | Multi-threaded environment |
⚡ When to Use Which?
- Use String when data does not change
- Use StringBuilder for better performance
- Use StringBuffer in multi-threaded environments
๐ Real-Life Example
Use String for fixed text like names.
Use StringBuilder when modifying text frequently like building a message.
Use StringBuffer when multiple threads access the same data.
๐ฏ Interview Tip
Always remember: String is immutable, while StringBuilder and StringBuffer are mutable.
In most real-world applications, StringBuilder is preferred because it is faster.
๐งช Practice Task
Create a program to append text using String, StringBuilder, and StringBuffer. Compare performance.
๐ Related Guides
๐ฏ Conclusion
Understanding the difference between String, StringBuilder, and StringBuffer helps you write efficient Java code.
Choose the right class based on your use case and performance needs.
Comments
Post a Comment