Use of hasArray() method of ByteBuffer class in java.


 

Use of hasArray() method of ByteBuffer class in java.

In this tutorial you will see the use of hasArray()method of ByteBuffer class in java.

In this tutorial you will see the use of hasArray()method of ByteBuffer class in java.

Use of hasArray() method of byte buffer class in java.

In this tutorial, we will check whether this associated buffer is based on a byte array or not, and provides read/write access.

ByteBuffer API.

The java.nio.ByteBuffer class extends java.nio.Buffer class. It provides the following methods:

Return type Method Description
static ByteBuffer wrap(byte[] b)  The wrap() method create a byte buffer by wrapping  the associated byte array. 
abstract boolean hasArray() The hasArray() method check associated buffer is based on byte array or not.

code

import java.nio.*;
import java.nio.ByteBuffer;

public class BufferHasArray {
  public static final int size = 256;
public static void main(String[]argv)throws Exception {
    byte[] bytes = new byte[size];
    ByteBuffer bytebuf = ByteBuffer.wrap(bytes);
    boolean isArray = bytebuf.hasArray();
    if (isArray ) {
   System.out.println("ByteBuffer is based on array");
    else {
System.out.println("ByteBuffer is not based on array");
    }
  }
}

Output

C:\>java BufferHasArray
ByteBuffer is based on array

Download this code

Ads