Published Aug 22, 2022Updated Aug 22, 2022
Contribute to Docs

The .replace() method switches a substring in a StringBuilder with a specified String and returns the modified object.


myStringBuilder.replace(start, end, str);

Where start and end are the zero-based indices of the characters being replaced. The last character replaced is at end - 1, or the end of the sequence if end exceeds the length of the sequence. The characters are removed and the String str is inserted at start, the sequence lengthening if needed. If start is negative, greater than the end, or greater than the length of the sequence then a StringIndexOutOfBoundsException is thrown.


The following example creates a StringBuilder with a specified String and then uses the .replace() method to change its contents:

import java.util.*;
public class Example {
public static void main(String[] args)
StringBuilder str = new StringBuilder("Hello World!");

This produces the following output:

Hello World!
Hello Goodbye!

All contributors

Looking to contribute?

Learn Java on Codecademy