VOOZH about

URL: https://www.geeksforgeeks.org/java/bytebuffer-getchar-method-in-java-with-examples/

⇱ ByteBuffer getChar() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ByteBuffer getChar() method in Java with Examples

Last Updated : 19 Sep, 2023
getChar()
The getChar() method of java.nio.ByteBuffer class is used to get method for reading a char value Reads the next two bytes at this buffer's current position, composing them into a char value according to the current byte order, and then increments the position by two. Syntax:
public abstract char getChar()
Return Value: This method returns the char value at the buffer's current position Throws: This method throws BufferUnderflowException – If the buffer’s current position is not smaller than its limit, then this exception is thrown. Below are the examples to illustrate the getChar() method: Examples 1:
Output:
Original ByteBuffer: 
G e e k s 

Byte Value: G

Next Byte Value: e
Examples 2:
Output:
Original ByteBuffer: a b c 

First char Value: a

Second char Value: b

Third char Value: c

since the buffer current position is incremented to greater than its limit 
Exception Thrown: java.nio.BufferUnderflowException
get(int index)
The get(int index) method of ByteBuffer is used to reads two bytes at the given index, composing them into a char value according to the current byte order. Syntax:
public abstract char getChar(int index)
Parameters: This method takes index (The index from which the Byte will be read) as a parameter. Return Value: This method returns the char value at the given index. Exception: This method throws IndexOutOfBoundsException. If index is negative or not smaller than the buffer’s limit this exception is thrown. Below are the examples to illustrate the get(int index) method: Examples 1:
Output:
Original ByteBuffer: a b c 

char Value at index 0: a

char Value at index 2: b

char Value at index 4: c
Examples 2:
Output:
Original ByteBuffer: a b c 

char Value at index 0: a

char Value at index 2: b

Trying to get the char at a negative index 

Exception Thrown: java.lang.IndexOutOfBoundsException
Comment