What is the ByteBuffer allocateDirect() method in Java?

What is the ByteBuffer allocateDirect() method in Java? Answer

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, capacitycapacity 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.
What is the ByteBuffer allocateDirect() method in Java? Review:

In our experience, we suggest you solve this What is the ByteBuffer allocateDirect() method in Java? and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the What is the ByteBuffer allocateDirect() method in Java?

Find on Educative

Conclusion:

I hope this What is the ByteBuffer allocateDirect() method in Java? would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.