0
Explore
0

StringBuilder in Java – A Complete Guide

Updated on July 30, 2025

Strings are a vital part of programming. You’ve likely used them for names, messages, input/output, and much more. But what happens when you need to frequently change or update a string?

Using regular String objects can be inefficient, because Strings in Java are immutable — once created, their content cannot be changed.

This is where StringBuilder comes in.

What is StringBuilder?

StringBuilder is a mutable class in Java, meaning you can modify the contents of the string without creating new objects.

It belongs to the java.lang package, so no import is needed.

Think of it like a notepad you can write and erase on, instead of making a new page every time (like with String).

Why use StringBuilder instead of String?

Let’s look at this example:

String s = "Hello";
s = s + " World";

Even though it looks like you’re modifying s, Java actually creates a new String object and assigns it to s. That’s wasteful in terms of memory and speed, especially in loops.

Now see this:

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");

Here, sb is modified directly — no new object is created. ✅

Difference: String vs StringBuilder vs StringBuffer

FeatureStringStringBuilderStringBuffer
MutabilityImmutableMutableMutable
Thread-safeYes❌ No✅ Yes
PerformanceSlowerFastest (Single Thread)Slower than StringBuilder
Packagejava.langjava.langjava.lang

Use StringBuilder when:

  • You need to modify strings often
  • You’re working in a single-threaded environment

How to create a StringBuilder

There are multiple ways:

StringBuilder sb1 = new StringBuilder(); // Empty builder
StringBuilder sb2 = new StringBuilder("Hello"); // With initial string
StringBuilder sb3 = new StringBuilder(50); // With capacity of 50

Commonly Used Methods of StringBuilder (with Examples)

Let’s learn the most used methods of StringBuilder.

1. append(String str)

Adds the string to the end.

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

You can also append numbers, chars, etc.

sb.append(123);
System.out.println(sb);  // Output: Hello World123

2. insert(int offset, String str)

Inserts a string at the specified index.

StringBuilder sb = new StringBuilder("Java");
sb.insert(2, "123");
System.out.println(sb);  // Output: Ja123va

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

Replaces characters between start (inclusive) and end (exclusive).

tringBuilder sb = new StringBuilder("JavaScript");
sb.replace(4, 10, "123");
System.out.println(sb);  // Output: Java123

4. delete(int start, int end)

Deletes characters between start and end.

StringBuilder sb = new StringBuilder("Programming");
sb.delete(3, 6);
System.out.println(sb);  // Output: Progamming

5. deleteCharAt(int index)

Deletes a single character at given index.

StringBuilder sb = new StringBuilder("Hello");
sb.deleteCharAt(1);
System.out.println(sb);  // Output: Hllo

6. reverse()

Reverses the string.

StringBuilder sb = new StringBuilder("ABC");
sb.reverse();
System.out.println(sb);  // Output: CBA

7. toString()

Converts StringBuilder to String.

StringBuilder sb = new StringBuilder("Hello");
String s = sb.toString();

8. Capacity and Length

StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity()); // Default = 16
sb.append("Java is great!");
System.out.println(sb.length());   // Actual number of characters

You can also ensure minimum capacity using:

sb.ensureCapacity(100);

Method Chaining in StringBuilder

Method Chaining means calling multiple methods on the same object in a single line — one after another.

This is possible because many methods (like in StringBuilder) return the object itself (i.e., return this), not void or another type.

So instead of doing this:

sb.append(" World");
sb.insert(5, ",");
sb.replace(6, 7, "-");

You can write all three in one line:

sb.append(" World").insert(5, ",").replace(6, 7, "-");

Why does this work?

Let’s say you have this method inside StringBuilder:

public StringBuilder append(String str) {
    // internal logic to append str
    return this;  // returns current object
}

Notice the return type is StringBuilder, not void. So once you call sb.append(…), you get back the same object — and can immediately call another method on it.

Step-by-step Breakdown of the Example

Here’s the code again:

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World").insert(5, ",").replace(6, 7, "-");
System.out.println(sb);  // Output: Hello-World

Let’s analyze it step by step:

sb.append(” World”)

  • Original: “Hello”
  • After append: “Hello World”

.insert(5, “,”)

  • Current string: “Hello World”
  • Insert a comma at index 5 (after ‘o’)
  • Result: “Hello, World”

