Java String codePointAt(): 32-Bit Unicode Code Point Retrieval

The String.codePointAt() method returns the Unicode code point (an integer value) at the specified character index in the string.

Surrogate Pairs & 32-Bit Character Decoding: Unlike charAt() which returns only a 16-bit char, codePointAt() automatically combines UTF-16 surrogate pairs to decode emojis and supplementary characters. To inspect code points preceding an index, see codePointBefore(). For total code point count, explore codePointCount(), or measure string size with length().

1. Syntax & Method Signature 🔝

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

 // Formal signature of String.codePointAt() in java.lang.String
public int codePointAt(int index)
Parameter / Element Type Description & Operational Rule
index int The 0-based code unit index in the string (ranges from 0 to length() - 1).
Return Value int The 32-bit Unicode code point value at the given index.
Exception Runtime Throws IndexOutOfBoundsException if index < 0 or index >= length().

2. Basic ASCII Code Point Examples 🔝

For standard ASCII and Latin characters, codePointAt() returns standard numeric character codes:

String my_str = "Welcome to plus2net";

 // Access ASCII code points at specific 0-based indices
System.out.println("codePointAt(0):  " + my_str.codePointAt(0));   // 87 ('W')
System.out.println("codePointAt(3):  " + my_str.codePointAt(3));   // 99 ('c')
System.out.println("codePointAt(15): " + my_str.codePointAt(15));  // 50 ('2')

Terminal Output:

codePointAt(0):  87
codePointAt(3):  99
codePointAt(15): 50

3. Emojis and Supplementary Characters (UTF-16 Surrogate Pairs) 🔝

Characters outside the Basic Multilingual Plane (such as emojis like 🚀) require two 16-bit code units. While charAt() returns an incomplete surrogate, codePointAt() returns the full 32-bit Unicode value:

 // String containing a 32-bit supplementary character (Rocket emoji: 🚀)
String text = "Rocket 🚀 launched";

 // The emoji is stored as 2 UTF-16 surrogate code units starting at index 7
int emojiIndex = 7;

 // charAt() returns only the high surrogate code unit (incomplete)
char highSurrogate = text.charAt(emojiIndex);
System.out.println("charAt(7):       " + (int) highSurrogate);           // 55357 (0xD83D)

 // codePointAt() automatically combines surrogate pairs into the full 32-bit code point
int fullCodePoint = text.codePointAt(emojiIndex);
System.out.println("codePointAt(7):  " + fullCodePoint);                  // 128640 (0x1F680)
System.out.println("Hex Code Point:  U+" + Integer.toHexString(fullCodePoint).toUpperCase());

Terminal Output:

charAt(7):       55357
codePointAt(7):  128640
Hex Code Point:  U+1F680

4. Comparison: codePointAt() vs. charAt() 🔝

Understanding when to use charAt() versus codePointAt() is essential for internationalized software:

Feature charAt(int index) codePointAt(int index)
Return Type 16-bit primitive char (0 to 65,535). 32-bit primitive int (0 to 1,114,111).
Emoji Handling Returns incomplete high or low surrogate. Combines surrogates into complete code point.
Primary Use Case Pure ASCII or 16-bit text parsing. Full Unicode text processing and emoji support.

5. Safe Unicode Iteration with Character.charCount() 🔝

Because supplementary code points span two char units, looping through strings requires advancing the index by Character.charCount(codePoint):

String text = "A🚀B";

 // SAFELY ITERATING: increment index by Character.charCount(codePoint)
int i = 0;
while (i < text.length()) {
    int cp = text.codePointAt(i);
    System.out.println("Index " + i + ": Code Point " + cp + " (" + new String(Character.toChars(cp)) + ")");
    i += Character.charCount(cp);  // jumps by 1 for ASCII, by 2 for emojis!
}

Terminal Output:

Index 0: Code Point 65 (A)
Index 1: Code Point 128640 (🚀)
Index 3: Code Point 66 (B)

6. Boundary Safety & IndexOutOfBoundsException 🔝

Indices must strictly stay within 0 and length() - 1. Passing length() raises an exception:

String str = "plus2net";

 // RISKY: Accessing str.length() throws IndexOutOfBoundsException
