Java .replace()
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.
Syntax
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.
Example
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!");System.out.println(str.toString());str.replace(6,11,"Goodbye");System.out.println(str.toString());}}
This produces the following output:
Hello World!Hello Goodbye!
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours