LongBuffer get(int) in Java

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

Syntax:

long java.nio.LongBuffer.get(int index)

This method takes one argument of type int as its parameter. This method reads the long at the given index.

Parameters: One parameter is required for this method.

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

Returns: The long at the given index.

Throws:

IndexOutOfBoundsException - If the index is negative or not smaller than the buffer's limit.

Approach 1: When no exceptions.

Java

import java.nio.LongBuffer;

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

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

        int index = 2;
        System.out.println(lb.get(index));
    }
}

Output:

3


Approach 2: IndexOutOfBoundsException 

Java

import java.nio.LongBuffer;

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

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

        int index = 5;
        System.out.println(lb.get(index));
    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.nio.Buffer.checkIndex(Buffer.java:738) at java.base/java.nio.HeapLongBuffer.get(HeapLongBuffer.java:171)


No comments:

Post a Comment