Java StringBuilder insert() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.lang.StringBuilder

Definition

In Java, sb.insert(offset, value) places text or a value's text form at offset, shifting later characters right as the buffer grows.

Every overload returns this for chaining. Offset 0 prepends at the start, and sb.length() appends at the end.

An instance method of the java.lang.StringBuilder class (since Java 1.5, JDK 1.5): a final, mutable sequence of UTF-16 characters that is not thread-safe. Call it on an existing builder, as in sb.insert(...). No import is needed because java.lang is always visible.

Syntax

Pass the zero-based target offset first, followed by the value or slice to insert.

Java
StringBuilder sb = new StringBuilder("World");
sb.insert(0, "Hello ");        // "Hello World"
sb.insert(5, ',');             // "Hello, World"
sb.insert(sb.length(), '!');   // "Hello, World!"
CallWhat it does
sb.insert(0, "prefix ")Prepends text at the start of the builder.
sb.insert(pos, 42)Inserts an int (or other primitive) at index pos.
sb.insert(sb.length(), " end")Valid boundary: inserts at the very end, just like append.
sb.insert(index, arr, off, len)Inserts a len-char slice from char[] arr at index.

Notice the parameter order in slice overloads: destination index in the builder comes first, followed by the source array or CharSequence and its range.

Library declarations
Java
// java.lang.StringBuilder
public StringBuilder insert(int offset, Object obj)
public StringBuilder insert(int offset, String str)
public StringBuilder insert(int offset, char[] str)
public StringBuilder insert(int index, char[] str, int offset, int len)
public StringBuilder insert(int dstOffset, CharSequence s)
public StringBuilder insert(int dstOffset, CharSequence s, int start, int end)
public StringBuilder insert(int offset, boolean b)
public StringBuilder insert(int offset, char c)
public StringBuilder insert(int offset, int i)
public StringBuilder insert(int offset, long l)
public StringBuilder insert(int offset, float f)
public StringBuilder insert(int offset, double d)

Parameters

ParameterDescription
offset / dstOffset / index (int)Zero-based insertion point in the builder, from 0 to length() inclusive.
str / obj / s / primitiveValue to convert to text and insert at that offset.
start, end / offset, lenOptional source bounds when inserting part of a CharSequence or char[].

Return Value

Return ValueDescription
StringBuilderA reference to this builder for chaining further edits.

Compare with Similar Methods

Editing positions inside a StringBuilder:

MethodHow it differs
append(x)Always adds at the end without shifting any existing characters.
replace(start, end, str)Overwrites an existing range instead of keeping both old and new characters.
setCharAt(index, ch)Replaces one existing char in place without changing length (returns void).
delete(start, end)Removes a range of characters and shifts the rest left.

Java Examples

Example 1 — Insert at Index 0, length(), and the Middle

Edit one builder in place at the front, the end, and between two words.

Java
public class StringBuilderInsertPositions {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("World");
        sb.insert(0, "Hello ");
        sb.insert(sb.length(), '!');
        sb.insert(5, ',');

        System.out.println(sb.toString());
        System.out.println("length = " + sb.length());
    }
}

How It Works

  1. Prepend at 0. insert(0, "Hello ") shifts "World" right by six places to form "Hello World".
  2. Insert at length(). Using sb.length() (11) places '!' right after the last character.
  3. Insert comma inside. insert(5, ',') slips a comma after "Hello", bumping length to 13.

Example 2 — Insert Thousand Separators and a char[] Slice

Walk backward to insert commas every three digits without invalidating earlier indexes, then insert part of a char[].

Java
public class StringBuilderInsertSeparators {
    public static void main(String[] args) {
        StringBuilder digits = new StringBuilder("1234567");
        for (int pos = digits.length() - 3; pos > 0; pos -= 3) {
            digits.insert(pos, ',');
        }
        System.out.println("Formatted: " + digits);

        char[] badge = {'V', 'I', 'P', '-', '9', '9'};
        StringBuilder label = new StringBuilder("User: []");
        label.insert(7, badge, 0, 3);
        System.out.println(label);
    }
}

How It Works

  1. Work right to left. Inserting at positions 4 and 1 keeps earlier digit indexes unchanged on the next iteration.
  2. Slice an array. label.insert(7, badge, 0, 3) copies the first three characters from badge right between '[' and ']'.
  3. Zero extra allocations. Both builds modify their buffers in place until printed.

Example 3 — Check Boundary Offsets and null Handling

Confirm that inserting at length() works (including for a null String), while length() + 1 throws.

Java
public class StringBuilderInsertBounds {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("Java");
        String nothing = null;
        sb.insert(sb.length(), '-').insert(sb.length(), nothing);
        System.out.println("After null insert: " + sb);

        try {
            sb.insert(sb.length() + 1, "x");
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("Out-of-bounds offset threw StringIndexOutOfBoundsException");
        }
    }
}

How It Works

  1. Chained end insert. Adding '-' at index 4 raises length to 5, so the second call reads the updated length().
  2. Null becomes "null". Because nothing has static type String, Java picks insert(int, String) and inserts four letters.
  3. Past length throws. Asking to insert at sb.length() + 1 violates the valid 0..length() range and throws StringIndexOutOfBoundsException.

Frequently Asked Questions

Any offset from 0 up to sb.length() inclusive. Offset 0 prepends to the start, and offset sb.length() appends to the end.
StringIndexOutOfBoundsException when offset is negative or greater than length(). The CharSequence slice overload throws IndexOutOfBoundsException for bad start/end bounds.
No. It edits the existing StringBuilder in place and returns this so you can chain calls.
A null String, Object, or CharSequence inserts the characters "null". A null char[] throws NullPointerException, and an uncast insert(0, null) is a compile error.
No, because each insert at index 0 shifts all existing characters to the right. For building reversed text, consider appending and calling reverse() once.

Next: lastIndexOf()

Find the starting index of the last matching String substring, or -1 if absent.

lastIndexOf() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful