ByteBuffer getDouble() in Java

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

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

Syntax:

double java.nio.ByteBuffer.getDouble()

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

Parameters: NA

Returns: The double 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 ByteBuffergetDouble {
    public static void main(String[] args) {

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

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

    }
}

Output:

8.20788039913184E-304


Approach 1.2: BufferUnderflowException

Java

import java.nio.ByteBuffer;

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

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

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

    }
}


Output:

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


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

Syntax:

double java.nio.ByteBuffer.getDouble(int index)

This method takes one argument of type int as its parameter. This method reads eight bytes at the given index, composing them into a double 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 double value at the given index.

Throws:

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

Java

import java.nio.ByteBuffer;

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

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

    }
}

Output:

8.207880453667947E-304


Approach 2.1: IndexOutOfBoundsException

Java

import java.nio.ByteBuffer;

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

        byte array[] = { 1234789010 };
        ByteBuffer bb = ByteBuffer.wrap(array);
        int index = -1;
        System.out.println(bb.getDouble(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.getDouble(HeapByteBuffer.java:611)


No comments:

Post a Comment