Java StringBuilder offsetByCodePoints() Method

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

Definition

In Java, sb.offsetByCodePoints(index, codePointOffset) starts at UTF-16 position index and steps forward (positive) or backward (negative) by codePointOffset Unicode code points, returning the resulting UTF-16 char index.

Because insert(), delete(), and setLength() take UTF-16 char indexes, offsetByCodePoints() lets you calculate safe cut points that never slice a surrogate pair in half.

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.offsetByCodePoints(...). No import is needed because java.lang is always visible.

Syntax

Pass a starting UTF-16 index and a signed step count in code points.

Java
StringBuilder sb = new StringBuilder("A\\uD83D\\uDE00B");
int afterTwo = sb.offsetByCodePoints(0, 2);   // 3 (index of 'B')
int backTwo  = sb.offsetByCodePoints(4, -2);  // 1 (start of emoji)
CallWhat it does
sb.offsetByCodePoints(0, 2)Finds UTF-16 index after the first 2 code points.
sb.offsetByCodePoints(sb.length(), -1)Finds start index of the last code point.
sb.offsetByCodePoints(i, 0)Returns i (validates that i is in 0..length()).

If index lands in the middle of a surrogate pair, moving forward or backward steps past that half so it still counts cleanly.

Library declarations
Java
// java.lang.StringBuilder
public int offsetByCodePoints(int index, int codePointOffset)

Parameters

ParameterDescription
index (int)Starting UTF-16 index (0 <= index <= length()).
codePointOffset (int)Number of code points to move: positive for forward, negative for backward, 0 for no move.

Return Value

Return ValueDescription
intThe target UTF-16 index after stepping by codePointOffset code points.

Compare with Similar Methods

Navigating and editing StringBuilder by code points:

MethodHow it differs
codePointCount(a, b)Counts how many code points lie between two known UTF-16 indexes.
codePointAt(index)Reads the code point located at the index returned by offsetByCodePoints().
insert(offset, str)Inserts safely at the UTF-16 boundary found by offsetByCodePoints().
setLength(newLen)Truncates cleanly at an index returned by offsetByCodePoints().

Java Examples

Example 1 — Step Forward and Backward Over a Surrogate Pair

Test positive and negative offsets on "A\\uD83D\\uDE00B" to verify exact UTF-16 landing positions.

Java
public class StringBuilderOffsetStep {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("A\uD83D\uDE00B");
        int fwd = sb.offsetByCodePoints(0, 2);
        int back = sb.offsetByCodePoints(sb.length(), -2);

        System.out.println("length = " + sb.length());
        System.out.println("offsetByCodePoints(0, 2) = " + fwd + " -> char '" + sb.charAt(fwd) + "'");
        System.out.println("offsetByCodePoints(4, -2) = " + back + " -> 0x" + Integer.toHexString(sb.codePointAt(back)).toUpperCase());
    }
}

How It Works

  1. Step forward 2 code points. Starting at 0 skips 'A' (1 char) and 0x1F600 (2 chars), landing at index 3 ('B').
  2. Step backward 2 code points. Starting at 4 skips 'B' (1 char) and the emoji (2 chars), landing at index 1.
  3. Exact boundary reached. codePointAt(1) reads the complete 0x1F600 symbol.

Example 2 — Insert After N Code Points Without Splitting Emoji

Find the UTF-16 index after two characters in "A\\uD83D\\uDE00BC" and insert a separator right after the emoji.

Java
public class StringBuilderOffsetInsert {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("A\uD83D\uDE00BC");
        int cut = sb.offsetByCodePoints(0, 2);
        sb.insert(cut, '-');

        System.out.println("Cut index = " + cut);
        System.out.println("Char at 3 = " + sb.charAt(3) + ", tail = " + sb.substring(4));
        System.out.println("Total code points = " + sb.codePointCount(0, sb.length()));
    }
}

How It Works

  1. Avoid fixed index 2. Inserting at index 2 directly would split the emoji's high and low surrogates.
  2. Safe cut at 3. offsetByCodePoints(0, 2) places the hyphen neatly between the emoji and "BC".
  3. Valid structure kept. Every surrogate pair stays whole, totaling 5 code points.

Example 3 — Truncate to N Code Points Safely and Catch Overrun

Use offsetByCodePoints(0, limit) with setLength() to trim text cleanly, and catch stepping past the end.

Java
public class StringBuilderOffsetTruncate {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("A\uD83D\uDE00BC");
        int keepLimit = 2;
        if (sb.codePointCount(0, sb.length()) > keepLimit) {
            int newEnd = sb.offsetByCodePoints(0, keepLimit);
            sb.setLength(newEnd);
        }
        System.out.println("Truncated length = " + sb.length() + ", codePoints = " + sb.codePointCount(0, sb.length()));

        try {
            sb.offsetByCodePoints(0, 5);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Stepping past end threw IndexOutOfBoundsException");
        }
    }
}

How It Works

  1. Truncate cleanly. Keeping 2 code points stops at UTF-16 length 3, preserving 'A' and the complete emoji.
  2. Check before stepping. Calling codePointCount() first ensures keepLimit exists in the builder.
  3. Overstepping throws. Trying to step forward 5 code points when only 2 remain raises IndexOutOfBoundsException.

Frequently Asked Questions

It returns a zero-based UTF-16 char index inside the StringBuilder after moving codePointOffset code points from index.
Yes. A negative offset moves backward toward index 0, useful for finding the start of the last N characters.
substring(), insert(), and delete() use UTF-16 char indexes. Computing the index with offsetByCodePoints() prevents splitting a surrogate pair in half.
When index is outside 0..length(), or when stepping forward/backward by codePointOffset goes past the end or before index 0.
It returns index unchanged as long as 0 <= index <= length().

Next: replace()

Replace characters from start to end with a String (the builder grows or shrinks to fit).

replace() 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.

13 people found this page helpful