Comparison - String, StringBuilder & StringBuffer

Difference between String, String Builder, and String Buffer

Feature
String
StringBuilder
StringBuffer

Mutability

Immutable

Mutable

Mutable

Thread Safety

Thread-safe (because it's immutable)

Not thread-safe

Thread-safe

Storage

String variables are stored in a “constant string pool”

String values are stored in a stack. If the values are changed then the new value replaces the older value.

Same as StringBuilder

Performance

Slower in operations involving multiple string modifications

Faster for single-threaded operations involving multiple string modifications

Slower than StringBuilder due to synchronization overhead

Usage

Used when the string value will not change or change infrequently

Used when the string value will change frequently and thread safety is not a concern

Used when the string value will change frequently and thread safety is a concern

Methods Available

Limited to standard string operations (e.g., length, charAt, substring)

Extensive methods for modifying strings (e.g., append, insert, delete, reverse)

Similar to StringBuilder with synchronized methods for thread safety

Thread Synchronization

Not applicable

Not synchronized

Synchronized methods

Memory Allocation

Fixed and cannot be changed after creation

Can grow dynamically

Can grow dynamically

String Pool

Supports string pool

Does not support string pool

Does not support string pool

Performance in Concatenation

Poor performance in concatenation (each concatenation creates a new object)

Better performance for concatenation (modifies the existing object)

Better performance for concatenation (modifies the existing object, but slower than StringBuilder)

Example Initialization

String str = "Hello";

StringBuilder sb = new StringBuilder("Hello");

StringBuffer sb = new StringBuffer("Hello");

Usage Scenario

Best for read-only or rarely modified strings

Best for frequently modified strings in single-threaded contexts

Best for frequently modified strings in multi-threaded contexts

Example Operations

str.concat(" World");

sb.append(" World");

sb.append(" World");

// String
String str = "Hello";
str = str.concat(" World"); // Creates a new string "Hello World"
System.out.println(str);    // Output: Hello World

// StringBuilder
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies the existing StringBuilder object
System.out.println(sb.toString()); // Output: Hello World

// StringBuffer
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Modifies the existing StringBuffer object
System.out.println(sb.toString()); // Output: Hello World 

Last updated

Was this helpful?