LongBuffer.allocate(int) in Java

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

Syntax:

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

This method takes one argument of type int as its parameter. This method allocates a new long 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 the native order of the underlying hardware.

Parameters: One parameter is required for this method.

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

Returns: The new long buffer.

Throws:

IllegalArgumentException - If the capacity is a negative integer

Approach 1: When no exceptions.

Java

import java.nio.LongBuffer;

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

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

Output:

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


Approach 2: IllegalArgumentException 

Java

import java.nio.LongBuffer;

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

        int capacity = -100;
        System.out.println(LongBuffer.allocate(capacity));
    }
}


Output:

Exception in thread "main" java.lang.IllegalArgumentException: capacity < 0: (-100 < 0) at java.base/java.nio.Buffer.createCapacityException(Buffer.java:275) at java.base/java.nio.LongBuffer.allocate(LongBuffer.java:360)


No comments:

Post a Comment