Java StringBuilder insert() method

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

Syntax:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public StringBuilder insert(int offset, String str)
public StringBuilder insert(int offset, String str)
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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();
}
}
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(); } }
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
www.w3schools.blog
www.w3schools.blog
www.w3schools.blog