Java StringBuilder codePointBefore() Method

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

Definition

In Java, sb.codePointBefore(index) returns the int Unicode code point that ends immediately before UTF-16 cursor position index inside a StringBuilder.

If the character right before index is the low surrogate of a valid surrogate pair, it combines both halves into the full supplementary code point. Paired with delete(), it lets you pop the last whole Unicode character (even an emoji) cleanly.

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

Syntax

Pass a cursor position from 1 through sb.length() inclusive.

Java
StringBuilder sb = new StringBuilder("A\\uD83D\\uDE00B");
int emoji = sb.codePointBefore(3);              // 128512 (0x1F600)
int last  = sb.codePointBefore(sb.length());    // 66 ('B')
CallWhat it does
sb.codePointBefore(sb.length())Reads the final Unicode code point in the builder.
sb.codePointBefore(cursor)Reads the code point immediately left of cursor.
cursor -= Character.charCount(cp)Steps a backward loop past 1 or 2 char units.

Valid indexes for codePointBefore() are 1 to length() inclusive—never 0.

Library declarations
Java
// java.lang.StringBuilder
public int codePointBefore(int index)

Parameters

ParameterDescription
index (int)UTF-16 cursor index right after the target code point (1 <= index <= length()).

Return Value

Return ValueDescription
intThe Unicode code point immediately before index.

Compare with Similar Methods

Inspecting and deleting code points backward:

MethodHow it differs
codePointAt(index)Looks forward starting at index instead of backward.
delete(start, end)Deletes the full 1- or 2-char range measured via Character.charCount(cp).
offsetByCodePoints(idx, -n)Jumps backward by multiple code points in one call.
String.codePointBefore(index)Read-only equivalent on an immutable String.

Java Examples

Example 1 — Pop the Last Unicode Character Safely (Backspace Pattern)

Use codePointBefore(sb.length()) to delete the entire trailing emoji pair rather than leaving a broken half-surrogate.

Java
public class StringBuilderCodePointBeforePop {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("A\uD83D\uDE00");
        System.out.println("Start length = " + sb.length());

        int cp = sb.codePointBefore(sb.length());
        int width = Character.charCount(cp);
        sb.delete(sb.length() - width, sb.length());

        System.out.println("Popped 0x" + Integer.toHexString(cp).toUpperCase() + " (width " + width + ")");
        System.out.println("Remaining: " + sb.toString() + " (length=" + sb.length() + ")");
    }
}

How It Works

  1. Read trailing symbol. codePointBefore(3) merges indexes 1 and 2 into 0x1F600.
  2. Measure UTF-16 span. Character.charCount(cp) returns 2, telling us how far back to delete.
  3. Remove full character. Deleting indexes 1..3 leaves only "A" with zero leftover surrogate halves.

Example 2 — Inspect Positions Before Each Code Point

Check cursor positions 1, 3, and 4 on "A\\uD83D\\uDE00B".

Java
public class StringBuilderCodePointBeforePair {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("A\uD83D\uDE00B");
        System.out.println("before(1) = 0x" + Integer.toHexString(sb.codePointBefore(1)).toUpperCase());
        System.out.println("before(3) = " + sb.codePointBefore(3) + " (0x" + Integer.toHexString(sb.codePointBefore(3)).toUpperCase() + ")");
        System.out.println("before(4) = 0x" + Integer.toHexString(sb.codePointBefore(4)).toUpperCase());
    }
}

How It Works

  1. Cursor after 'A'. Position 1 sits between 'A' and the emoji, returning 0x41.
  2. Cursor after emoji. Position 3 looks left across indexes 2 and 1, uniting the surrogate pair into 128512.
  3. Cursor at length(). Position 4 sits after 'B' and returns 0x42.

Example 3 — Walk a Builder Backward and Catch Index 0

Scan right to left across a builder using Character.charCount(), then confirm codePointBefore(0) throws.

Java
public class StringBuilderCodePointBeforeLoop {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("X\uD83D\uDE80Y");
        for (int pos = sb.length(); pos > 0; ) {
            int cp = sb.codePointBefore(pos);
            System.out.println("before " + pos + " -> 0x" + Integer.toHexString(cp).toUpperCase());
            pos -= Character.charCount(cp);
        }

        try {
            sb.codePointBefore(0);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Index 0 threw IndexOutOfBoundsException");
        }
    }
}

How It Works

  1. Step left cleanly. Subtracting Character.charCount(cp) jumps from cursor 3 straight to 1 over the two-char emoji.
  2. Three characters visited. The loop reads 'Y', U+1F680, and 'X' in reverse order.
  3. Zero throws. Nothing lies before index 0, so codePointBefore(0) raises IndexOutOfBoundsException.

Frequently Asked Questions

Because no character exists before index 0. Valid cursor positions run from 1 to sb.length() inclusive.
Read cp = sb.codePointBefore(sb.length()), then call sb.delete(sb.length() - Character.charCount(cp), sb.length()).
It returns 128512 (0x1F600), because indexes 1 and 2 hold the high and low surrogate pair ending right before index 3.
IndexOutOfBoundsException when index < 1 or index > sb.length().
No. It only reads the code point and leaves the builder unchanged.

Next: codePointCount()

Count the Unicode code points in a range, treating each surrogate pair as one character.

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

12 people found this page helpful