What is the ByteBuffer get() method in Java?

The get() method of the ByteBuffer class in Java returns the byte at the current buffer position in a ByteBuffer object. The current buffer position is also incremented.

The process is illustrated below:

To use the get() method, you will need to import the ByteBuffer class into your program, as shown below:

import java.nio.ByteBuffer

The prototype of the get() method is shown below:

public abstract byte get()

Parameters

The get() method does not accept any parameters.

Return value

The get() method returns the byte at the current buffer position. If the current buffer position exceeds the length of the buffer, the get() method throws a BufferUnderflowException.

Example

The code below shows how the get() method can be used in Java:

import java.nio.*;
import java.util.*;
class getMethods {
public static void main(String[] args) {
// initialize buffer instance
ByteBuffer newBuffer = ByteBuffer.allocate(5);
byte values[] = {2, 1, 6, 7, 10};
// add values to buffer
for(int i = 0; i < 5; i++)
{
newBuffer.put(values[i]);
}
newBuffer.rewind();
// Print buffer
System.out.println("The ByteBuffer is: " + Arrays.toString(newBuffer.array()));
// Using get() to return all buffer values
System.out.println("\nUsing get() to return buffer values:");
for(int i = 0; i < 5; i++)
{
byte current_val = newBuffer.get();
System.out.println(current_val);
}
}
}

Explanation

First, a ByteBuffer object called newBuffer is initialized through the allocate() method.

Since newBuffer has the capacity to store five elements, the put() method is repeatedly invoked in a for-loop to add values to the buffer. The rewind() method in line 1818 sets the current buffer position to the start of the buffer, i.e., index 0.

Next, a for-loop is used to extract each value stored in the buffer. Each loop iteration invokes the get() method in line 2727, which returns the value at the current buffer position and increments the current buffer position by one.

Free Resources