Difference between String Builder and String Buffer?

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

FeatureStringBuilderStringBuffer
Thread SafetyNot thread-safe✅ Thread-safe (synchronized methods)
PerformanceFaster (no overhead of synchronization)Slower (due to synchronization)
Introduced InJava 5Java 1.0
Usage ScenarioWhen working in a single-threaded contextWhen 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.

Leave a Reply

Your email address will not be published. Required fields are marked *