Java StringBuilder replace() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.lang.StringBuilder

Definition

In Java, sb.replace(start, end, str) replaces the characters from index start (inclusive) to end (exclusive) with the characters of str. Unlike String, it modifies the builder in place and returns this.

str does not need to match the old span's length: the builder automatically grows when str is longer, shrinks when it is shorter, and acts like delete when str is empty.

An instance method of the java.lang.StringBuilder class (since Java 1.5, JDK 1.5): a final, mutable sequence of UTF-16 characters that is not thread-safe. Call it on an existing builder, as in sb.replace(...). No import is needed because java.lang is always visible.

Syntax

Pass start, end, and the replacement String—indexes first, string last.

Java
StringBuilder sb = new StringBuilder("Hello, World!");
sb.replace(7, 12, "Java");     // "Hello, Java!" (shorter string shrinks builder)
sb.replace(0, 5, "Welcome");   // "Welcome, Java!" (longer string grows builder)
CallWhat it does
sb.replace(0, 4, "Hi")Replaces indexes 0..3 with a shorter String.
sb.replace(5, 100, "!")end above length() clamps to length().
sb.replace(pos, pos + old.length(), next)Replaces a substring located via indexOf().
sb.replace(start, end, "")Deletes the range [start, end).

Notice the signature order: StringBuilder.replace(int start, int end, String str) swaps characters by index range, whereas String.replace(oldText, newText) searches by text.

Library declarations
Java
// java.lang.StringBuilder
public StringBuilder replace(int start, int end, String str)

Parameters

ParameterDescription
start (int)Inclusive start index (0 <= start <= length()).
end (int)Exclusive end index (end >= start). Values greater than length() are clamped to length().
str (String)The replacement String (must not be null).

Return Value

Return ValueDescription
StringBuilderA reference to this builder for chaining.

Compare with Similar Methods

Ways to update text in a StringBuilder:

MethodHow it differs
insert(offset, str)Adds str without removing any existing characters.
delete(start, end)Removes a range with no replacement (same as replacing with "").
setCharAt(index, ch)Overwrites one char at a single index (returns void).
indexOf(str)Finds the index range to pass to replace() when replacing by text.

Java Examples

Example 1 — Mask All Except the Last Four Digits

Keep the last four characters of a card number and replace the prefix in place.

Java
public class StringBuilderReplaceMask {
    public static void main(String[] args) {
        StringBuilder card = new StringBuilder("4111-2222-3333-4444");
        card.replace(0, card.length() - 4, "****-****-****-");
        System.out.println("Masked: " + card);
    }
}

How It Works

  1. Compute cut point. card.length() - 4 stops right before "4444" at index 15.
  2. Overwrite prefix. replace(0, 15, "****-****-****-") masks the first three groups in one call.
  3. Last four preserved. Only the targeted span changes, leaving 4444 intact.

Example 2 — Replace With Shorter or Longer Text and Clamp end

Watch length() shrink and grow in place, and verify that end > length() clamps safely.

Java
public class StringBuilderReplaceGrowShrink {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("I like cats and dogs");
        sb.replace(7, 11, "elephants");
        System.out.println("Grew (" + sb.length() + "):   " + sb);

        sb.replace(sb.indexOf("dogs"), 999, "birds!");
        System.out.println("Clamped (" + sb.length() + "): " + sb);
    }
}

How It Works

  1. Grow automatically. Replacing 4-letter "cats" (indexes 7..11) with 9-letter "elephants" expands length from 20 to 25.
  2. Find end span. indexOf("dogs") returns index 21 after the earlier expansion.
  3. Clamp end past length. Passing 999 clamps to the builder end, swapping "dogs" for "birds!".

Example 3 — Replace All Occurrences and Check null Rules

Loop with indexOf to replace every match in place, and verify that null throws NullPointerException.

Java
public class StringBuilderReplaceAllLoop {
    public static void main(String[] args) {
        StringBuilder text = new StringBuilder("go Java, go!");
        String from = "go";
        String to = "learn";

        int idx = 0;
        while ((idx = text.indexOf(from, idx)) != -1) {
            text.replace(idx, idx + from.length(), to);
            idx += to.length();
        }
        System.out.println(text);

        try {
            text.replace(0, 2, null);
        } catch (NullPointerException e) {
            System.out.println("null str threw NullPointerException");
        }
    }
}

How It Works

  1. Advance past replacement. Setting idx += to.length() ensures the search moves past "learn" and never re-matches inside replacement text.
  2. Two replacements done. Both "go" occurrences expand in place to produce learn Java, learn!.
  3. Null string rejected. Passing null as the third argument raises NullPointerException.

Frequently Asked Questions

StringBuilder.replace(start, end, str) replaces a range of indexes in place. String.replace(old, new) searches for matching characters or substrings and returns a new String.
Yes. StringBuilder automatically shifts trailing characters right or left and grows its buffer if str is longer.
end is clamped to sb.length(), replacing from start up to the end of the builder.
It throws NullPointerException. Unlike append(null), replace() does not convert null into "null".
Find its index with sb.indexOf(word), then call sb.replace(pos, pos + word.length(), replacement).

Next: reverse()

Reverse the characters in place, keeping valid surrogate pairs together in the right order.

reverse() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful