← Back to Home

StringBuffer

StringBuffer is a mutable, thread-safe class in Java used to create and manipulate strings. It is designed for scenarios where string content changes frequently and multiple threads may access the same object. This topic is important for interviews, especially when comparing String, StringBuilder, and StringBuffer.

What Is StringBuffer?

  • A mutable sequence of characters
  • Part of java.lang package
  • Thread-safe (synchronized methods)
  • Slower than StringBuilder, faster than repeated String concatenation
StringBuffer sb = new StringBuffer("Java");
          

Why StringBuffer Exists

  • String → Immutable (inefficient for frequent changes)
  • StringBuilder → Mutable but not thread-safe
  • StringBuffer → Mutable and thread-safe

Use case: Multi-threaded environments where string modification is required.

Key Characteristics of StringBuffer

  • Mutable
  • Synchronized (thread-safe)
  • Allows modification without creating new objects
  • Methods are synchronized → performance overhead

How StringBuffer Works (Conceptual)

StringBuffer sb = new StringBuffer("Java");
sb.append(" World");
          
  • Same object is modified
  • No new object created (unlike String)

Commonly Used Constructors

StringBuffer sb1 = new StringBuffer();          // default capacity 16
StringBuffer sb2 = new StringBuffer("Java");    // capacity = 16 + length
StringBuffer sb3 = new StringBuffer(50);        // custom capacity
          

Capacity Concept (Important)

StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); // 16
          

When capacity is exceeded:

newCapacity = (oldCapacity * 2) + 2
          

Commonly Used StringBuffer Methods

append()

sb.append(" Java");
          

insert()

sb.insert(4, " Core");
          

replace()

sb.replace(0, 4, "Core");
          

delete()

sb.delete(0, 4);
          

reverse()

sb.reverse();
          

length() and capacity()

sb.length();
sb.capacity();
          

Example Program

StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
sb.insert(4, " Core");
sb.replace(0, 4, "Core");
sb.reverse();
System.out.println(sb);
          

StringBuffer vs StringBuilder vs String

Feature String StringBuilder StringBuffer
Mutability Immutable Mutable Mutable
Thread Safety Yes No Yes
Performance Slow (changes) Fastest Slower than SB
Synchronization N/A No Yes
Use Case Read-only Single-thread Multi-thread

When to Use StringBuffer

  • Multi-threaded applications
  • Shared string modification
  • Thread safety is more important than performance

When NOT to Use StringBuffer

  • Single-threaded applications
  • Performance-critical code
  • Simple string concatenation

Common Beginner Mistakes

  • Using StringBuffer unnecessarily
  • Assuming it is faster than StringBuilder
  • Ignoring synchronization overhead
  • Confusing immutability with thread safety

StringBuffer Examples (Quick Reference)

1. Creating a StringBuffer Object

StringBuffer sb = new StringBuffer("Java");
          
  • Creates a mutable sequence of characters.
  • Stored in heap memory.
  • Thread-safe (synchronized).

2. Default StringBuffer Constructor

StringBuffer sb = new StringBuffer();
System.out.println(sb.length());
          
  • Creates empty buffer.
  • Initial length = 0.
  • Default capacity = 16.

3. StringBuffer with Initial Capacity

StringBuffer sb = new StringBuffer(50);
System.out.println(sb.capacity());
          
  • Capacity reserved upfront.
  • Improves performance when size is known.

4. Appending Strings (append())

StringBuffer sb = new StringBuffer("Java");
sb.append(" Selenium");
System.out.println(sb);
          
  • Modifies the same object.
  • No new object created.
  • Output: Java Selenium.

5. Appending Different Data Types

StringBuffer sb = new StringBuffer("Count: ");
sb.append(10);
sb.append(true);
System.out.println(sb);
          
  • Supports int, boolean, char, double, etc.
  • Output: Count: 10true.

6. Inserting Text (insert())

StringBuffer sb = new StringBuffer("Java");
sb.insert(4, " Selenium");
System.out.println(sb);
          
  • Inserts at specified index.
  • Output: Java Selenium.

7. Deleting Characters (delete())

StringBuffer sb = new StringBuffer("Java Selenium");
sb.delete(4, 13);
System.out.println(sb);
          
  • Deletes substring between indices.
  • Output: Java.

8. Deleting Single Character (deleteCharAt())

StringBuffer sb = new StringBuffer("Javva");
sb.deleteCharAt(3);
System.out.println(sb);
          
  • Removes character at index.
  • Output: Java.

