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 the ByteBuffer.

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.

The ByteBuffer.allocate() method

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 capacity
int capacity = 10;
// Creating new ByteBuffer
ByteBuffer bytebuffer = ByteBuffer.allocate(capacity);
// Putting the values in ByteBuffer
bytebuffer.put((byte)25);
bytebuffer.put(4, (byte)50); // placing on 4th index
// Printing the ByteBuffer
System.out.println(Arrays.toString(bytebuffer.array()));
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved