Home » Java Tutorial » StringBuffer in Java – Complete Guide for Beginners

StringBuffer in Java – Complete Guide for Beginners

Working with strings is one of the most common tasks in Java. While the String class is useful, it’s immutable, which means once a String is created, it cannot be changed.

To overcome this limitation, Java provides mutable alternatives:
👉 StringBuilder
👉 StringBuffer

In this tutorial, we’ll learn StringBuffer, will explore its features, usage, advantages, and differences with String and StringBuilder.

What is StringBuffer in Java?

StringBuffer is a class in Java used to create mutable (modifiable) strings.

  • It is present in the java.lang package.
  • Unlike String, we can modify the contents (insert, append, delete) without creating a new object.
  • It is thread-safe, meaning it is synchronized and safe to use in a multi-threaded environment.

In short we can define it as, StringBuffer is a mutable (modifiable) sequence of characters. Unlike String, which is immutable, StringBuffer allows you to change the content without creating a new object.

Why use StringBuffer?

  • When you need to modify strings frequently (e.g., inside loops).
  • When your application is multi-threaded, and you need synchronized operations on strings.

Syntax to Create a StringBuffer

StringBuffer sb = new StringBuffer();              // Empty buffer, capacity = 16
StringBuffer sb2 = new StringBuffer("Hello");      // Initialized with Hello
StringBuffer sb3 = new StringBuffer(30);           // Custom initial capacity

Capacity in StringBuffer

  • Default capacity is 16 characters (for empty buffer).
  • If you initialize with a string, capacity becomes: 16 + length of the string.
StringBuffer sb = new StringBuffer("Java");
System.out.println(sb.capacity()); // Output: 20 (16 + 4)

Important Methods of StringBuffer

Let’s explore the most important and frequently used methods with examples.

1. append(String str)

Appends the specified string to the end.

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World

2. insert(int offset, String str)

Inserts string at a given position.

StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " Java");
System.out.println(sb); // Output: Hello Java

3. replace(int start, int end, String str)

Replaces characters between start and end with the given string.

StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb); // Output: Hello Java

4. delete(int start, int end)

Deletes characters between the start and end index.

StringBuffer sb = new StringBuffer("Hello Java");
sb.delete(5, 10);
System.out.println(sb); // Output: Hello

5. reverse()

Reverses the sequence of characters.

StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); // Output: olleH

6. capacity()

Returns the current capacity of the buffer.

StringBuffer sb = new StringBuffer("Hi");
System.out.println(sb.capacity()); // Output: 18 (16 + 2)

7. ensureCapacity(int minCapacity)

Ensures the capacity is at least equal to the minimum specified.

StringBuffer sb = new StringBuffer();
sb.ensureCapacity(50);
System.out.println(sb.capacity()); // Output: 50 or more

8. charAt(int index)

Returns the character at the specified index.

tStringBuffer sb = new StringBuffer("Java");
System.out.println(sb.charAt(2)); // Output: v

9. length()

Returns the number of characters in the buffer.

StringBuffer sb = new StringBuffer("Java");
System.out.println(sb.length()); // Output: 4

String vs StringBuffer vs StringBuilder

FeatureStringStringBufferStringBuilder
MutabilityImmutableMutableMutable
Thread-safeYes (but unnecessary)Yes (Synchronized)No (Not synchronized)
PerformanceSlow (due to immutability)Slower (due to sync)Faster (no sync)
Usage in Multi-threadNot idealBest choiceNot suitable
Packagejava.langjava.langjava.lang

Real-life Example of StringBuffer

Suppose you want to build a long string from user inputs in a loop:

public class StringBufferExample {
    public static void main(String[] args) {
        // Creating a StringBuffer object
        StringBuffer sb = new StringBuffer("Hello");

        // Appending text
        sb.append(" World");
        System.out.println("After append: " + sb);

        // Inserting text
        sb.insert(5, ",");
        System.out.println("After insert: " + sb);

        // Replacing part of the text
        sb.replace(6, 11, " Java");
        System.out.println("After replace: " + sb);

        // Deleting characters
        sb.delete(0, 1);
        System.out.println("After delete: " + sb);

        // Reversing the content
        sb.reverse();
        System.out.println("After reverse: " + sb);
    }
}

Output

After append: Hello World
After insert: Hello, World
After replace: Hello, Java
After delete: ello, Java
After reverse: avaJ ,olle

Key Points:

  • StringBuffer is thread-safe (synchronized), which means it can be safely used in multithreaded environments.
  • Use StringBuffer when you need to make many modifications to strings.
  • For single-threaded environments, StringBuilder is a faster alternative.

Internal Implementation of StringBuffer in Java

✅ 1. Basic Structure

Internally, StringBuffer uses a character array (char[]) to store the string content.

✅ 2. Important Fields

Here’s a simplified version of how StringBuffer is implemented:

public final class StringBuffer extends AbstractStringBuilder implements java.io.Serializable, CharSequence {
    public StringBuffer() {
        super(16); // default capacity is 16
    }

    public StringBuffer(String str) {
        super(str.length() + 16); // capacity = string length + 16
        append(str);              // copy content to buffer
    }

    // All methods like append(), insert(), delete(), etc., are defined in AbstractStringBuilder
}

✅ 3. Backed by AbstractStringBuilder

StringBuffer extends an abstract class called AbstractStringBuilder, which actually holds the logic for:

  • append()
  • insert()
  • delete()
  • reverse()
  • And more…

Core Fields in AbstractStringBuilder:

char[] value;      // the internal character array
int count;         // the number of characters currently used

How It Works (Step-by-Step)

🧩 Initialization:

StringBuffer sb = new StringBuffer("Hello");
  • Allocates a new char[] of size: length of "Hello" + 16 = 21.
  • Copies “Hello” into the internal array.
  • count is set to 5.

🧩 Append Operation:

sb.append(" World");
  • Appends characters one by one.
  • If the internal char[] is full, it grows automatically:
newCapacity = (oldCapacity * 2) + 2;
  • Content is not copied every time unless the array becomes full.

✅ 4. Thread Safety

StringBuffer is synchronized, meaning all public methods like append(), insert(), etc., are thread-safe.

Example:

public synchronized StringBuffer append(String str) {
    super.append(str);
    return this;
}

That’s why it’s slower than StringBuilder in single-threaded scenarios.

When to Use What?

  • Use StringBuffer when:
    • You modify strings often.
    • Your application is multi-threaded.
  • Use StringBuilder when:
    • You want faster performance in single-threaded programs.
  • Avoid using String for heavy string modifications inside loops or large data operations.

Interview Tip: Why is StringBuffer synchronized?

To prevent data inconsistency in a multi-threaded environment.
It ensures that only one thread can modify the buffer at a time.

Summary of Key Points

ConceptExplanation
StringBufferA class used to create modifiable strings.
Thread-safetyYes (synchronized methods).
PerformanceSlower than StringBuilder due to synchronization.
Common Methodsappend(), insert(), replace(), delete(), reverse()
Use CaseMulti-threaded applications with frequent string modifications.

Conclusion

The StringBuffer class is a powerful utility in Java that solves the problem of inefficient string handling in cases where you need frequent modifications, especially in multi-threaded applications.

Now that you’ve learned everything from syntax to advanced usage of StringBuffer, you’re ready to use it confidently in your Java projects.