ByteBuffer.allocate() in Java

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

Syntax:

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

This method takes one argument of type int as its parameter. This method allocates a new 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. It will have a backing array, and its array offset will be zero.

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 ByteBufferallocate {
    public static void main(String[] args) {

        int capacity = 100;
        System.out.println(ByteBuffer.allocate(capacity));

    }
}

Output:

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


Approach 2: IllegalArgumentException 

Java

import java.nio.ByteBuffer;

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

        int capacity = -1;
        System.out.println(ByteBuffer.allocate(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.ByteBuffer.allocate(ByteBuffer.java:360)


No comments:

Post a Comment