What is the CharBuffer position() method in Java?

The java.nio.CharBuffer class is used to store a buffer of characters. We can use this class’s position() method to set the positionPosition of a buffer is its index that will be read or written next of a buffer.

Syntax

The position() method can be declared as shown in the code snippet below:


public CharBuffer position(int position)

  • position: The position to be set of the buffer.

If a mark is defined and it is greater than the position, the mark is discarded.


Return value

The position() method returns the buffer after setting its position to position.

Code

The code snippet below demonstrates the use of the position() method:

import java.nio.*;
import java.util.*;
public class main {
public static void main(String[] args) {
int n1 = 4;
CharBuffer buff1 = CharBuffer.allocate(n1);
buff1.put('a');
buff1.put('c');
System.out.println("buff1: " + Arrays.toString(buff1.array()));
System.out.println("position at(before setting position): " + buff1.position());
System.out.println("position(3)");
buff1.position(3);
System.out.println("position at(after setting position): " + buff1.position());
}
}

Explanation

A CharBuffer buff1 is declared in line 7. The position of buff1 is 2. The position() method is used in line 14 to set the position of buff1 to 3.

Free Resources