Java String codePointCount(): Measuring True Unicode Character Length

The String.codePointCount() method returns the number of Unicode code points (individual characters) in a specified index range of a string.

Surrogate Pairs & Human-Visible Length: While length() measures 16-bit UTF-16 code units, codePointCount() correctly treats 2-unit surrogate pair emojis as single characters. To retrieve the 32-bit code point at a specific index, see codePointAt() and codePointBefore(). For 16-bit code units, see charAt(), or check for empty text with isEmpty().

1. Syntax & Method Signature 🔝

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

 // Formal signature of String.codePointCount() in java.lang.String
public int codePointCount(int beginIndex, int endIndex)
Parameter / Element Type Description & Operational Rule
beginIndex int The 0-based index to the first char of the text range.
endIndex int The index after the last char of the text range (exclusive).
Return Value int The number of Unicode code points within the text range [beginIndex, endIndex).
Exception Runtime Throws IndexOutOfBoundsException if beginIndex < 0, endIndex > length(), or beginIndex > endIndex.

2. Basic Code Point Counting Examples 🔝

In standard Latin text where characters fit in a single 16-bit code unit, codePointCount() equals length():

String my_str = "Welcome to plus2net";

 // Count code points within the slice [0, 10)
System.out.println("Slice [0, 10):  " + my_str.codePointCount(0, 10));  // 10

 // Count total code points across the entire string
System.out.println("Total count:    " + my_str.codePointCount(0, my_str.length()));  // 19
System.out.println("length():       " + my_str.length());  // 19

Terminal Output:

Slice [0, 10):  10
Total count:    19
length():       19

3. The Emoji Surrogate Pair Delta: Code Units vs. Code Points 🔝

Supplementary Unicode characters (emojis like 🚀 and 🔥) require two 16-bit UTF-16 code units. length() counts 2, whereas codePointCount() accurately counts 1:

 // String containing emojis: 🚀 (Rocket) and 🔥 (Fire)
String status = "Launch 🚀🔥";

 // length() counts 16-bit UTF-16 code units (surrogate pairs occupy 2 units each)
System.out.println("status.length():         " + status.length());  // 11

 // codePointCount() counts true Unicode characters
int realCount = status.codePointCount(0, status.length());
System.out.println("codePointCount(0, len):  " + realCount);        // 9

Terminal Output:

status.length():         11
codePointCount(0, len):  9

4. Comparison: codePointCount() vs. length() 🔝

Key architectural differences between character measurement methods in Java:

Method Measured Entity Time Complexity Recommended Application
str.length() 16-bit UTF-16 code units O(1) constant time Buffer allocations, memory sizing, array bounds.
str.codePointCount(...) 32-bit Unicode code points O(N) range scan User input validation, social media post caps, internationalized text limits.

5. Measuring Code Points Within Specific Substring Slices 🔝

You can count code points in specific sections without creating temporary heap strings via substring():

String phrase = "Data: 🚀 Rocket";

 // Count code points in prefix before emoji
System.out.println("Prefix [0, 6): " + phrase.codePointCount(0, 6));  // 6 ("Data: ")

 // Count code points across emoji and suffix
System.out.println("Suffix [6, phrase.length()): " + phrase.codePointCount(6, phrase.length()));  // 8

Terminal Output:

Prefix [0, 6): 6
Suffix [6, phrase.length()): 8

6. Boundary Conditions & IndexOutOfBoundsException 🔝

The method enforces strict boundary conditions: beginIndex must not exceed endIndex, and endIndex cannot exceed length():

String str = "Java";

 // ERROR 1: beginIndex > endIndex throws IndexOutOfBoundsException
try {
    System.out.println(str.codePointCount(3, 1));
} catch (IndexOutOfBoundsException e) {
    System.out.println("Caught: beginIndex > endIndex!");
}

 // ERROR 2: endIndex > length() throws IndexOutOfBoundsException
try {
    System.out.println(str.codePointCount(0, 10));
} catch (IndexOutOfBoundsException e) {
    System.out.println("Caught: endIndex > length!");
}

