ByteBuffer allocate() method in Java with Examples
The allocate() method of java.nio.ByteBuffer class is used to allocate a new byte 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 ByteBuffer allocate(int capacity)
Parameters: This method takes capacity, in bytes as parameter.
Return Value: This method returns the new byte buffer .
Throws: This method throws IllegalArgumentException, If the capacity is a negative integer
Below are the examples to illustrate the allocate() method:
Examples 1:
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 4 ;
try {
ByteBuffer bb = ByteBuffer.allocate(capacity);
bb.put(( byte ) 20 );
bb.put(( byte ) 30 );
bb.put(( byte ) 40 );
bb.put(( byte ) 50 );
bb.rewind();
System.out.println( "Original ByteBuffer: "
+ Arrays.toString(bb.array()));
}
catch (IllegalArgumentException e) {
System.out.println( "IllegalArgumentException catched" );
}
catch (ReadOnlyBufferException e) {
System.out.println( "ReadOnlyBufferException catched" );
}
}
}
|
Output:
Original ByteBuffer: [20, 30, 40, 50]
Examples 2:
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = - 4 ;
try {
System.out.println( "Trying to allocate negative" +
" value in ByteBuffer" );
ByteBuffer bb = ByteBuffer.allocate(capacity);
bb.put(( byte ) 20 );
bb.put(( byte ) 30 );
bb.put(( byte ) 40 );
bb.put(( byte ) 50 );
bb.rewind();
System.out.println( "Original ByteBuffer: "
+ Arrays.toString(bb.array()));
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
catch (ReadOnlyBufferException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Trying to allocate negative value in ByteBuffer
Exception thrown : java.lang.IllegalArgumentException
Last Updated :
25 Jul, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...