Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

StringBuilder.insert()

Inserts a value at the given position of a StringBuilder.

Available since: Java 5

Syntax

public StringBuilder insert(int offset, Object obj)

Parameters

ParameterTypeDescription
offsetintThe index to insert before: 0 for the start, length() for the end.
objObject, String, int, char…What to insert.

Return value

StringBuilderThe same StringBuilder.

Examples

Inserting at the start and in the middle:

void main() {
    var sb = new StringBuilder("world");
    sb.insert(0, "Hello ");
    sb.insert(5, ",");
    IO.println(sb);
}

Output:

Hello, world

Thousands separators by hand — inserting from right to left:

void main() {
    var sb = new StringBuilder("1234567");
    for (int i = sb.length() - 3; i > 0; i -= 3) {
        sb.insert(i, ' ');
    }
    IO.println(sb);
}

Output:

1 234 567

Notes

An index outside 0..length() throws StringIndexOutOfBoundsException. Inserting at the start shifts all characters, so in a long loop it is cheaper to append and call reverse() at the end.

See also

In the tutorial

  • StringBuilder — StringBuilder in Java: a mutable string, append, insert, reverse, deleteCharAt, call chains and building a string in a loop.

Thanks for reading!

Donate to the site — we work hard for you.