The allocate() method of java.nio.CharBuffer Class is used to allocate a new char 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 CharBuffer allocate(int capacity)
Parameter: This method takes the new buffer’s capacity, in char, as a parameter.
Return Value: This method returns the new char buffer.
Exception: This method throws the IllegalArgumentException if the capacity is a negative integer.
Below program illustrates the allocate() method:
Examples 1:
Java
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
char capacity = 10 ;
CharBuffer fb = CharBuffer.allocate(capacity);
fb.put( 'a' );
fb.put( 3 , 'b' );
System.out.println( "ChartBuffer: "
+ Arrays.toString(fb.array()));
}
}
|
Output:
ChartBuffer: [a, , , b, , , , , , ]
Examples 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 integer" );
CharBuffer fb = CharBuffer.allocate(capacity);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown: " + e);
}
}
}
|
Output:
Trying to allocate a negative integer
Exception thrown: java.lang.IllegalArgumentException
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Jan, 2022
Like Article
Save Article