The allocate() method of java.nio.LongBuffer Class is used to allocate a new Long buffer next to the existing buffer. The new buffer’s position will be zero. Its limit will be its capacity. Its mark will be undefined. And each of its elements will be initialized to zero. It will have a backing array, and its array offset will be zero.
Syntax:
public static LongBuffer allocate(Long capacity)
Parameter: This method takes the new buffer’s capacity, in Long, as a parameter.
Return Value: This method returns the new Long buffer.
Exception: This method throws the IllegalArgumentException if the capacity is a negative Longer.
Below programs illustrate the allocate() method:
Program 1:
Java
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int Capacity = 10 ;
LongBuffer ib = LongBuffer.allocate(Capacity);
ib.put( 11 );
ib.put( 2 , 19 );
System.out.println( "LongBuffer: "
+ Arrays.toString(ib.array()));
}
}
|
Output: LongBuffer: [11, 0, 19, 0, 0, 0, 0, 0, 0, 0]
Program 2: To demonstrate IllegalArgumentException
Java
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int Capacity = - 10 ;
try {
System.out.println( "Trying to allocate a Negative Longer" );
LongBuffer ib = LongBuffer.allocate(Capacity);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown: " + e);
}
}
}
|
OutputTrying to allocate a Negative Longer
Exception thrown: java.lang.IllegalArgumentException: capacity < 0: (-10 < 0)