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.
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.
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 arraychar[] arr = new char[9];// creating the CharBuffer object and// wrapping the char array into itCharBuffer charBuffer = CharBuffer.wrap(arr);// 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