ByteBuffer arrayOffset() in Java

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

Syntax:

int java.nio.ByteBuffer.arrayOffset()

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

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.ByteBuffer;

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

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

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

Output:

0


Approach 2: ReadOnlyBufferException

Java

import java.nio.ByteBuffer;

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

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

        ByteBuffer readOnly = bb.asReadOnlyBuffer();
        System.out.println(readOnly.arrayOffset());
    }
}


Output:

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


No comments:

Post a Comment