Java String codePointBefore(): Preceding Unicode Code Point Retrieval

The String.codePointBefore() method returns the Unicode code point (an integer value) immediately preceding the specified index in the string.

Backward Lookups & Surrogate Pairs: While forward lookups use codePointAt(), codePointBefore() looks backward from an index (ranging from 1 to length()) and automatically merges UTF-16 surrogate pairs. To count 32-bit Unicode characters across a range, see codePointCount(). For 16-bit character units, see charAt(). For substring extraction, explore substring().

1. Syntax & Method Signature 🔝

The codePointBefore() method is defined directly in java.lang.String:

 // Formal signature of String.codePointBefore() in java.lang.String
public int codePointBefore(int index)
Parameter / Element Type Description & Operational Rule
index int The 1-based index following the desired code point (valid range: 1 to length()).
Return Value int The 32-bit Unicode code point value before the given index.
Exception Runtime Throws IndexOutOfBoundsException if index < 1 or index > length().

2. Basic Backward Inspection Examples 🔝

Retrieving the character code point that occurs immediately before a specified index coordinate:

String my_str = "Welcome to plus2net";

 // 1. Character before index 1 is at index 0 ('W')
System.out.println("codePointBefore(1):  " + my_str.codePointBefore(1));   // 87 ('W')

 // 2. Character before index 3 is at index 2 ('l')
System.out.println("codePointBefore(3):  " + my_str.codePointBefore(3));   // 108 ('l')

 // 3. Character before index 15 is at index 14 ('s')
System.out.println("codePointBefore(15): " + my_str.codePointBefore(15));  // 115 ('s')

Terminal Output:

codePointBefore(1):  87
codePointBefore(3):  108
codePointBefore(15): 115

3. Inspecting the Last Character of a String 🔝

Passing str.length() into codePointBefore() directly retrieves the final character's Unicode code point, eliminating manual subtraction:

String my_str = "Welcome to plus2net";

 // Inspect the final character of the string by passing str.length()
int lastCharCp = my_str.codePointBefore(my_str.length());
System.out.println("Code point before length(): " + lastCharCp);  // 116 ('t')

 // Equivalent inspection using charAt() and length() - 1
char lastChar = my_str.charAt(my_str.length() - 1);
System.out.println("Character at length() - 1:  " + lastChar);    // 't'

Terminal Output:

Code point before length(): 116
Character at length() - 1:  t

4. Backward Surrogate Decoding for Emojis and Symbols 🔝

When an emoji resides at the end of a string, passing length() causes Java to look backward from index length() - 1 to length() - 2, merging both surrogate units into a single 32-bit code point:

 // String ending with a 32-bit supplementary character (Rocket emoji: 🚀)
String text = "Launch 🚀";

 // The emoji occupies two UTF-16 surrogate code units at text.length() - 2 and text.length() - 1
int endOfText = text.length();

 // codePointBefore() looks backward from endOfText, sees low + high surrogates, and returns 32-bit code point
int emojiCp = text.codePointBefore(endOfText);
System.out.println("codePointBefore(length): " + emojiCp);  // 128640 (0x1F680)
System.out.println("Hex Code Point:          U+" + Integer.toHexString(emojiCp).toUpperCase());

Terminal Output:

codePointBefore(length): 128640
Hex Code Point:          U+1F680

5. Comparison: codePointBefore() vs. codePointAt() 🔝

Understanding index boundary differences between forward and backward code point inspection:

Feature / Property codePointAt(int index) codePointBefore(int index)
Inspection Direction Forward from index to index + 1. Backward from index - 1 to index - 2.
Valid Index Range 0 to length() - 1. 1 to length().
Passing Index 0 Returns first character code point. Throws Exception (nothing before 0).
Passing length() Throws Exception (out of bounds). Returns final character code point.

6. Reverse Unicode Iteration with Character.charCount() 🔝

In a backward loop, decrementing the index by Character.charCount(codePoint) ensures you step cleanly over both 1-unit ASCII characters and 2-unit surrogate pair emojis:

String text = "A🚀B";

 // Backward iteration from text.length() down to 0
int i = text.length();
while (i > 0) {
    int cp = text.codePointBefore(i);
    System.out.println("Before index " + i + ": Code Point " + cp + " (" + new String(Character.toChars(cp)) + ")");
    i -= Character.charCount(cp);  // jumps backward by 2 for emojis, by 1 for ASCII!
}

