Nearby lessons

111 of 125

Java - StringBuffer and StringBuilder

📌 What You Will Learn
  • Why String objects are immutable
  • String vs StringBuffer vs StringBuilder
  • The most important methods of String
  • == vs equals() — the classic interview question
  • How to split, join and manipulate text

StringBuffer and StringBuilder is a core concept of the Java language. This lesson explains String vs StringBuffer vs StringBuilder, String vs StringBuffer — Question and Answer and StringBuffer — Constructors and Methods with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

String vs StringBuffer vs StringBuilder

If you need to change text many times, do not use String — every change creates a new object, which is slow. Use StringBuffer or StringBuilder instead:

PointStringStringBufferStringBuilder
Immutable?YesNoNo
Thread safe?Yes (immutable)Yes (synchronized)No
SpeedSlow when changed oftenMediumFastest
Java versionJDK 1.0JDK 1.0Java 5
When to useText that never changesMulti-threaded changesSingle-threaded changes (most common)
Trainer's Note: Trainer rule of thumb: use String for normal values, StringBuilder when you are building text in a loop (like a report), and StringBuffer only when multiple threads share the same buffer.
Example01
JCode Cell
1StringBuilder sb = new StringBuilder("Hello");
2sb.append(" World"); // changes the SAME object
3sb.insert(5, ",");
4sb.reverse();
5System.out.println(sb);
Output
dlroW ,olleH

String vs StringBuffer — Question and Answer

PointStringStringBuffer
MutabilityImmutable (cannot change)Mutable (can change)
StorageString Constant PoolHeap (for the buffer object)
Changing contentCreates a new object each timeChanges the same object
Performance with changesSlowFast
Thread safe?Yes (immutable)Yes (synchronized)

StringBuffer — Constructors and Methods

StringBuffer (and its sibling StringBuilder) has three constructors:

ConstructorWhat it does
new StringBuffer()Empty buffer with initial capacity 16
new StringBuffer(int capacity)Empty buffer with your own capacity
new StringBuffer(String str)Buffer with the given text; new capacity = 16 + text length

And the key methods (StringBuilder has the same methods):

MethodWhat it doesExample
append(data)Add text at the endsb.append("Hi")
insert(index, str)Insert text at a positionsb.insert(1, "-")
delete(start, end)Remove a range of characterssb.delete(1, 3)
reverse()Reverse the whole contentsb.reverse()
replace(start, end, str)Replace a range with textsb.replace(1, 3, "X")
capacity()Current capacity of the buffersb.capacity()
length()Number of characters currently heldsb.length()
ensureCapacity(n)Set a minimum capacity (min 16)sb.ensureCapacity(100)
Example03
JCode Cell
1class BufferDemo {
2 public static void main(String[] args) {
3 StringBuffer sb = new StringBuffer("Hello");
4 sb.append(" World"); // Hello World
5 sb.insert(5, ","); // Hello, World
6 sb.reverse(); // dlroW ,olleH
7 System.out.println(sb);
8 
9 StringBuilder s2 = new StringBuilder("Java");
10 s2.append(" 8");
11 System.out.println(s2); // Java 8
12 }
13}
Output
dlroW ,olleH Java 8
📝 Key Takeaways
  • String is a class, not a primitive; it is immutable.
  • Immutability gives security, thread safety and pool caching.
  • Use StringBuilder (fastest, not thread-safe) or StringBuffer (thread-safe) when text changes often.
  • == compares references; .equals() compares content. Always use .equals() for Strings.
  • Override toString() to print objects meaningfully.
  • Text blocks (Java 15+) make multi-line strings clean.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2