try {
    System.out.println(str.codePointAt(str.length()));
} catch (IndexOutOfBoundsException e) {
    System.out.println("Caught IndexOutOfBoundsException: index equals length!");
}

 // SAFE: The last valid index is length() - 1
int lastCp = str.codePointAt(str.length() - 1);
System.out.println("Last character code point: " + lastCp);  // 116 ('t')

Terminal Output:

Caught IndexOutOfBoundsException: index equals length!
Last character code point: 116

7. Production Recipe: Comprehensive Unicode Inspector 🔝

Printing formatted character tables with glyph, decimal code, and hexadecimal Unicode annotations:

public class UnicodeInspector {
    public static void inspect(String input) {
        if (input == null) return;
        for (int i = 0; i < input.length(); ) {
            int cp = input.codePointAt(i);
            String glyph = new String(Character.toChars(cp));
            System.out.printf("Char: %-2s | Dec: %-6d | Hex: U+%04X%n", glyph, cp, cp);
            i += Character.charCount(cp);
        }
    }

    public static void main(String[] args) {
        inspect("Java ☕");
    }
}

Terminal Output:

Char: J  | Dec: 74     | Hex: U+004A
Char: a  | Dec: 97     | Hex: U+0061
Char: v  | Dec: 118    | Hex: U+0076
Char: a  | Dec: 97     | Hex: U+0061
Char:    | Dec: 32     | Hex: U+0020
Char: ☕ | Dec: 9749   | Hex: U+2615

8. Practical Recipe: Pure ASCII String Validator 🔝

Validating whether an identifier or header consists strictly of 7-bit ASCII characters (values 0 through 127):

public class AsciiChecker {
    public static boolean isPureAscii(String s) {
        if (s == null) return false;
        for (int i = 0; i < s.length(); i++) {
            if (s.codePointAt(i) > 127) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println("hello:   " + isPureAscii("hello"));    // true
        System.out.println("café:    " + isPureAscii("café"));     // false (é > 127)
    }
}

Terminal Output:

hello:   true
café:    false

9. Common Developer Pitfalls & Traps 🔝

Accessing the Low-Surrogate Offset Directly

If an emoji spans indices 0 and 1, calling codePointAt(0) returns the combined 32-bit code point (128640). Calling codePointAt(1) returns the isolated low surrogate (56960). Always increment indices by Character.charCount().

Off-by-One Error on String Length

Passing str.length() into codePointAt() crashes with IndexOutOfBoundsException. The last character is located at str.length() - 1.

10. Complete Compilable Java Program 🔝

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

public class StringCodePointAtFullDemo {
    public static void main(String[] args) {
        String sample = "Java 🚀";

         // 1. Verify standard ASCII code point
        if (sample.codePointAt(0) == 74) {
            System.out.println("Check 1 Passed: 'J' evaluated to code point 74.");
        }

         // 2. Verify 32-bit surrogate pair code point for emoji
        int emojiCp = sample.codePointAt(5);
        if (emojiCp == 128640) {
            System.out.println("Check 2 Passed: Rocket emoji evaluated to code point 128640.");
        }

         // 3. Verify character count of supplementary character
        if (Character.charCount(emojiCp) == 2) {
            System.out.println("Check 3 Passed: Rocket emoji occupies 2 UTF-16 code units.");
        }

        System.out.println("All String.codePointAt() verification tests passed successfully!");
    }
}

Terminal Output:

Check 1 Passed: 'J' evaluated to code point 74.
Check 2 Passed: Rocket emoji evaluated to code point 128640.
Check 3 Passed: Rocket emoji occupies 2 UTF-16 code units.
All String.codePointAt() verification tests passed successfully!

11. Frequently Asked Questions (FAQ) 🔝

How do I convert a code point integer back to a String?

Use new String(Character.toChars(codePoint)) or Java 11's Character.toString(codePoint).

What is the difference between codePointAt() and codePointBefore()?

codePointAt(i) inspects the character at index i (and looks forward for a surrogate). codePointBefore(i) inspects the character at index i - 1 (and looks backward).

Is codePointAt() an O(1) operation?

Yes. It performs a direct array index lookup and checks if the character is in the surrogate range in constant time.

What happens when calling codePointAt() on a null string?

Calling null.codePointAt(0) throws a NullPointerException. Guard variables before accessing.

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