Difference Between String, StringBuffer, and StringBuilder in Java

๐Ÿ” 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.

Written by: Rehan Khan

Comments

Popular posts from this blog

Git And GitHub Collaborators and teams

How to create React JS application

๐Ÿ“ฑ Top 50 Android Developer Interview Questions and Answers