What is the Difference Between String StringBuffer and StringBuilder in Java?

🆚 Go to Comparative Table 🆚

The main differences between String, StringBuffer, and StringBuilder in Java are:

  1. Immutability: String is immutable, meaning it cannot be changed once created, whereas both StringBuffer and StringBuilder are mutable, providing methods for string manipulation.
  2. Thread Safety: StringBuffer is thread-safe and synchronized, meaning its operations are safe for use with multiple threads. StringBuilder, on the other hand, is not thread-safe and is not synchronized, making it faster and suitable for use in single-threaded environments.
  3. Performance: StringBuilder is generally faster than StringBuffer due to its lack of synchronization, which allows it to avoid the overhead of thread safety.

Here is a summary of their key characteristics:

String StringBuffer StringBuilder
Immutability Immutable Mutable Mutable
Thread Safety Not Thread-Safe Thread-Safe & Synchronized Not Thread-Safe & Not Synchronized
Performance Slower (due to immutability) Slower (due to synchronization) Faster

In summary, use StringBuilder for string manipulation in single-threaded environments, and use StringBuffer when multiple threads are working on the same string.

Comparative Table: String StringBuffer vs StringBuilder in Java

Here is a table comparing the differences between String, StringBuffer, and StringBuilder in Java:

Feature String StringBuffer StringBuilder
Storage String pool (Heap memory) Heap memory Heap memory
Mutability Immutable Mutable Mutable
Performance Slower than StringBuffer while performing concatenation Faster than String, slower than StringBuilder while performing concatenation Faster than both String and StringBuffer while performing concatenation
Usage in threaded environment Not used in a threaded environment Used in a multi-threaded environment Not recommended for multi-threaded environments
Synchronization Not synchronized Synchronized Not synchronized
  • String: Represents an immutable sequence of characters. When concatenating strings, a new string is generated, leaving the original string intact and creating garbage for garbage collection.
  • StringBuffer: A mutable and thread-safe class that allows for efficient string manipulation, particularly in multi-threaded environments. Methods like append(), insert(), delete(), and substring() are provided for string manipulation.
  • StringBuilder: Similar to StringBuffer, but not thread-safe and more suitable for single-threaded environments. It provides the same methods for string manipulation as StringBuffer and is faster than both String and StringBuffer while performing concatenation.