What is the ByteBuffer array() method in Java?

In Java, the array() method of the ByteBuffer class returns the array that backs a provided ByteBuffer object.

The process is illustrated below.

Any changes to the ByteBuffer object’s content are reflected in the array returned by the array() method.

To use the array() method, you will need to import the ByteBuffer class into your program, as shown below.

import java.nio.ByteBuffer

The prototype of the array() method is shown below.

public final byte[] array()

Parameters

The array() method does not accept any parameters.

Return value

The array() method returns a byte array that backs the given ByteBuffer object.

If the buffer is backed by an array but is set to read-only, then the array() method throws the ReadOnlyBufferException.

Similarly, if the buffer is not backed by an array, the array() method throws the UnsupportedOperationException.

Example

The code below shows how the array() method can be used in Java.

import java.nio.*;
import java.util.*;
class arrayMethod {
public static void main(String[] args) {
// initialize ByteBuffer instance
ByteBuffer buffer = ByteBuffer.allocate(6);
byte values[] = {2, 1, 6, 7, 10};
// add values to buffer
for(int i = 0; i < 5; i++)
{
buffer.put(values[i]);
}
// get array that backs buffer
byte [] bufferArray = buffer.array();
// Print buffer array
System.out.println("The buffer array is: " + Arrays.toString(bufferArray));
// update buffer
buffer.put((byte)20);
bufferArray = buffer.array();
System.out.println("The new buffer array is: " + Arrays.toString(bufferArray));
// create a read-only copy
ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
// get backing array
try
{
byte [] readOnlyArray = readOnlyBuffer.array();
}
catch (ReadOnlyBufferException error)
{
System.out.println("An exception was thrown: " + error);
}
}
}

Explanation

First, a ByteBuffer object called buffer is initialized through the allocate() method. buffer has the capacity to store 66 elements.

Next, a for-loop adds values to buffer through the put() method.

The array() method in line 1919 proceeds to return the backing array for the buffer object. The contents of the array reflect the contents of buffer. Therefore, the addition of new values to buffer changes the backing array. As a result, the array() method in line 2626 returns a different array than the one before.

Finally, a read-only copy of buffer is created through the asReadOnlyBuffer() method. The array() method in line 3535 throws the ReadOnlyBufferException when it tries to return the backing array.

Free Resources