The getChar
method is defined for the ByteBuffer
class in Java. The getChar
method reads the next 2 bytes in ByteBuffer
and returns it as a char
. If the index
parameter variant of this method is used, then the position from which the bytes are read is specified by the index
argument.
public abstract char getChar()
public abstract char getChar(int index)
index
is an integer that specifies the index of the ByteBuffer
from which the bytes are to be read.char
composed of the 2 bytes read from the ByteBuffer
instance is returned.BufferUnderflowException
is thrown if the buffer’s position is not smaller than the size of the buffer.import java.nio.*;class Program {public static void main( String args[] ) {try {ByteBuffer buffer = ByteBuffer.allocate(20);buffer.asCharBuffer().put("Hello");char currentChar;System.out.println("Buffer Data: ");while ((currentChar = buffer.getChar()) != 0) {System.out.println(currentChar);}System.out.println("Buffer Data at index 0: ");System.out.println(buffer.getChar(0));} catch (BufferUnderflowException err) {System.out.println("\nError: " + err);}}}
A ByteBuffer
of 20 bytes is initialized and stored in the buffer
variable in the example above. Using the asCharBuffer
method, we treat this byte buffer as a CharBuffer
to put the string Hello
as a series of characters in buffer
. Then, we invoke the getChar
method to get the character and print it on the standard output until buffer
has reached its end. Lastly, we read and print the first character inside the buffer
by specifying the index
argument as 0.
Free Resources