Java String.chars
Stream the UTF-16 units of a string as nonnegative int values.
A simple example
String.chars
- Start with "AB"
- Do this Read the two UTF-16 units
- Result 65, 66
class Main {
public static void main(String[] args) throws Exception {
System.out.println("AB".chars().boxed().toList());
}
}
[65, 66]
Syntax
public IntStream chars()
JDK 21 method signatures (1)
public IntStream chars()Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCount ASCII digits in a ticket label
A ticket identifier mixes digits with letters and punctuation. Count only the digit positions needed for the report instead of treating the entire printed label as one numeric value.
class Main {
public static void main(String[] args) throws Exception {
String ticket = "T-42";
System.out.println(ticket.chars().filter(c -> c >= '0' && c <= '9').count());
}
}
2
The filter accepts only the two ASCII digit units.
Measure the UTF-16 size of a reaction
A ticket includes a symbol outside the basic multilingual plane. Inspect its UTF-16 representation before using the string length as a count of what a reader sees on the screen.
class Main {
public static void main(String[] args) throws Exception {
String reaction = "😀";
System.out.println(reaction.chars().count());
}
}
2
This supplementary character is represented by two surrogate units.
Read a parcel sorting code
The depot scans a parcel marked NC-17. This identifier uses only ASCII characters. Count all characters, including the separator, to check the scanner’s length field.
What to watch for
Surrogate pairs produce two items. Use codePoints for a stream of complete Unicode code points.