← All languages
Java method of the day
Random

StringBuilder.insert

Insert a value at a specified position in the character sequence.

Description

The insert() method inserts the string representation of the given argument into the StringBuilder at the specified offset. Characters at and after the offset are shifted to the right. Like append(), it accepts many types including String, char, int, double, boolean, and Object.

The offset must be greater than or equal to 0 and less than or equal to the current length of the sequence. An IndexOutOfBoundsException is thrown if the offset is invalid.

The method returns the same StringBuilder instance, allowing method chaining. This is useful for building formatted strings where values need to be placed at specific positions rather than just appended to the end.

Arguments

NameDescriptionOptional
offset The position at which to insert the value. No
value The value to insert. Can be a String, char, int, double, boolean, or Object. No

Example

StringBuilder sb = new StringBuilder("Hello World");
sb.insert(5, ",");
sb.toString(); // "Hello, World"

sb.insert(0, "Say: ");
sb.toString(); // "Say: Hello, World"

Reference