What are new methods added to the String class in Java 9?


A String is an immutable class in Java and there are two new methods added to the String class in Java 9. Those methods are chars() and codePoints(). Both of these two methods return the IntStream object.

1) chars():

The chars() method of String class can return a stream of int zero-extending the char values from this sequence.

Syntax

public IntStream chars()

Example

import java.util.stream.IntStream;

public class StringCharsMethodTest {
   public static void main(String args[]) {
      String str = "Welcome to TutorialsPoint";
      IntStream intStream = str.chars();
      intStream.forEach(x -> System.out.printf("-%s", (char)x));
   }
}

Output

-W-e-l-c-o-m-e- -t-o- -T-u-t-o-r-i-a-l-s-P-o-i-n-t


2) codePoints():

The codePoints() method can return a stream of code point values from this sequence.

Syntax

public IntStream codePoints()

Example

import java.util.stream.IntStream;

public class StringCodePointsMethodTest {
   public static void main(String args[]) {
      String str = "Welcome to Tutorix";
      IntStream intStream = str.codePoints();
      intStream.forEach(x -> System.out.print(new StringBuilder().appendCodePoint(x)));
   }
}

Output

Welcome to Tutorix

Updated on: 17-Mar-2020

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements