The StringBuffer.replace() is the inbuilt method which is used to replace the characters in a substring of this sequence with the characters in the specified String. Here simply the characters in the substring are removed and other char is inserted at the start.
public StringBuffer replace(int first, int last, String st)
Parameters : The method accepts three parameters.
- first : This is of integer type which refers to the starting index.
- last : This is of integer type which refers to the the ending index.
- st : This is of string type which refer to the String that will replace previous contents.
Return Value : The method returns this object after performing the above mentioned operations.
Exception : If the first is negative, greater than length(), or greater than last then StringIndexOutOfBoundsException.
Input: StringBuffer= "The first planet of solar system is merrhxy" first = 39 last = 42 st = "cur" Output: The first planet of solar system is mercury
Below programs illustrate the java.lang.StringBuffer.replace() method:
string buffer = Welcome to Geekshssgeeks After replacing string buffer= Welcome to Geekforsgeeks
Program 2: When negative index is passed:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -15 at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:851) at java.lang.StringBuffer.replace(StringBuffer.java:452) at Geeks.main(Geeks.java:14)
Program 3: When index passed is greater than length
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start > length() at java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:853) at java.lang.StringBuffer.replace(StringBuffer.java:452) at Geeks.main(Geeks.java:14)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- StringBuffer reverse() Method in Java with Examples
- Formatted output in Java
- StringTokenizer class in Java with example | Set 1 ( Constructors)
- Super Keyword in Java
- StringBuffer delete() Method in Java with Examples
- HashSet vs TreeSet in Java
- ShortBuffer allocate() method in Java With Examples
- IntBuffer duplicate() method in Java with Examples
- ShortBuffer compact() method in Java With Examples
- LongBuffer equals() method in Java