Terminal Output:

Before index 4: Code Point 66 (B)
Before index 3: Code Point 128640 (🚀)
Before index 1: Code Point 65 (A)

7. The Index 0 Exception Trap 🔝

Calling codePointBefore(0) throws an immediate StringIndexOutOfBoundsException because no characters exist prior to index 0:

String str = "plus2net";

 // ERROR: Index 0 has no preceding character!
try {
    System.out.println(str.codePointBefore(0));
} catch (StringIndexOutOfBoundsException e) {
    System.out.println("Caught StringIndexOutOfBoundsException: index out of range: 0");
}

 // SAFE ACCESS: Ensure index is between 1 and str.length()
if (str.length() >= 1) {
    System.out.println("First char code point: " + str.codePointBefore(1));  // 112 ('p')
}

Terminal Output:

Caught StringIndexOutOfBoundsException: index out of range: 0
First char code point: 112

8. Production Recipe: Trailing Sentence Punctuation Validator 🔝

Validating whether an article headline or paragraph ends with standard sentence-ending punctuation without calling substring():

public class TrailingPunctuationValidator {
    public static boolean endsWithPunctuation(String s) {
        if (s == null || s.isEmpty()) return false;
        int lastCodePoint = s.codePointBefore(s.length());
        return lastCodePoint == '.' || lastCodePoint == '!' || lastCodePoint == '?';
    }

    public static void main(String[] args) {
        System.out.println("Hello world!: " + endsWithPunctuation("Hello world!"));  // true
        System.out.println("Hello world:  " + endsWithPunctuation("Hello world"));   // false
    }
}

Terminal Output:

Hello world!: true
Hello world:  false

9. Common Developer Pitfalls & Traps 🔝

Assuming Index 0 is Valid

Unlike charAt(0) and codePointAt(0), codePointBefore(0) is illegal and throws StringIndexOutOfBoundsException. The minimum valid index is always 1.

Stepping Backward with Simple i--

If a string contains emojis, decrementing with i-- lands inside the surrogate pair, causing subsequent calls to return orphaned surrogate units. Always decrement by i -= Character.charCount(cp).

10. Complete Compilable Java Program 🔝

You can compile and run this complete verification class locally in any Java IDE or environment:

public class StringCodePointBeforeFullDemo {
    public static void main(String[] args) {
        String greeting = "Java ☕";

         // 1. Verify code point of first character via index 1
        if (greeting.codePointBefore(1) == 74) {
            System.out.println("Check 1 Passed: First character 'J' has code point 74.");
        }

         // 2. Verify code point of last character via length()
        int lastCp = greeting.codePointBefore(greeting.length());
        if (lastCp == 9749) {
            System.out.println("Check 2 Passed: Coffee cup emoji has code point 9749.");
        }

         // 3. Verify bounds guarding against index 0
        boolean caught = false;
        try {
            greeting.codePointBefore(0);
        } catch (IndexOutOfBoundsException e) {
            caught = true;
        }
        if (caught) {
            System.out.println("Check 3 Passed: Index 0 successfully caught as out-of-bounds.");
        }

        System.out.println("All String.codePointBefore() verification checks passed successfully!");
    }
}

Terminal Output:

Check 1 Passed: First character 'J' has code point 74.
Check 2 Passed: Coffee cup emoji has code point 9749.
Check 3 Passed: Index 0 successfully caught as out-of-bounds.
All String.codePointBefore() verification checks passed successfully!

11. Frequently Asked Questions (FAQ) 🔝

Why does codePointBefore(length()) not throw an exception?

Because codePointBefore(k) inspects the character before index k. When k = length(), it inspects the character at index length() - 1, which is the valid final character.

How do I get the first character's code point using codePointBefore?

Pass index 1: str.codePointBefore(1) returns the code point of the character at index 0.

Is codePointBefore() an O(1) operation?

Yes. It performs a direct array lookup and checks whether the preceding character forms a surrogate pair in constant time.

What happens when calling codePointBefore() on an empty string?

For an empty string (""), length() is 0. Any index you pass (including 0 or 1) is out of bounds and throws StringIndexOutOfBoundsException. Guard with !str.isEmpty().

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer