Home »
Java programming language
Java StringBuilder replace() method with example
StringBuilder Class replace() method: Here, we are going to learn about the replace() method of StringBuilder Class with its syntax and example.
Submitted by Preeti Jain, on December 22, 2019
StringBuilder Class replace() method
- replace() method is available in java.lang package.
- replace() method is used to replaces the set of character lies b/w beg and end parameter with the characters in the given string.
- replace() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- replace() method may throw an exception at the time of replacing a set of characters with the given string.
StringIndexOutOfBoundsException – This exception may throw when the first parameter beg < 0 , greater than length() or beg > end.
Syntax:
public StringBuilder replace(int beg, int end, String s);
Parameter(s):
- int beg – represents the starting index to replace the set of character.
- int end – represents the ending index till replace the set of characters.
- String s – represents the string that will replace contents b/w beg and end.
Return value:
The return type of this method is StringBuilder, it returns this StringBuilder object.
Example:
// Java program to demonstrate the example
// of replace (int beg , int end , String s)
// method of StringBuilder
public class Replace {
public static void main(String[] args) {
int beg = 5;
int end = 10;
String s = "Program";
// Creating an StringBuilder object
StringBuilder st_b = new StringBuilder("Java World ");
// Display st_b
System.out.println("st_b = " + st_b);
// By using replace(beg,end,s) method is to replace the string
// from index "beg" to index "end" in st_b with the given string
// ("Program")
st_b.replace(beg, end, s);
// Display st_b
System.out.println("st_b.replace(beg,end,s) = " + st_b);
}
}
Output
st_b = Java World
st_b.replace(beg,end,s) = Java Program