What is the ByteBuffer allocate() method in Java?
ByteBuffer is a built-in class available in the java.nio.ByteBuffer package.
ByteBuffer implements a byte buffer and allows the user to perform various categories of operations upon buffers of datatype byte.
allocate() is a method defined in the ByteBuffer class. The following is the function prototype:
public static ByteBuffer allocate(int capacity)
Parameters and return value
The allocate() method takes the following input parameter:
capacity: An integer value that represents the size, in byes, of theByteBuffer.
The method returns the new ByteBuffer. If the capacity provided is a negative integer, then an IllegalArgumentException is thrown.
Functionality
The allocate() method allocates a new ByteBuffer. The size of the buffer is set to the capacity passed as the input argument.
Once the method is invoked, each element of the buffer is initialized to zero. The offset (or position) is also set to zero by default.
Code
The following code demonstrates how to use the allocate method.
import java.nio.*;import java.util.*;public class Edpresso {public static void main(String[] args){// Declaring capacityint capacity = 10;// Creating new ByteBufferByteBuffer bytebuffer = ByteBuffer.allocate(capacity);// Putting the values in ByteBufferbytebuffer.put((byte)25);bytebuffer.put(4, (byte)50); // placing on 4th index// Printing the ByteBufferSystem.out.println(Arrays.toString(bytebuffer.array()));}}
Free Resources