StringBuffer replace() method in Java

In this tutorial, we will learn about StringBuffer replace() method in Java.

StringBuffer class in Java provides replace() method. This method can be used to replace the characters in a String with the specified String. You need to pass the start index, end index and the substring to replace the characters in the String. The substring begins at the specified start index and extends to the character at index end – 1 or to the end of the sequence if no such character exists. First the characters in the substring are removed and then the specified String is inserted at start.

The syntax of replace() method is:

start – The beginning index, inclusive.
end – The ending index, exclusive.
str – String that will replace previous contents.

This object.

StringIndexOutOfBoundsException – if start is negative, greater than length(), or greater than end.



In the above program, we have used replace() method to replace the characters in the string from index 8 to 12 with substring “replace”.

Other tutorials:

StringBuffer in Java


Related posts

Leave a Comment