The CharBuffer class in Java is used to create and manipulate character buffers.
A buffer is a temporary storage of data. It is mostly used to read the input data or export data to another process/program.
There are three methods of creating a character buffer:
The allocate
method is used for the second approach. It is used to allocate space in the memory for the character buffer.
public static CharBuffer allocate(int capacity)
The allocate
method accepts a single integer parameter.
capacity
is the number of characters that can be accommodated in the character buffer, i.e., the buffer’s capacity.
If
n
is a negative number, this method throws the illegal argument exception.
This method returns the new character buffer as the object of the CharBuffer
class.
The following snippet of code uses the allocate
method to allocate memory for the character buffer. In this case, we have passed 10 as an argument to the allocate
, which sets the maximum capacity of the character buffer to 10.
Then the put
method is used to populate data into the character buffer, and the flip
method is used to set the position and limit of the buffer.
If we try to enter more characters than the maximum capacity of the buffer, it will throw an exception.
The length
function is used to calculate the number of characters between the position and the limit of the buffer.
import java.nio.*;import java.util.*;public class main {public static void main(String[] args){// using the allocate method to create space// in the memory for the character bufferCharBuffer charBuffer = CharBuffer.allocate(10);// populating data into the CharBuffer objectcharBuffer.put("Educative");// usig the flip function to set// position to 0th index and// limit to the last value of positioncharBuffer.flip();// Get the length of the charBuffer// using length() methodint length = charBuffer.length();// print the byte bufferSystem.out.println("CharBuffer is : "+ Arrays.toString(charBuffer.array())+ "\nLength of CharBuffer: "+ length);}}
Free Resources