← Back to Chapters

String vs StringBuffer vs StringBuilder

? String vs StringBuffer vs StringBuilder

? Quick Overview

In Java, String, StringBuffer, and StringBuilder are used to work with text data. They differ mainly in mutability, thread safety, and performance.

? Key Concepts

  • String → Immutable text object
  • StringBuffer → Mutable & thread-safe
  • StringBuilder → Mutable & not thread-safe (faster)

? Syntax / Theory

  • Once a String object is created, it cannot be changed.
  • StringBuffer allows modification and is synchronized.
  • StringBuilder allows modification but is not synchronized.

? Interactive Simulator: Mutability

Type a word and click the buttons to see how memory is handled differently.

String (Immutable)

Ref @x001 ""

*Notice how a new object is created every time.

StringBuilder (Mutable)

Ref @x999 ""

*Notice the Address Ref stays the same.

? Code Examples

? View Code Example
// Demonstrating immutability of String
String s = "Hello";
s.concat(" World");
System.out.println(s);
? View Code Example
// StringBuffer allows modification and is thread-safe
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb);
? View Code Example
// StringBuilder allows modification and is faster
StringBuilder sbuilder = new StringBuilder("Hello");
sbuilder.append(" World");
System.out.println(sbuilder);

? Live Output / Explanation

Output

Hello
Hello World
Hello World

The String value does not change because it is immutable. Both StringBuffer and StringBuilder modify the original object.

? Tips & Best Practices

  • Use String for fixed text values.
  • Use StringBuffer in multi-threaded environments.
  • Use StringBuilder in single-threaded applications for better performance.

? Try It Yourself

  • Write a program that compares performance of String and StringBuilder.
  • Create a loop that appends text 1000 times using all three classes.
  • Observe memory and execution time differences.