The position(int newPosition) method of java.nio.CharBuffer Class is used to set this buffer’s position. If the mark is defined and larger than the new position then it is discarded.
Syntax:
public CharBuffer position(int newPosition)
Parameters: This method takes the newPosition as parameter which is the new position value. It must be non-negative and no larger than the current limit.
Return Value: This method returns this buffer.
Below are the examples to illustrate the position() method:
Examples 1:
// Java program to demonstrate // position() method import java.nio.*; import java.util.*; public class GFG { public static void main(String[] args) { char [] carr = { 'a' , 'b' , 'c' , 'd' }; // creating object of CharBuffer // and allocating size capacity CharBuffer cb = CharBuffer.wrap(carr); // try to set the position at index 2 // using position() method cb.position( 2 ); // Set this buffer mark position cb.mark(); // try to set the position at index 4 // using position() method cb.position( 4 ); // display position System.out.println( "position before reset: " + cb.position()); // try to call reset() to restore // to the position we marked cb.reset(); // display position System.out.println( "position after reset: " + cb.position()); } } |
position before reset: 4 position after reset: 2
Examples 2:
// Java program to demonstrate // position() method import java.nio.*; import java.util.*; public class GFG { public static void main(String[] args) { // creating object of CharBuffer // and allocating size capacity CharBuffer cb = CharBuffer.allocate( 4 ); // try to set the position at index 1 // using position() method cb.position( 1 ); // putting the value of CharBuffer // using append() method cb.append( 'x' ); // try to set the position at index 3 // using position() method cb.position( 3 ); // putting the value of CharBuffer // using append() method cb.append( "y" ); // display position System.out.println( "CharBuffer: " + Arrays.toString(cb.array())); } } |
CharBuffer: [, x,, y]
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/CharBuffer.html#position-int-