
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are new methods added to the String class in Java 9?
In this article, we will learn about the new methods added to the String class in Java 9. We will learn about Strings and the new methods in the String class, along with examples.
Strings
A String is the type of object that contains a collection of characters enclosed by double quotes (" "). The Java platform provides the String class to create and manipulate strings in Java.
The String class is immutable, so that once it is created, a String object cannot be changed. String is the only class where operator overloading is supported in Java, we can concatenate two strings using the "+" operator.
Below is the basic syntax for creating a string in Java:
String str = "TutorialsPoint";
New Methods in the String Class
There are two new methods added to the String class in Java 9:
chars() Method
The chars() method of the String class can return a stream of int, zero-extending the char values from this sequence. The IntStream returned contains the character code point values from the given string.
The chars() method does not accept any parameters. If we use this method on a string with the null value, it throws a NullPointerException error.
Syntax
The following is the syntax for the chars() method declaration:
public IntStream chars()
Example
Below is an example of the chars() Method in Java:
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
codePoints() Method
The codePoints() method can return a stream of code points (Unicode) values from this sequence. The codePoints() method does not accept any parameters.
The code point values are similar to the ASCII values in Java. If we use this method on a string with the null value, it throws a NullPointerException error.
Syntax
The following is the syntax for the codePoints() method declaration:
public IntStream codePoints()
Example
Below is an example of the codePoints() Method in Java:
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