Java StringBuffer example to insert a string or charSeq in a StringBuffer at the specified position using insert

public StringBuffer insert(int offset,String str)
Inserts the string into this character sequence.
The characters of the String argument are inserted, in order, into this sequence at the indicated offset, moving up any characters originally above that position and increasing the length of this sequence by the length of the argument. If str is null, then the four characters "null" are inserted into this sequence.
The character at index k in the new character sequence is equal to:

the character at index k in the old character sequence, if k is less than offset
the character at index k-offset in the argument str, if k is not less than offset but is less than offset+str.length()
the character at index k-str.length() in the old character sequence, if k is not less than offset+str.length()
The offset argument must be greater than or equal to 0, and less than or equal to the length of this sequence.

package com.candidjava;

public class StringBufferInsert 
    public static void main(String[] args) 
        StringBuffer sb = new StringBuffer("Stu_Name  Stu_Age  Stu_Rank");
        sb.insert(8, "  Stu_Id");

Stu_Name Stu_Id Stu_Age Stu_Rank

Here the Stu_Id is inserted at the offset position 8 in the StringBuffer.

offset - the offset.
str - a string.

a reference to this object.

StringIndexOutOfBoundsException - if the offset is invalid.

Related Post