.insert()

Published Aug 22, 2022
Contribute to Docs

The .insert() method places a sequence of characters into the StringBuilder and returns a reference to the object.

Syntax

myStringBuilder.insert(index, str);

The index argument is the zero-based index where the characters are to be inserted. If str is a String, a CharSequence*, or a char[] array**, the characters contained are inserted at index and its capacity is increased by the number of characters inserted. For other types, it behaves as if str was first converted to a string by using String.valueOf(str). If index is negative or greater than the length of the sequence, then a StringIndexOutOfBoundsException is thrown.

* For CharSequence arguments, .insert() can have two additional optional int arguments:

myStringBuilder.insert(index, str, start, end)

In this case, .insert() will insert the subsequence defined by the start and end points specified by start and end.

** For char[] arguments, .insert() can have two additional optional int arguments:

myStringBuilder.insert(index, str, start, len)

In this case, .insert() will insert the subsequence defined by the start point and length specified by start and len.

Example

The following example creates a StringBuilder with a specified String and then uses the .insert() method to change it:

import java.util.*;
public class Example {
public static void main(String[] args)
{
StringBuilder str = new StringBuilder("Hello World!");
System.out.println(str.toString());
str.insert(6, "to the ");
System.out.println(str.toString());
}
}

This produces the following output:

Hello World!
Hello to the World!

All contributors

Looking to contribute?

Learn Java on Codecademy