What is the String.chars method in Java?

Overview

The chars() method is an instance method of the String class. It returns an IntStream that consists of the code point values of the characters in the given string. This method was added to the String class in Java 9.

Syntax

public IntStream chars()

Parameters

This method has no parameters.

Return value

This method returns an IntStream of char values from the string.

Code

import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
// Define a string
String string = "hello-educative";
// use the chars method to get a stream of char values
IntStream codePointStream = string.chars();
// convert the code points back to characters and print the output
codePointStream.mapToObj(Character::toChars).forEach(System.out::println);
}
}

Explanation

  • Line 1: We import the relevant packages.
  • Line 6: We define a string called string.
  • Line 9: We use the chars() method to get a stream of character values.
  • Line 12: We convert the code points back to characters and print the output.