The allocateDirect() method of java.nio.ByteBuffer class is used Allocates 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 allocate() method.
public static ByteBuffer allocateDirect(int capacity)
Parameters: This method takes capacity, in bytes, as parameter.
Return Value: This method returns the new byte buffer.
Exception: This method throws IllegalArgumentException, If the capacity is a negative integer.
Below are the examples to illustrate the allocateDirect() method:
Direct ByteBuffer: [20, 30, 40, 50] State of the ByteBuffer : java.nio.HeapByteBuffer[pos=0 lim=4 cap=4]
Examples 2: To show IllegalArgumentException
Trying to allocate negative value in ByteBuffer Exception thrown : java.lang.IllegalArgumentException: Negative capacity: -4
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.