Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.chars()

Returns a stream of the character codes of a string.

Available since: Java 9

Syntax

public IntStream chars()

Return value

IntStreamAn IntStream — a stream of int values, one per char.

Examples

Counting vowels:

void main() {
    long vowels = "programming".chars()
            .filter(c -> "aeiou".indexOf(c) != -1)
            .count();
    IO.println(vowels);
}

Output:

3

The stream elements are numbers; cast to char to get characters:

void main() {
    "abc".chars().forEach(c -> IO.println(c + " " + (char) c));
}

Output:

97 a
98 b
99 c

Notes

The method is declared in the CharSequence interface since Java 8 and overridden in String in Java 9. For emoji and other characters outside the Basic Multilingual Plane use codePoints().

See also

Related recipes

In the tutorial

  • String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.

Thanks for reading!

Donate to the site — we work hard for you.