VOOZH about

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

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


  • Courses
  • Tutorials
  • Interview Prep

ByteBuffer allocateDirect() method in Java with Examples

Last Updated : 20 Mar, 2024

The allocateDirect() method of java.nio.ByteBuffer class is used to Allocate a new direct byte buffer. The new buffer's position will be zero, its limit will be its capacity, its mark will be undefined, and each of its elements will be initialized to zero. Whether or not it has a backing array is unspecified. This method is 25%-75% faster than the allocate() method.

Syntax:

public static ByteBuffer allocateDirect(int capacity)

Parameters: This method takes capacity, in bytes, as a parameter.
Return Value: This method returns the new byte buffer.
Exception: This method throws IllegalArgumentException If the capacity is a negative integer.

Program for ByteBuffer allocateDirect() method in Java

Example 1:

Below is the implemented ByteBuffer allocateDirect() method :


Output
State of the ByteBuffer : java.nio.DirectByteBuffer[pos=4 lim=4 cap=4]

Examples 2:

Below is the implementation of ByteBuffer allocateDirect() method in Java to show IllegalArgumentException


Output
Trying to allocate negative value in ByteBuffer
Exception thrown : java.lang.IllegalArgumentException: capacity < 0: (-4 < 0)
Comment