Terminal Output:

Caught: beginIndex > endIndex!
Caught: endIndex > length!

7. Production Recipe: Detecting Emojis & Multi-Unit Characters 🔝

Instantly detecting whether user submissions contain supplementary characters or emojis by comparing code unit length with code point count:

public class EmojiDetector {
    public static boolean containsSupplementaryChars(String s) {
        if (s == null) return false;
         // If code units exceed code points, surrogate pairs exist!
        return s.length() != s.codePointCount(0, s.length());
    }

    public static void main(String[] args) {
        System.out.println("Has emojis? 'Hello':   " + containsSupplementaryChars("Hello"));    // false
        System.out.println("Has emojis? 'Hello 🚀': " + containsSupplementaryChars("Hello 🚀"));  // true
    }
}

Terminal Output:

Has emojis? 'Hello':   false
Has emojis? 'Hello 🚀': true

8. Practical Recipe: Social Media Post Length Validator 🔝

Validating message character thresholds where emojis must count as 1 character rather than 2 code units, trimming surrounding spaces with trim():

public class SocialMediaPostValidator {
    private static final int MAX_POST_LENGTH = 15;

    public static boolean isValidPostLength(String post) {
        if (post == null || post.trim().isEmpty()) return false;
        int actualChars = post.codePointCount(0, post.length());
        return actualChars <= MAX_POST_LENGTH;
    }

    public static void main(String[] args) {
        String post = "Launch now! 🚀🔥✨";
        System.out.println("UTF-16 length:     " + post.length());  // 18 (> 15)
        System.out.println("Human code points: " + post.codePointCount(0, post.length()));  // 15
        System.out.println("Is post valid?     " + isValidPostLength(post));  // true
    }
}

Terminal Output:

UTF-16 length:     18
Human code points: 15
Is post valid?     true

9. Common Developer Pitfalls & Traps 🔝

Assuming length() Matches User-Visible Characters

Relying on str.length() to enforce character limits on social media or SMS messages causes posts with emojis to prematurely hit length caps. Always use codePointCount(0, length()) for human-facing limits.

Inverted Range Indexing

Passing codePointCount(end, start) where start < end throws an immediate IndexOutOfBoundsException. The first argument must always be less than or equal to the second.

10. Complete Compilable Java Program 🔝

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

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

         // 1. Verify ASCII character count
        if ("plus2net".codePointCount(0, 8) == 8) {
            System.out.println("Check 1 Passed: ASCII string code point count equals 8.");
        }

         // 2. Verify surrogate pair reduction
        int codePoints = sample.codePointCount(0, sample.length());
        if (sample.length() == 7 && codePoints == 6) {
            System.out.println("Check 2 Passed: Rocket emoji occupies 2 code units but 1 code point.");
        }

         // 3. Verify empty range yields 0
        if (sample.codePointCount(2, 2) == 0) {
            System.out.println("Check 3 Passed: Identical begin and end indices yield count of 0.");
        }

        System.out.println("All String.codePointCount() unit checks passed successfully!");
    }
}

Terminal Output:

Check 1 Passed: ASCII string code point count equals 8.
Check 2 Passed: Rocket emoji occupies 2 code units but 1 code point.
Check 3 Passed: Identical begin and end indices yield count of 0.
All String.codePointCount() unit checks passed successfully!

11. Frequently Asked Questions (FAQ) 🔝

Why is codePointCount() O(N) while length() is O(1)?

Because strings store the total char array length in constant time. To count code points, Java must scan the character range to identify surrogate pairs.

What happens if beginIndex equals endIndex?

If beginIndex == endIndex, the text range is empty and codePointCount() returns 0 without error.

What if a string contains an unmatched, lone surrogate?

Java's specification states that unpaired or isolated surrogate code units count as one code point each.

How do I get the true character count of an entire string?

Call str.codePointCount(0, str.length()). This returns the exact number of Unicode code points across the entire text.

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