Library contents

Java String.chars

Stream the UTF-16 units of a string as nonnegative int values.

A simple example

String.chars

  1. Start with "AB"
  2. Do this Read the two UTF-16 units
  3. Result 65, 66
The integer values for the uppercase letters A and B are 65 and 66.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("AB".chars().boxed().toList());
    }
}
Output
[65, 66]

Syntax

Java 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.java

Count 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.

From the programString ticket = "T-42"
Result2
Main.java
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());
    }
}
Output
2

The filter accepts only the two ASCII digit units.

Advertisements

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.

From the programString reaction = "😀"
Result2
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String reaction = "😀";
        System.out.println(reaction.chars().count());
    }
}
Output
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.

GivenNC-17
Worked result5

What to watch for

Surrogate pairs produce two items. Use codePoints for a stream of complete Unicode code points.

Documentation for String.chars