Java StringBuilder insert() Method
Example
Insert the word "Java " at position 6:
StringBuilder sb = new StringBuilder("Hello World");
sb.insert(6, "Java ");
System.out.println(sb);
Definition and Usage
The insert() method inserts text or a value at the specified position. The characters after that position move to the right.
It works with strings, characters, numbers, booleans and objects. Values that are not text are converted to text first.
Syntax
One of the following:
public StringBuilder insert(int index, type value)
public StringBuilder insert(int index, char[] str, int offset, int len)
public StringBuilder insert(int index, CharSequence s, int start, int end)
type can be String, char, int, long, float, double, boolean, char[], CharSequence or Object.
Parameter Values
| Parameter | Description |
|---|---|
| index | Required. The position to insert at. |
| value | Required. The value to insert. |
| str | A char array to take characters from. |
| offset | The index of the first character to take from the array. |
| len | The number of characters to take from the array. |
| s | A CharSequence, like a String, to take characters from. |
| start | The index of the first character to take from s. |
| end | The index after the last character to take from s. |
Technical Details
| Returns: | The same StringBuilder, with the value inserted. |
|---|---|
| Throws: | StringIndexOutOfBoundsException - if index is negative or larger than the length. |
Related Pages
❮ StringBuilder Methods