VOOZH about

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

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


  • Courses
  • Tutorials
  • Interview Prep

ByteBuffer get() method in Java with Examples

Last Updated : 24 May, 2019
get()
The get() method of java.nio.ByteBuffer class is used to read the byte at the buffer's current position, and then increments the position. Syntax :
public abstract byte get()
Return Value: This method returns the byte 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 get() method: Examples 1:
Output:
Original ByteBuffer: [20, 30, 40, 0, 0]

Byte Value: 20

Next Byte Value: 30
Examples 2:
Output:
Original ByteBuffer: [20, 30, 0]

Byte Value: 0

since the buffer current position is incremented to greater than its limit 
Exception throws : java.nio.BufferUnderflowException
get(int index)
The get(int index) method of ByteBuffer is used to read the article at a specified index. Syntax :
public abstract byte get(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 Byte 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: [20, 30, 40]

Byte Value at index 0: 20

Byte Value at index 1: 30

Byte Value at index 2: 40
Examples 2:
Output:
Original ByteBuffer: [20, 30, 40]

Byte Value at index 0: 20

Byte Value at index 1: 30

Trying to get the byte of index greater than its limit 

Exception throws : java.lang.IndexOutOfBoundsException
Comment