IntBuffer arrayOffset() in Java

arrayOffset(): This method is available in java.nio.IntBuffer class of Java.

Syntax:

int java.nio.IntBuffer.arrayOffset()

This method returns the offset within this buffer's backing array of the first element of the buffer.

Parameters: NA

Returns: The offset within this buffer's array of the first element of the buffer.

Throws:

1. ReadOnlyBufferException - If this buffer is backed by an array but is read-only.

2. UnsupportedOperationException - If this buffer is not backed by an accessible array

Approach 1: When no exceptions

Java

import java.nio.IntBuffer;

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

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

        System.out.println(lb.arrayOffset());
    }
}

Output:

0


Approach 2: ReadOnlyBufferException 

Java

import java.nio.IntBuffer;

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

        int array[] = { 1, 2, 3, 4 };
        IntBuffer ib = IntBuffer.wrap(array);

        IntBuffer readOnly = ib.asReadOnlyBuffer();
        System.out.println(readOnly.arrayOffset());
    }
}

Output:

Exception in thread "main" java.nio.ReadOnlyBufferException at java.base/java.nio.IntBuffer.arrayOffset(IntBuffer.java:1354)



No comments:

Post a Comment