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()
The get()
method does not accept any parameters.
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.
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 instanceByteBuffer newBuffer = ByteBuffer.allocate(5);byte values[] = {2, 1, 6, 7, 10};// add values to bufferfor(int i = 0; i < 5; i++){newBuffer.put(values[i]);}newBuffer.rewind();// Print bufferSystem.out.println("The ByteBuffer is: " + Arrays.toString(newBuffer.array()));// Using get() to return all buffer valuesSystem.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);}}}
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 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 , which returns the value at the current buffer position and increments the current buffer position by one.