ByteBuffer array() in Java

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

Syntax:

byte[] java.nio.ByteBuffer.array()

Returns the byte array that backs this buffer (optional operation).

Parameters: NA

Returns: The array that backs this 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;
import java.util.Arrays;

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

        byte arr[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(arr);

        System.out.println(Arrays.toString(bb.array()));
       

    }
}

Output:

[1, 2, 3, 4]


Approach 2: ReadOnlyBufferException 

Java

import java.nio.ByteBuffer;
import java.util.Arrays;

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

        byte arr[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(arr);

        ByteBuffer readOnly = bb.asReadOnlyBuffer();

        System.out.println(Arrays.toString(readOnly.array()));

    }
}


Output:

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


No comments:

Post a Comment