Java StringBuffer insert() Method

insert(int offset, String str)

insert a specified string at the offset indicated position.

 

Syntax:

public synchronized StringBuffer insert(int offset, String str)

 

Note:

  • If the specified string is null then it inserts a “null” string at the offset indicated position.
  • If the insert has an object, int, double, etc instead of a string then the argument value is first converted into a string using String.valueOf()before inserting.
  • The offset should be between 0 and to length of the string, if it is not StringIndexOutOfBoundsException will be thrown.

Example:

class TestStringBuffer{
    StringBuffer sb = new StringBuffer("www.com");
    
    public void insertTest(){
        //insert specified string at 
                //the offset indicated position.
        System.out.println(sb.insert(3,".w3schools"));
    }
}

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

Output

www.w3schools.blog

 

Please follow and like us:
Content Protection by DMCA.com