ShortBuffer allocate() method in Java With Examples
Last Updated :
27 May, 2021
The allocate() method of java.nio.ShortBuffer Class is used to allocate a new short buffer.
The position of the new Buffer will be zero & it’s limit is its capacity, though the mark is undefined, and each of its elements is initialized to zero. It will be having a backing array, and the array offset as zero.
Syntax:
public static ShortBuffer allocate(int capacity)
Parameters: The method accepts a mandatory parameter capacity which specifies the capacity of the new buffer, in shorts.
Return Value: This method returns the new ShortBuffer.
Exception: This method throws the IllegalArgumentException, if the capacity is a negative integer.
Below programs illustrate the use of allocate() method :
Program 1:
Java
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 5 ;
ShortBuffer sb = ShortBuffer.allocate(capacity);
sb.put(( short ) 10000 );
sb.put(( short ) 10640 );
sb.put(( short ) 10189 );
sb.put(( short )- 2000 );
sb.put(( short )- 16780 );
System.out.println( "ShortBuffer: "
+ Arrays.toString(sb.array()));
}
}
|
Output:
ShortBuffer: [10000, 10640, 10189, -2000, -16780]
Program 2: To show NullPointerException
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 integer" );
FloatBuffer fb = FloatBuffer.allocate(capacity);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown: " + e);
}
}
}
|
Output
Trying to allocate a negative integer
Exception thrown: java.lang.IllegalArgumentException: capacity < 0: (-10 < 0)
Reference: https://docs.oracle.com/javase/7/docs/api/java/nio/ShortBuffer.html#allocate()
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...