Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
bytebuffer
buffer
communitycreator

What is the ByteBuffer allocateDirect() method in Java?

Sheza Naveed

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.

The allocateDirect() method in Java is used to allocate a new direct ByteBuffer.

  • The position of the new buffer will be zero.
  • The limit of the new buffer will be its capacity.
  • The mark of the new buffer will be undefined.
  • Every element in the new buffer will be initialized to zero.

Syntax

public static ByteBuffer allocateDirect(int capacity)

Parameter

The allocateDirect method takes in one parameter, capacity. capacity tells in bytes about new buffer positions.

Return value

The allocateDirect method returns a new ByteBuffer.

IllegalArgumentException is thrown by the allocateDirect method if the value of capacity is negative.

Code

The code below demonstrates how the allocateDirect method works.

import java.util.*;
import java.nio.*;
public class main {
public static void main(String[] args)
{
int capacity = 4;
try {
ByteBuffer temp = ByteBuffer.allocateDirect(capacity);
byte[] barray = { 20, 30, 40, 50 };
temp = ByteBuffer.wrap(barray);
System.out.println("Direct ByteBuffer: "
+ Arrays.toString(temp.array()));
System.out.print("State of the ByteBuffer : ");
System.out.println(temp.toString());
}
catch (IllegalArgumentException exception) {
System.out.println("Exception thrown !!");
}
}
}

Explanation

  • In line 7, the capacity of ByteBuffer is declared.
  • In line 9, the object of ByteBuffer is created and the size of the ByteBuffer allocated is that of capacity.
  • In line 11, byte array is wrapped into ByteBuffer.

RELATED TAGS

java
bytebuffer
buffer
communitycreator

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