The codePointCount() method counts how many Unicode code points appear in a slice of a string. Unlike length(), it treats emoji and other supplementary characters as a single symbol—essential for accurate text limits and validation.
01
Count Code Points
Real character count.
02
Index Range
beginIndex to endIndex.
03
Half-Open Range
Inclusive start, exclusive end.
04
Emoji = One
Not two like length().
05
vs length()
Code units vs code points.
06
Text Limits
Tweets, forms, UI caps.
Fundamentals
Definition and Usage
In Java, codePointCount(int beginIndex, int endIndex) belongs to java.lang.String. It answers the question: “How many Unicode characters (code points) lie between these two indexes?” The indexes themselves refer to UTF-16 code unit positions, the same numbering used by charAt() and substring().
The range follows Java’s usual half-open convention: include the code point at beginIndex, exclude whatever starts at endIndex. Calling codePointCount(0, str.length()) counts every visible character in the entire string.
💡
Beginner Tip
Think of codePointCount(a, b) as the Unicode-aware version of counting characters in substring(a, b). If your string has no emoji, the result often equals b - a. When emoji appear, codePointCount is smaller than the char difference because each emoji is one code point but two chars.
Foundation
📝 Syntax
The codePointCount() method is declared in the String class:
java
public int codePointCount(int beginIndex, int endIndex)
Parameters
beginIndex — the starting index (inclusive). Must be between 0 and length().
endIndex — the ending index (exclusive). Must be between beginIndex and length().
Return Value
Returns the number of Unicode code points in the range [beginIndex, endIndex).
Exceptions
Throws StringIndexOutOfBoundsException if beginIndex is negative, greater than endIndex, or greater than the string length; or if endIndex is negative or greater than the string length.
Cheat Sheet
⚡ Quick Reference
String
Call
Result
"Hello"
codePointCount(0, 5)
5
"Hi 😀"
length()
5 (UTF-16 units)
"Hi 😀"
codePointCount(0, 5)
4 (visible chars)
"Java"
codePointCount(1, 3)
2 ("av")
"Java"
codePointCount(2, 2)
0 (empty range)
Full string
s.codePointCount(0, s.length())
Total code points
Substring
s.codePointCount(2, 6)
Count in a range
Compare
end - begin
Equals only without emoji
Modern API
s.codePoints().count()
Java 8+ stream alternative
Hands-On
Examples Gallery
Run these in Java 8+. They progress from a simple full-string count to emoji-aware ranges and comparison with length().
📚 Getting Started
Count every code point in a string that includes an emoji rocket.
Example 1 — Count Code Points in the Entire String
The string "Java🚀Programming" has 16 visible characters but 17 UTF-16 code units because the rocket emoji uses a surrogate pair.
java
public class CodePointCountExample {
public static void main(String[] args) {
String str = "Java\uD83D\uDE80Programming";
int codePoints = str.codePointCount(0, str.length());
int charUnits = str.length();
System.out.println("Code points (entire string): " + codePoints);
System.out.println("UTF-16 length(): " + charUnits);
}
}
codePointCount(0, length()) counts 4 letters + 1 emoji + 11 letters in Programming = 16 code points. length() adds an extra unit for the second half of the emoji surrogate pair.
Example 2 — Emoji Makes length() Misleading
A short greeting with one emoji shows why UI character limits should use code points, not length().
java
public class EmojiCount {
public static void main(String[] args) {
String greeting = "Hi 😀";
System.out.println("Visible characters: " +
greeting.codePointCount(0, greeting.length()));
System.out.println("length() returns: " + greeting.length());
}
}
📤 Output:
Visible characters: 4
length() returns: 5
How It Works
Users see four characters: H, i, space, and 😀. Java’s length() reports five because the emoji occupies two char slots. codePointCount() matches user expectations.
📈 Practical Patterns
Partial ranges, comparisons, and real-world validation.
Example 3 — Count Code Points in a Partial Range
Count from index 5 to the end of the rocket string. Java adjusts when beginIndex lands inside a surrogate pair.
java
public class PartialRangeCount {
public static void main(String[] args) {
String str = "Java\uD83D\uDE80Programming";
int full = str.codePointCount(0, str.length());
int partial = str.codePointCount(5, str.length());
System.out.println("Full string: " + full + " code points");
System.out.println("From index 5: " + partial + " code points");
}
}
📤 Output:
Full string: 16 code points
From index 5: 12 code points
How It Works
Index 5 is the low surrogate of the rocket. Java treats it as part of the emoji and counts the rocket plus all of Programming (11 letters) = 12 code points. The first four letters (Java) are excluded.
Example 4 — codePointCount() on a Plain ASCII Substring
When no supplementary characters are in the range, the count equals the index difference.
java
public class AsciiRangeCount {
public static void main(String[] args) {
String word = "Programming";
int begin = 0;
int end = 4;
int cpCount = word.codePointCount(begin, end);
int charDiff = end - begin;
System.out.println("codePointCount(0, 4): " + cpCount);
System.out.println("end - begin: " + charDiff);
System.out.println("Substring: \"" + word.substring(begin, end) + "\"");
}
}
📤 Output:
codePointCount(0, 4): 4
end - begin: 4
Substring: "Prog"
How It Works
For BMP-only (basic) text, each code point equals one char, so codePointCount(a, b) matches b - a. The difference only matters once emoji or rare scripts enter the string.
Example 5 — Validate a 10-Character User Input Limit
A practical use: reject input that exceeds ten visible characters, even when emoji are allowed.
java
public class InputLimitCheck {
private static final int MAX_CODE_POINTS = 10;
public static boolean isWithinLimit(String input) {
if (input == null) return true;
return input.codePointCount(0, input.length()) <= MAX_CODE_POINTS;
}
public static void main(String[] args) {
System.out.println(isWithinLimit("Hello")); // true
System.out.println(isWithinLimit("1234567890")); // true
System.out.println(isWithinLimit("12345678901")); // false
System.out.println(isWithinLimit("Hi 😀😀😀")); // true (6 visible)
}
}
📤 Output:
true
true
false
true
How It Works
Using length() here would under-count emoji (each counts as 2 toward the limit unfairly). codePointCount(0, length()) aligns with what the user actually typed on screen.
Applications
🚀 Common Use Cases
Input validation — enforce “max 280 characters” style limits that match visible symbols.
Substring planning — know how many real characters a char-index range covers before slicing.
Internationalization — count user-visible glyphs in multilingual forms and chat apps.
Progress indicators — show “12 of 50 characters” accurately when emoji are allowed.
Testing Unicode handling — verify that parsers treat supplementary characters as single units.
🧠 How codePointCount() Works
1
You define a range
Pass beginIndex (inclusive) and endIndex (exclusive) in UTF-16 units.
Input
2
Bounds are checked
Invalid ranges throw StringIndexOutOfBoundsException before counting begins.
Validate
3
Surrogate pairs merge
Each supplementary character in the range contributes one to the total, even though it spans two char values.
Unicode
=
📊
int count
The number of Unicode code points in [beginIndex, endIndex).
Important
📝 Notes
The range is half-open: include beginIndex, exclude endIndex—same as substring(beginIndex, endIndex).
When beginIndex == endIndex, the result is 0 (empty range).
Surrogate pairs count as one code point, not two.
Indexes refer to UTF-16 code units, not bytes in a file or network buffer.
In Java 8+, str.codePoints().count() counts all code points in the full string as an alternative API.
Performance
⚡ Optimization
codePointCount() scans the specified range once (O(endIndex - beginIndex)). For a one-time full-string count, it is efficient and clearer than manual loops. If you already iterate code points with codePoints() or need repeated counts on huge strings, profile before optimizing—for typical form validation and UI limits, this method is the right balance of correctness and simplicity.
Wrap Up
Conclusion
The codePointCount() method gives you an accurate character count for any slice of a Java string. It is the counting companion to codePointAt() and codePointBefore() in the Unicode indexing toolkit.
Use it whenever length() might mislead—emoji, global text, and user-facing limits. For ASCII-only utilities, endIndex - beginIndex still works; for modern apps, default to code points.
Use codePointCount(0, length()) for visible character totals
Match range semantics with substring(begin, end)
Validate beginIndex <= endIndex before calling
Prefer code points for user-facing length limits
Combine with codePointAt() when walking strings
❌ Don’t
Use length() alone for emoji-aware character caps
Assume end - begin always equals the code point count
Pass endIndex greater than length()
Confuse code point count with byte length in UTF-8 files
Split strings mid-surrogate based on char counts alone
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about codePointCount()
Use these points when counting characters in Java strings.
5
Core concepts
📊01
Counts Code Points
Visible character total.
Purpose
📏02
Two Indexes
begin inclusive, end exclusive.
Syntax
😀03
Emoji = 1
Not 2 like length().
Unicode
🛡04
Input Limits
Fair user validation.
Use case
🔄05
Like substring
Same range rules.
Pattern
❓ Frequently Asked Questions
codePointCount(int beginIndex, int endIndex) returns how many Unicode code points appear in the half-open range from beginIndex (inclusive) to endIndex (exclusive), measured in UTF-16 code unit positions.
Call it on any String: string.codePointCount(beginIndex, endIndex). Both parameters are int indexes into the string's UTF-16 storage.
length() counts UTF-16 code units (char positions). codePointCount(0, length()) counts visible Unicode characters. Emoji and other supplementary characters occupy two code units but count as one code point.
beginIndex must be between 0 and length() inclusive. endIndex must be between beginIndex and length() inclusive. Violations throw StringIndexOutOfBoundsException.
Yes. The range is inclusive at the start and exclusive at the end—the same convention as String.substring(beginIndex, endIndex).
Use it when you need an accurate character count for display limits, validation, or slicing international text—especially when emoji or non-BMP scripts may be present.