Java StringBuilder.chars() – Examples

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

chars()

StringBuilder.chars() returns a stream of int zero-extending the char values from this sequence.

The behavior of char() function is susceptible to changes in the StringBuilder sequence during read operations.

ADVERTISEMENT

Syntax

The syntax of chars() function is

chars()

Returns

The function returns IntStream object.

You may use forEach() on this integer stream, or convert it to an array using toArray() method..

Example 1 – chars()

In this example, we will create a StringBuilder object with some initial string literal. We will use StringBuilder.char() function to get a stream of integer values for the chars in sequence. We will use forEach() on this stream of integers and print them.

Java Program

public class Example { 
    public static void main(String[] args) { 
        // create a StringBuilder object 
        StringBuilder stringBuilder = new StringBuilder("abcdefgh");
        //print elements from integer stream
        stringBuilder.chars().forEach(i -> {
        	System.out.println(i);
        }); 
    } 
}

Output

97
98
99
100
101
102
103
104

Example 2 – chars()

In this example, we will create a StringBuilder object with some initial string literal. We will use StringBuilder.char() function to get a stream of integer values for the chars in sequence. We will use forEach() on this pipe line of integers, typecast each of the integer to char, and print them.

Java Program

public class Example { 
    public static void main(String[] args) { 
        // create a StringBuilder object 
        StringBuilder stringBuilder = new StringBuilder("abcdefgh");
        //print integers from pipe line as characters
        stringBuilder.chars().forEach(i -> {
        	System.out.println((char)i);
        }); 
    } 
}

Output

a
b
c
d
e
f
g
h

Example 3 – chars() – NullPointerException

In this example, we will create a StringBuilder object with null. When we call chars() on this null object, the function throws NullPointerException.

Java Program

public class Example { 
    public static void main(String[] args) { 
        // create a StringBuilder object 
        StringBuilder stringBuilder = null;
        //print elements from integer stream
        stringBuilder.chars().forEach(i -> {
        	System.out.println((char)i);
        }); 
    } 
}

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.chars() function, and also learnt how to use this function with the help of examples.