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.
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
Parameter
Description
start (int)
Inclusive start index (0 <= start <= length()).
end (int)
Exclusive end index (end >= start). Values greater than length() are clamped to length().
Advance past replacement. Setting idx += to.length() ensures the search moves past "learn" and never re-matches inside replacement text.
Two replacements done. Both "go" occurrences expand in place to produce learn Java, learn!.
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).