0
0
JavaComparisonBeginner · 4 min read

String vs StringBuffer vs StringBuilder in Java: Key Differences and Usage

String is immutable, meaning its value cannot change after creation. StringBuffer and StringBuilder are mutable and allow modification, but StringBuffer is thread-safe while StringBuilder is faster but not synchronized.
⚖️

Quick Comparison

Here is a quick comparison of String, StringBuffer, and StringBuilder based on key factors.

FeatureStringStringBufferStringBuilder
MutabilityImmutableMutableMutable
Thread SafetyNot thread-safeThread-safe (synchronized)Not thread-safe
PerformanceSlower for modificationsSlower than StringBuilder due to synchronizationFaster than StringBuffer, good for single-thread
Use CaseFixed text, constantsMulti-threaded environmentSingle-threaded environment
Introduced InJava 1.0Java 1.0Java 1.5
⚖️

Key Differences

String objects are immutable, which means once created, their value cannot be changed. Any modification creates a new String object, which can be costly in loops or frequent changes.

StringBuffer is mutable and synchronized, making it safe to use in multi-threaded programs where multiple threads might modify the same string data. However, synchronization adds overhead, making it slower than StringBuilder.

StringBuilder is also mutable but not synchronized, so it is faster and preferred in single-threaded scenarios where thread safety is not a concern. It was introduced in Java 5 to improve performance over StringBuffer when synchronization is unnecessary.

⚖️

Code Comparison

This example shows how to append text using StringBuffer.

java
public class StringBufferExample {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Hello");
        sb.append(" World");
        System.out.println(sb.toString());
    }
}
Output
Hello World
↔️

StringBuilder Equivalent

The same task using StringBuilder is simpler and faster in single-threaded use.

java
public class StringBuilderExample {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Hello");
        sb.append(" World");
        System.out.println(sb.toString());
    }
}
Output
Hello World
🎯

When to Use Which

Choose String when your text does not change, like constants or fixed messages. Use StringBuffer if you need to modify strings in a multi-threaded environment where safety matters. Opt for StringBuilder when you want fast string modifications in a single-threaded context, such as building strings in loops.

Key Takeaways

Use String for immutable text that does not change.
Use StringBuffer for thread-safe mutable strings in multi-threaded programs.
Use StringBuilder for faster mutable strings in single-threaded scenarios.
Avoid unnecessary synchronization to improve performance with StringBuilder.
Understand your program's threading needs to pick the right string class.