What is the allocate() method of CharBuffer class in Java?

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:

  • wrapping a character array into a buffer
  • allocating memory to the character buffer
  • duplicating an existing character buffer

The allocate method is used for the second approach. It is used to allocate space in the memory for the character buffer.

Syntax

public static CharBuffer allocate(int capacity)

Parameters and return value

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.

Example

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 buffer
CharBuffer charBuffer = CharBuffer.allocate(10);
// populating data into the CharBuffer object
charBuffer.put("Educative");
// usig the flip function to set
// position to 0th index and
// limit to the last value of position
charBuffer.flip();
// Get the length of the charBuffer
// using length() method
int length = charBuffer.length();
// print the byte buffer
System.out.println("CharBuffer is : "
+ Arrays.toString(
charBuffer.array())
+ "\nLength of CharBuffer: "
+ length);
}
}
Copyright ©2024 Educative, Inc. All rights reserved