Java StringBuilder insert() Method



The Java StringBuilder insert() method is used to insert a string passed argument into a StringBuilder object.

The insert() method accepts different types of an argument, such as Boolean, int, char, and so on. It throws an exception if the given offset is not valid.

The insert() method has 12 polymorphic variants with different parameters: Boolean, char, char[], CharSequnevce, double, float, int, long, object, String, and StringBuilder. (Below are the syntaxes of all the polymorphic variants).

The offset argument must be greater than or equal to 0, and less than or equal to the length of this sequence.

Syntax

Following is the syntax of the Java StringBuilder insert() method −

public StringBuilder insert(int offset, boolean b)// first syntax 
public StringBuilder insert(int offset, char c)// second syntax
public StringBuilder insert(int offset, char[] str)// third syntax
public StringBuilder insert(int index, char[] str, int offset, int len)// fourth syntax
public StringBuilder insert(int dstOffset, CharSequence s)// fifth syntax
public StringBuilder insert(int dstOffset, CharSequence s, int start, int end)// sixth syntax
public StringBuilder insert(int offset, double d)// seven syntax
public StringBuilder insert(int offset, float f)// eight syntax
public StringBuilder insert(int offset, int i)// nine syntax
public StringBuilder insert(int offset, long l)// ten syntax
public StringBuilder insert(int offset, Object obj)// eleven syntax
public StringBuilder insert(int offset, String str)// twelve syntax 

Parameters

  • offset − This is the offset.

  • b − This is the boolean value.

  • c − This is the char value.

  • strch − This is the character array.

  • index − This is the position at which to insert sub-array.

  • len − This is the number of chars in the sub-array to be inserted.

  • dstoffset − This is the offset.

  • s − This is the sequence to be inserted.

  • start − This is the starting index of the subsequence to be inserted.