VOOZH about

URL: https://www.geeksforgeeks.org/java/bytebuffer-array-method-in-java-with-examples/

⇱ ByteBuffer array() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ByteBuffer array() method in Java with Examples

Last Updated : 3 Jun, 2021

The array() method of java.nio.ByteBuffer class is used to return the byte array that backs the taken buffer.
Modifications to this buffer's content will cause the returned array's content to be modified, and vice versa.
Invoke the hasArray() method before invoking this method in order to ensure that this buffer has an accessible backing array.

Syntax : 

public final byte[] array()


Return Value: This method returns the array that backs this buffer.
Exception: This method throws the ReadOnlyBufferException, If this buffer is backed by an array but is read-only.

Below are the examples to illustrate the array() method:

Example 1:  


Output: 
ByteBuffer: [20, 30, 40, 50]

byte array: [20, 30, 40, 50]

 

Example 2:  


Output: 
Original ByteBuffer: [20, 30, 40, 50]

ReadOnlyBuffer ByteBuffer : 20, 30, 40, 50, 

Trying to get the array from bb1 for editing
Exception throws: java.nio.ReadOnlyBufferException

 
Comment