Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

What is the ByteBuffer allocate() method in Java?

Khizar Hayat Saani

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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()));
}
}

RELATED TAGS

java

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring