Java StringBuilder insert() method

insert(int offset, String str): insert a specified string at the offset indicated position.

Syntax:

public StringBuilder insert(int offset, String str)

 

Note:
  1. If the specified string is null then it inserts the “null” string at the offset indicated position.
  2. 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.
  3. The offset should be between 0 and to length of the string, if it is not StringIndexOutOfBoundsException will be thrown.

 

StringBuilder insert() Example

class TestStringBuilder{
    StringBuilder sb = new StringBuilder("www.com");

    public void insertTest(){
        //insert specified string at 
                //the offset indicated position.
        System.out.println(sb.insert(3,".w3schools"));
    }
}

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

Output

www.w3schools.blog

 

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