What is the ByteBuffer allocateDirect() method in Java?

The allocateDirect() method in Java is used to allocate a new direct ByteBuffer.

  • The position of the new buffer will be zero.
  • The limit of the new buffer will be its capacity.
  • The mark of the new buffer will be undefined.
  • Every element in the new buffer will be initialized to zero.

Syntax

public static ByteBuffer allocateDirect(int capacity)

Parameter

The allocateDirect method takes in one parameter, capacity. capacity tells in bytes about new buffer positions.

Return value

The allocateDirect method returns a new ByteBuffer.

IllegalArgumentException is thrown by the allocateDirect method if the value of capacity is negative.

Code

The code below demonstrates how the allocateDirect method works.

import java.util.*;
import java.nio.*;
public class main {
public static void main(String[] args)
{
int capacity = 4;
try {
ByteBuffer temp = ByteBuffer.allocateDirect(capacity);
byte[] barray = { 20, 30, 40, 50 };
temp = ByteBuffer.wrap(barray);
System.out.println("Direct ByteBuffer: "
+ Arrays.toString(temp.array()));
System.out.print("State of the ByteBuffer : ");
System.out.println(temp.toString());
}
catch (IllegalArgumentException exception) {
System.out.println("Exception thrown !!");
}
}
}

Explanation

  • In line 7, the capacity of ByteBuffer is declared.
  • In line 9, the object of ByteBuffer is created and the size of the ByteBuffer allocated is that of capacity.
  • In line 11, byte array is wrapped into ByteBuffer.

Free Resources