StringBuffer and StringBuilder in Java

StringBuffer and StringBuilder are both Java classes for creating and manipulating mutable sequences of characters, but they differ in thread safety and performance.

Here’s a breakdown:

FeatureStringBufferStringBuilder
MutabilityMutable (like StringBuilder)Mutable (like StringBuffer)
Thread SafetyYes — methods are synchronized, so multiple threads can use the same object without corrupting dataNo — methods are not synchronized, so unsafe in multi-threaded contexts
PerformanceSlower than StringBuilder because synchronization adds overheadFaster than StringBuffer because no synchronization overhead
Introduced InJava 1.0Java 5
UsageUse when multiple threads need to modify the same string objectUse when only one thread will be modifying the string

Example:

// StringBuffer example (thread-safe)
StringBuffer sbf = new StringBuffer("Hello");
sbf.append(" World");
System.out.println(sbf); // Hello World

// StringBuilder example (faster, not thread-safe)
StringBuilder sbd = new StringBuilder("Hello");
sbd.append(" World");
System.out.println(sbd); // Hello World

Rule of Thumb:

  • Single-threaded → Use StringBuilder (better performance).
  • Multi-threaded → Use StringBuffer (safety over speed).

Leave a Reply