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

The CharBuffer class in Java is used to create and manipulate character buffers.

The length method of the CharBuffer class is used to obtain the length of the character buffer created using it.

The length of a character buffer is the number of characters between the current position and the buffer’s limit.

A buffer is a temporary storage of data. It is mostly used to read the input data or export data to another process/program.

Each buffer has a position and a limit. Initially, position points to index 0 and limit points to the last index. Each time a character is entered, it is placed at position, and the position is incremented by one.

Parameters and return value

The length function does not accept any parameters and returns an integer value. This integer value is the number of characters between the position and the limit of the buffer, including the character present at the position.

Example

The following snippet creates a new char array of size 9. Then we’ve used the wrap function to create a CharBuffer object using this array. Any changes in this array will also be reflected in the character buffer.

We have used the put function to input the data into the character buffer, and then the flip function is used to bring the position of the buffer to its beginning and the limit to the last value of position.

Then the length function is used to calculate the number of characters between the new position and _limit.

import java.nio.*;
import java.util.*;
public class main {
public static void main(String[] args)
{
// Declare the char array
char[] arr = new char[9];
// creating the CharBuffer object and
// wrapping the char array into it
CharBuffer charBuffer = CharBuffer.wrap(arr);
// 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);
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved