Java StringBuilder.codePoints() – Examples

In this tutorial, we will learn about the Java StringBuilder.codePoints() function, and learn how to use this function to get the sequence as stream of code points, with the help of examples.

codePoints()

StringBuilder.codePoints() returns a stream of code point values from this StringBuilder sequence.

ADVERTISEMENT

Syntax

The syntax of codePoints() function is

codePoints()

Returns

The function returns IntStream of Unicode code points.

Example 1 – codePoints()

In this example, we will initialize a StringBuilder object, and get the stream of Unicode code points by calling codePoints() method on this StringBuilder object. And print all the code points using forEach() method.

Java Program

import java.util.stream.IntStream;

public class Example { 
    public static void main(String[] args) { 
        // create a StringBuilder object 
        StringBuilder stringBuilder = new StringBuilder("abcdefgh");

        IntStream codePoints = stringBuilder.codePoints(); 
        codePoints.forEach(codePoint -> {
        	System.out.println(codePoint);
        });
    }
}

Output

97
98
99
100
101
102
103
104

Example 2 – codePoints()

In this example, we will take null value for the StringBuilder, and try to call codePoints() on this null object. It should throw java.lang.NullPointerException.

Java Program

import java.util.stream.IntStream;

public class Example { 
    public static void main(String[] args) { 
        StringBuilder stringBuilder = null;
        IntStream codePoints = stringBuilder.codePoints();
    }
}

Output

Exception in thread "main" java.lang.NullPointerException
	at Example.main(Example.java:6)

Conclusion

In this Java Tutorial, we have learnt the syntax of Java StringBuilder.codePoints() function, and also learnt how to use this function with the help of examples.