LongBuffer get(long[], int, int) in Java

get(long[], int, int): This method is available in java.nio.LongBuffer class of Java.

Syntax:

LongBuffer java.nio.LongBuffer.get(long[] dst, int offset, int length)

This method takes three arguments one of type long array and the other two are of type int as its parameters. This method transfers longs from this buffer into the given destination array.

Parameters: One parameter is required for this method.

dst: The array into which longs are to be written.

offset: The offset within the array of the first long to be written; must be non-negative and no larger than dst.length.

length: The maximum number of longs to be written to the given array; must be non-negative and no larger than dst.length - offset.

Returns: This buffer.

Throws:

1. BufferUnderflowException - If there are fewer than length longs remaining in this buffer.

2. IndexOutOfBoundsException - If the preconditions on the offset and length parameters do not hold

Approach 1: When no exceptions.

Java

import java.nio.LongBuffer;

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

        long array[] = { 1, 2, 3, 4 };
        LongBuffer lb = LongBuffer.wrap(array);

        long dst[] = { 1, 2, 3, 4 };
        int offset = 0;
        int length = 2;
        System.out.println(lb.get(dst, offset, length));
    }
}

Output:

java.nio.HeapLongBuffer[pos=2 lim=4 cap=4]


Approach 2: BufferUnderflowException

Java

import java.nio.LongBuffer;

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

        long array[] = { 1 };
        LongBuffer lb = LongBuffer.wrap(array);

        long dst[] = { 1, 2, 3 };
        int offset = 0;
        int length = 2;
        System.out.println(lb.get(dst, offset, length));
    }
}


Output:

Exception in thread "main" java.nio.BufferUnderflowException at java.base/java.nio.HeapLongBuffer.get(HeapLongBuffer.java:185)



Approach 3: IndexOutOfBoundsException

Java

import java.nio.LongBuffer;

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

        long array[] = { 1, 2, 3, 4 };
        LongBuffer lb = LongBuffer.wrap(array);

        long dst[] = { 1, 2, 3 };
        int offset = 0;
        int length = 4;
        System.out.println(lb.get(dst, offset, length));
    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Range [0, 0 + 4) out of bounds for length 3 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromIndexSize(Preconditions.java:82) at java.base/jdk.internal.util.Preconditions.checkFromIndexSize(Preconditions.java:343) at java.base/java.util.Objects.checkFromIndexSize(Objects.java:411) at java.base/java.nio.HeapLongBuffer.get(HeapLongBuffer.java:182)


No comments:

Post a Comment