Java StringBuffer replace() Method

replace(int startIndex, int endIndex, String str)

The replace the substring of the string buffer from startIndex to endIndex-1 with the specified string.

Syntax:

public synchronized  StringBuffer replace(int startIndex, int endIndex, String str)

 

Note: startIndex should be between 0 and to length of the string or less than endIndex, if it is not StringIndexOutOfBoundsException will be thrown.

 

Example:

class TestStringBuffer{
    StringBuffer sb = new StringBuffer("www.abc.com");
    
    public void replaceTest(){
        //replace the substring of the string buffer from 
        //startIndex to endIndex-1 with specified string.
        System.out.println(sb.replace(4,7,"w3schools"));
    }
}

public class StringBufferReplaceExample {
    public static void main(String args[]){
        //creating TestStringBuffer object
        TestStringBuffer obj = new TestStringBuffer();
        
        //method call
        obj.replaceTest();
    }
}

Output

www.w3schools.blog