9. Reversing String (reverse())

StringBuffer sb = new StringBuffer("Java");
sb.reverse();
System.out.println(sb);
          
  • Reverses characters in place.
  • Output: avaJ.

10. Replacing Substring (replace())

StringBuffer sb = new StringBuffer("Java Automation");
sb.replace(5, 15, "Selenium");
System.out.println(sb);
          
  • Replaces characters between indices.
  • Output: Java Selenium.

11. Finding Length

StringBuffer sb = new StringBuffer("Java");
System.out.println(sb.length());
          
  • Returns number of characters.
  • Output: 4.

12. Finding Capacity

StringBuffer sb = new StringBuffer("Java");
System.out.println(sb.capacity());
          
  • Capacity = 16 + length of initial string.
  • Output: 20.

13. Ensuring Capacity (ensureCapacity())

StringBuffer sb = new StringBuffer();
sb.ensureCapacity(50);
System.out.println(sb.capacity());
          
  • Ensures minimum capacity.
  • Avoids frequent resizing.

14. Character Access (charAt())

StringBuffer sb = new StringBuffer("Java");
System.out.println(sb.charAt(1));
          
  • Index-based character access.
  • Output: a.

15. Setting Character (setCharAt())

StringBuffer sb = new StringBuffer("Java");
sb.setCharAt(1, 'o');
System.out.println(sb);
          
  • Modifies character at index.
  • Output: Jova.

16. Converting StringBuffer to String

StringBuffer sb = new StringBuffer("Java");
String s = sb.toString();
System.out.println(s);
          
  • Creates immutable String.
  • Common when returning values.

17. String Immutability vs StringBuffer Mutability

String s = "Java";
s.concat(" Selenium");
System.out.println(s);
StringBuffer sb = new StringBuffer("Java");
sb.append(" Selenium");
System.out.println(sb);
          
  • String remains unchanged.
  • StringBuffer changes in place.
  • Output: Java, Java Selenium.

18. Thread Safety Demonstration (Conceptual)

StringBuffer sb = new StringBuffer("Test");
sb.append(" Safe");
          
  • All methods are synchronized.
  • Safe for multi-threaded environments.
  • Slower than StringBuilder.

19. Using StringBuffer in Loop (Performance Friendly)

StringBuffer sb = new StringBuffer();
for (int i = 1; i <= 5; i++) {
  sb.append(i);
}
System.out.println(sb);
          
  • Avoids multiple String objects.
  • Output: 12345.

20. Comparing StringBuffer Objects

StringBuffer sb1 = new StringBuffer("Java");
StringBuffer sb2 = new StringBuffer("Java");
System.out.println(sb1.equals(sb2));
          
  • equals() not overridden.
  • Compares references.
  • Output: false.

21. Correct Way to Compare StringBuffer Content

StringBuffer sb1 = new StringBuffer("Java");
StringBuffer sb2 = new StringBuffer("Java");
System.out.println(sb1.toString().equals(sb2.toString()));
          
  • Convert to String for content comparison.
  • Output: true.

22. StringBuffer with Null Handling

StringBuffer sb = new StringBuffer();
sb.append((String) null);
System.out.println(sb);
          
  • Appends literal "null".
  • Output: null.

23. StringBuffer Substring

StringBuffer sb = new StringBuffer("Automation");
String sub = sb.substring(0, 4);
System.out.println(sub);
          
  • Returns a String, not StringBuffer.
  • Output: Auto.

24. Clearing a StringBuffer

StringBuffer sb = new StringBuffer("Java");
sb.setLength(0);
System.out.println(sb.length());
          
  • Clears content.
  • Output: 0.

25. Interview Summary Example (StringBuffer)

StringBuffer sb = new StringBuffer("Java");
sb.append(" Test");
System.out.println(sb);
          
  • Demonstrates mutability, heap storage, thread safety.
  • Very common interview discussion topic.

Interview-Ready Answers

Short Answer

StringBuffer is a mutable and thread-safe class used to modify strings in multi-threaded environments.

Detailed Answer

In Java, StringBuffer allows modification of string content without creating new objects and ensures thread safety through synchronized methods. It is suitable for multi-threaded applications but has lower performance compared to StringBuilder.

Key Takeaway

Use StringBuffer only when thread safety is required. For most modern applications, prefer StringBuilder unless multiple threads modify the same string.