Comparison - String, StringBuilder & StringBuffer
Difference between String, String Builder, and String Buffer
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");
Last updated
Was this helpful?