ByteBuffer.allocateDirect() in Java

ByteBuffer.allocateDirect(): This method is available in java.nio.ByteBuffer class of Java.

Syntax:

ByteBuffer java.nio.ByteBuffer.allocateDirect(int capacity)

This method takes one argument of type int as its parameter. This method allocates a new direct byte buffer. The new buffer's position will be zero, its limit will be its capacity, its mark will be undefined, each of its elements will be initialized to zero, and its byte order will be BIG_ENDIAN. Whether or not it has a backing array is unspecified.

Parameters: One parameter is required for this method.

capacity : The new buffer's capacity, in bytes.

Returns: The new byte buffer.

Throws:

IllegalArgumentException - If the capacity is a negative integer

Approach 1: When no exceptions.

Java

import java.nio.ByteBuffer;

public class ByteBufferallocateDirect {
    public static void main(String[] args) {

        int capacity = 100;

        System.out.println(ByteBuffer.allocateDirect(capacity));

    }
}

Output:

java.nio.DirectByteBuffer[pos=0 lim=100 cap=100]


Approach 2: IllegalArgumentException 

Java

import java.nio.ByteBuffer;

public class ByteBufferallocateDirect {
    public static void main(String[] args) {

        int capacity = -1;

        System.out.println(ByteBuffer.allocateDirect(capacity));

    }
}


Output:

Exception in thread "main" java.lang.IllegalArgumentException: capacity < 0: (-1 < 0) at java.base/java.nio.Buffer.createCapacityException(Buffer.java:275) at java.base/java.nio.Buffer.<init>(Buffer.java:238) at java.base/java.nio.ByteBuffer.<init>(ByteBuffer.java:286) at java.base/java.nio.ByteBuffer.<init>(ByteBuffer.java:294) at java.base/java.nio.MappedByteBuffer.<init>(MappedByteBuffer.java:107) at java.base/java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:116) at java.base/java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:330)


No comments:

Post a Comment