IntBuffer array() in Java

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

Syntax:

int[] java.nio.IntBuffer.array()

This method returns the int array that backs this buffer.

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.IntBuffer;
import java.util.Arrays;

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

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

        System.out.println(Arrays.toString(ib.array()));
    }
}

Output:

[1, 2, 3, 4]


Approach 2: ReadOnlyBufferException 

Java

import java.nio.IntBuffer;
import java.util.Arrays;

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

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

        IntBuffer readOnly = ib.asReadOnlyBuffer();

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

Output:

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


No comments:

Post a Comment