Java.lang.StringBuilder.insert() Method



The java.lang.StringBuilder.insert(int index, char[] str, int offset, int len) method inserts the string representation of a subarray of the str array argument into this sequence.

The subarray begins at the specified offset and extends len chars. The characters of the subarray are inserted into this sequence at the position indicated by index. The length of this sequence increases by len chars.


Following is the declaration for java.lang.StringBuilder.insert() method

public StringBuilder insert(int index, char[] str, int offset, int len)


  • index − This is the position at which to insert subarray.

  • str − This is the character array.

  • offset − This is the index of the first char in subarray to be inserted.

  • len − This is the number of chars in the subarray to be inserted.

Return Value

This method returns this object.


StringIndexOutOfBoundsException − if index is negative or greater than length(), or offset or len are negative, or (offset+len) is greater than str.length.


The following example shows the usage of java.lang.StringBuilder.insert() method.

package com.tutorialspoint;

import java.lang.*;

public class StringBuilderDemo {

   public static void main(String[] args) {
      StringBuilder str = new StringBuilder("tutorials website");
      System.out.println("string = " + str);

      // character array to be inserted
      char cArr[] = { 'p', 'o', 'i', 'n', 't' };
      /* insert character array which begins at offset 9, extends
         to len 5 with specified index */
      str.insert(9, cArr, 0, 5);

      // prints StringBuilder after insertion
      System.out.print("After insertion = ");

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

string = tutorials website
After insertion = tutorialspoint website