.replace(6, 7, “-“)

  • Current string: “Hello, World”
  • Index 6 is the space after the comma
  • So it replaces the space between comma and ‘W’ with “-“
  • Final string: “Hello-World”

Real-world Analogy

Imagine you’re modifying a sentence on a whiteboard:

  • append(” World”) ⇒ add something at the end
  • insert(5, “,”) ⇒ insert a character at a specific spot
  • replace(6, 7, “-“) ⇒ replace one part of it with another

Now instead of wiping the board and rewriting after each step, you’re just modifying the same board (object) in a smooth flow — that’s method chaining!

Benefits of Method Chaining

  • Shorter, cleaner code
  • Easier to read when done properly
  • Avoids creating temporary variables

Caution

  • Don’t chain too many methods in one line if it hurts readability.
  • Always know what each index refers to before using insert or replace — mistakes here can crash your program.

One More Example:

StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming").insert(4, "-").replace(5, 16, "Rocks");
System.out.println(sb);  // Output: Java-Rocks

Steps:

  1. append(” Programming”) → “Java Programming”
  2. insert(4, “-“) → “Java- Programming”
  3. replace(5, 16, “Rocks”) → replaces ” Programming” with “Rocks” ⇒ “Java-Rocks”

Method Chaining = multiple operations on the same object in a single, continuous line.
It works because methods like append, insert, and replace return the same object (this).
It’s elegant and powerful — especially with classes like StringBuilder that modify strings efficiently.

Performance Comparison (Loop Example)

We are trying to build a string that contains all numbers from 0 to 9999, one after the other.

We’ll compare:

  1. Using String (immutable)
  2. Using StringBuilder (mutable)

Let’s compare speed.

Using String:

String s = "";
for (int i = 0; i < 10000; i++) {
    s += i;
}

Let’s understand what happens in the background:

Strings in Java are immutable, which means:

  • Once a String is created, it cannot be changed.
  • Any operation like concatenation (+) creates a new String object.

Loop Behavior:

  • First iteration: s = “” + 0 ⇒ s becomes “0”
  • Second iteration: s = “0” + 1 ⇒ new string “01” is created
  • Third iteration: s = “01” + 2 ⇒ new string “012” is created
  • 10,000 iterations = 10,000 new String objects created in memory!

Result:

  • Huge memory waste
  • High CPU overhead for object creation and garbage collection
  • Very slow execution

Behind the scenes, Java uses a hidden StringBuilder for + in simple statements — but not inside loops! Inside loops, this results in repeated object creation.

Each + creates a new object. Very slow.

Using StringBuilder:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
    sb.append(i);
}

Let’s see how this works:

StringBuilder is mutable:

  • It does not create a new object on each append
  • It modifies the same object, reusing the buffer

Loop Behavior:

  • First iteration: sb = “0”
  • Second iteration: sb = “01”
  • All operations happen inside the same object

Result:

  • Fast execution (because no object creation overhead)
  • Efficient memory usage (default buffer expands only when needed)
  • Ideal for loop-based string operations

Much faster and memory-efficient. 🔥

Real Performance Comparison (Approximate)

Let’s say we measure time taken to run each version.

OperationTime TakenMemory Used
Using String (+)~2–10 secondsHigh (many objects)
Using StringBuilder< 100 msLow (1 object + buffer)

Real-World Use Cases

  • Creating dynamic HTML or SQL queries
  • Efficient log generation
  • Processing or building large text files
  • Repeated text transformations (e.g., reversing, replacing)

Interview Tip

Q1. Why use StringBuilder over String?

Ans: Because StringBuilder is mutable and more memory-efficient when performing multiple string modifications, like in loops.

Q2. What is the most efficient way to concatenate strings in a loop?

Ans: Use StringBuilder, because String is immutable and each + operation creates a new object, which is inefficient in loops.

Summary

ConceptExplanation
StringBuilderA mutable sequence of characters
Main AdvantageNo new object creation on modification
Important Methodsappend(), insert(), delete(), replace()
Use CaseString manipulation in single-threaded apps
PerformanceFaster than String and StringBuffer in most cases

Final Thoughts

StringBuilder is like a power tool for strings in Java. If your app modifies strings frequently, start using it. You’ll not only save memory but also improve performance, and that’s what great developers do!