ByteBuffer get() in Java

get(): This method is available in java.nio.ByteBuffer class of Java.

Syntax:

byte java.nio.ByteBuffer.get()

This method reads the byte at this buffer's current position, and then increments the position.

Parameters: NA

Returns: The byte at the buffer's current position.

Throws:

1. BufferUnderflowException - If the buffer's current position is not smaller than its limit

Approach 1: When no exceptions.

Java

import java.nio.ByteBuffer;

public class ByteBufferget {
    public static void main(String[] args) {

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);

        System.out.println(bb.get());

    }
}

Output:

1


Approach 2: BufferUnderflowException

Java

import java.nio.ByteBuffer;

public class ByteBufferget {
    public static void main(String[] args) {

        byte array[] = {};
        ByteBuffer bb = ByteBuffer.wrap(array);

        System.out.println(bb.get());

    }
}


Output:

Exception in thread "main" java.nio.BufferUnderflowException at java.base/java.nio.Buffer.nextGetIndex(Buffer.java:694) at java.base/java.nio.HeapByteBuffer.get(HeapByteBuffer.java:166)


No comments:

Post a Comment