← Back to Chapters

Java StringBuffer

? Java StringBuffer

? Quick Overview

StringBuffer is a mutable sequence of characters in Java. Unlike String, it allows modification of text without creating new objects, making it suitable for frequent string manipulations.

? Key Concepts

  • Mutable (content can be changed)
  • Thread-safe (synchronized)
  • Slower than StringBuilder due to synchronization
  • Used when multiple threads modify strings

? Syntax / Theory

The StringBuffer class belongs to java.lang package and provides methods like append(), insert(), delete(), and reverse().

? Code Example

? View Code Example
// Creating and modifying a StringBuffer
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
sb.insert(5, ",");
System.out.println(sb);
}
}

?️ Live Output / Explanation

Output

Hello, World

The original string is modified directly using append() and insert() without creating new objects.

? Interactive Playground

Simulate StringBuffer operations live:

Hello

✅ Tips & Best Practices

  • Use StringBuffer when thread safety is required
  • Prefer StringBuilder for single-threaded applications
  • Avoid excessive synchronization unless needed

? Try It Yourself

  • Create a StringBuffer and reverse its content
  • Delete characters from a specific index range
  • Compare performance with StringBuilder