Java.lang.StringBuffer.replace() Method



The java.lang.StringBuffer.replace() method replaces the characters in a substring of this sequence with characters in the specified String.

The substring begins at the specified start 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.


Following is the declaration for java.lang.StringBuffer.replace() method

public StringBuffer replace(int start, int end, String str)


  • start − This is the beginning index, inclusive.

  • end − This is the ending index, exclusive.

  • str − This is the String that will replace previous contents.

Return Value

This method returns this object.


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


The following example shows the usage of java.lang.StringBuffer.replace() method.

package com.tutorialspoint;

import java.lang.*;

public class StringBufferDemo {

   public static void main(String[] args) {
      StringBuffer buff = new StringBuffer("Java Util Package");
      System.out.println("buffer = " + buff);

      // replace substring from index 5 to index 9
      buff.replace(5, 9, "Lang");

      // prints the stringbuffer after replacing
      System.out.println("After replacing: " + buff);

Let us compile and run the above program, this will produce the following result −

buffer = Java Util Package
After replacing: Java Lang Package