Java.lang.StringBuffer.insert() Method



The java.lang.StringBuffer.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.StringBuffer.insert() method

public StringBuffer 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 offset.

  • 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.StringBuffer.insert() method.

package com.tutorialspoint;

import java.lang.*;

public class StringBufferDemo {

   public static void main(String[] args) {
   StringBuffer buff = new StringBuffer("tutorials website");
   System.out.println("buffer = " + buff);
   // 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 */
   buff.insert(9, cArr, 0, 5);
   // prints stringbuffer after insertion
   System.out.print("After insertion = ");

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

buffer = tutorials website
After insertion = tutorialspoint website