Thearray() method ofjava.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 theReadOnlyBufferException, If this buffer is backed by an array but is read-only.
Below are the examples to illustrate the array() method:
Example 1:
Java// Java program to demonstrate// array() methodimportjava.nio.*;importjava.util.*;publicclassGFG{publicstaticvoidmain(String[]args){// Declaring the capacity of the ByteBufferintcapacity=4;// Creating the ByteBuffertry{// creating object of ByteBuffer// and allocating size capacityByteBufferbb=ByteBuffer.allocate(capacity);// putting the int to byte typecast value in ByteBufferbb.put((byte)20);bb.put((byte)30);bb.put((byte)40);bb.put((byte)50);// print the ByteBufferSystem.out.println("ByteBuffer: "+Arrays.toString(bb.array()));// getting byte array from ByteBuffer// using array() methodbyte[]arr=bb.array();// print the byte arraySystem.out.println("\nbyte array: "+Arrays.toString(arr));}catch(IllegalArgumentExceptione){System.out.println("Exception throws: "+e);}}}Output: ByteBuffer: [20, 30, 40, 50]byte array: [20, 30, 40, 50]
Example 2:
Java// Java program to demonstrate// array() methodimportjava.nio.*;importjava.util.*;publicclassGFG{publicstaticvoidmain(String[]args){// Declaring the capacity of the ByteBufferintcapacity=4;// Creating the ByteBuffertry{// creating object of ByteBuffer// and allocating size capacityByteBufferbb=ByteBuffer.allocate(capacity);// putting the int to byte typecast value// in ByteBufferbb.put((byte)20);bb.put((byte)30);bb.put((byte)40);bb.put((byte)50);bb.rewind();// print the ByteBufferSystem.out.println("Original ByteBuffer: "+Arrays.toString(bb.array()));// Creating a read-only copy of ByteBuffer// using asReadOnlyBuffer() methodByteBufferbb1=bb.asReadOnlyBuffer();bb1.rewind();// print the ByteBufferSystem.out.print("\nReadOnlyBuffer ByteBuffer : ");while(bb1.hasRemaining())System.out.print(bb1.get()+", ");// getting byte array from read-only// ByteBuffer using array() methodSystem.out.println("\n\nTrying to get the array"+" from bb1 for editing");byte[]arr=bb1.array();}catch(IllegalArgumentExceptione){System.out.println("Exception throws: "+e);}catch(ReadOnlyBufferExceptione){System.out.println("Exception throws: "+e);}}}Output: Original ByteBuffer: [20, 30, 40, 50]ReadOnlyBuffer ByteBuffer : 20, 30, 40, 50, Trying to get the array from bb1 for editingException throws: java.nio.ReadOnlyBufferException
Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java