ByteBuffer getLong() in Java

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

Approach 1: When the method does not take any argument.

Syntax:

long java.nio.ByteBuffer.getLong()

This method reads the next eight bytes at this buffer's current position, composing them into a long value according to the current byte order, and then increments the position by eight.

Parameters: NA

Returns: The long value at the buffer's current position.

Throws:

BufferUnderflowException - If there are fewer than eight bytes remaining in this buffer

Java

import java.nio.ByteBuffer;

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

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

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

    }
}

Output:

72623859790382856


Approach 1.1: BufferUnderflowException

Java

import java.nio.ByteBuffer;

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

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

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

    }
}


Output:

Exception in thread "main" java.nio.BufferUnderflowException at java.base/java.nio.Buffer.nextGetIndex(Buffer.java:702) at java.base/java.nio.HeapByteBuffer.getLong(HeapByteBuffer.java:489)


Approach 2: When the method takes one argument of type int.

Syntax:

long java.nio.ByteBuffer.getLong(int index)

This method reads eight bytes at the given index, composing them into a long value according to the current byte order.

Parameters: One parameter is required for this method.

index: The index from which the bytes will be read.

Returns: The long value at the given index.

Throws:

IndexOutOfBoundsException - If the index is negative or not smaller than the buffer's limit, minus seven

Java

import java.nio.ByteBuffer;

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

        byte array[] = { 123456789 };
        ByteBuffer bb = ByteBuffer.wrap(array);
        int index = 0;
        System.out.println(bb.getLong(index));

    }
}

Output:

72623859790382856


Approach 2.1: IndexOutOfBoundsException 

Java

import java.nio.ByteBuffer;

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

        byte array[] = { 123456789 };
        ByteBuffer bb = ByteBuffer.wrap(array);
        int index = -1;
        System.out.println(bb.getLong(index));

    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.nio.Buffer.checkIndex(Buffer.java:744) at java.base/java.nio.HeapByteBuffer.getLong(HeapByteBuffer.java:494)


No comments:

Post a Comment