CharBuffer chars() methods in Java with Examples
Last Updated :
19 Jan, 2023
The chars() method of java.nio.CharBuffer Class is used to return a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. The stream binds to this sequence when the terminal stream operation commences (specifically, for mutable sequences the spliterator for the stream is late-binding). If the sequence is modified during that operation then the result is undefined.
Syntax:
public IntStream chars()
Return Value: This method returns an IntStream of char values from this sequence. Below are the examples to illustrate the chars() method: Example 1:
Java
import java.nio.*;
import java.util.*;
import java.util.stream.IntStream;
public class GFG {
public static void main(String[] args)
{
CharBuffer charbuffer
= CharBuffer.allocate( 3 );
charbuffer.append( 'a' )
.append( 'b' )
.append( 'c' )
.rewind();
System.out.println("Original CharBuffer: "
+ Arrays.toString(
charbuffer.array())
+ "\n");
IntStream stream = charbuffer.chars();
stream.forEach(System.out::println);
}
}
|
Output:
Original CharBuffer: [a, b, c]
97
98
99
Example 2:
Java
import java.nio.*;
import java.util.*;
import java.util.stream.IntStream;
public class GFG {
public static void main(String[] args)
{
CharBuffer charbuffer
= CharBuffer.allocate( 5 );
charbuffer.append(( char ) 140 )
.append(( char ) 117 )
.append(( char ) 118 )
.append(( char ) 0 )
.append(( char ) 90 )
.rewind();
System.out.println("Original CharBuffer: "
+ Arrays.toString(
charbuffer.array())
+ "\n");
IntStream stream = charbuffer.chars();
stream.forEach(System.out::println);
}
}
|
Output:
Original CharBuffer: [?, u, v, , Z]
140
117
118
0
90
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/CharBuffer.html#chars–
Share your thoughts in the comments
Please Login to comment...