LongBuffer.wrap(long[], int, int) in Java

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

Syntax:

LongBuffer java.nio.LongBuffer.wrap(long[] array, 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 wraps a long array into a buffer.

Note: The new buffer will be backed by the given long array; that is, modifications to the buffer will cause the array to be modified and vice versa.

Parameters: Three parameters are required for this method.

array: The array that will back the new buffer.

offset: The offset of the subarray to be used; must be non-negative and no larger than array.length. The new buffer's position will be set to this value.

length: The length of the subarray to be used; must be non-negative and no larger than array.length - offset.The new buffer's limit will be set to offset + length.

Returns: The new long buffer.

Throws:

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 LongBufferwrap2 {
    public static void main(String[] args) {

        long array[] = { 1, 2, 3, 4 };

        int offset = 0;
        int length = 2;
        System.out.println(LongBuffer.wrap(array, offset, length));
    }
}

Output:

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


Approach 2: IndexOutOfBoundsException 

Java

import java.nio.LongBuffer;

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

        long array[] = { 1, 2, 3, 4 };

        int offset = 0;
        int length = 6;
        System.out.println(LongBuffer.wrap(array, offset, length));
    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.nio.LongBuffer.wrap(LongBuffer.java:408)


LongBuffer.wrap(long[])


No comments:

Post a Comment