Both StringBuilder
and StringBuffer
are used for building/modifying strings without creating new objects each time, unlike String
. But they differ mainly in thread safety and performance.
🔄 Key Differences Between StringBuilder
and StringBuffer
Feature | StringBuilder | StringBuffer |
---|---|---|
Thread Safety | ❌ Not thread-safe | ✅ Thread-safe (synchronized methods) |
Performance | Faster (no overhead of synchronization) | Slower (due to synchronization) |
Introduced In | Java 5 | Java 1.0 |
Usage Scenario | When working in a single-threaded context | When working in a multi-threaded context |
🧪 Simple Example
public class StringBuilderVsBuffer {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder(“Hello “);
sb.append(“World!”);
System.out.println(“StringBuilder: ” + sb);
StringBuffer sf = new StringBuffer(“Hello “);
sf.append(“Java!”);
System.out.println(“StringBuffer: ” + sf);
}
}
🖨 Output:
StringBuilder: Hello World!
StringBuffer: Hello Java!
🧠 Quick Tip:
If you’re not sharing the object across threads, prefer StringBuilder
—you’ll get better performance.