Java - Buffer Position, Limit and Mark


Position and limit are two properties of a buffer.

When a buffer is created, its position is set to 0 and its limit is equal to its capacity.

You can get/set the position of a buffer using its position() method.

Method Meaning
position() returns the current value of the position of a buffer.
position(int newPosition) sets the position of the buffer to the specified newPosition value and returns the reference of the buffer.

You can get/set the limit of a buffer using its overloaded limit() method.

Method Meaning
limit()returns the current value of the limit of a buffer.
limit(int newLimit) sets the limit of a buffer to the specified newLimit value and returns the reference of the buffer.

You can bookmark a position of a buffer by using the mark() method.

When you call the mark() method, the buffer stores the current value of its position as its mark value.

Then set the position of a buffer to its previously bookmarked value by reset() method.

The buffer's mark is not defined when it is created.

You must call the reset() method on a buffer only when its mark is defined. Otherwise, the reset() method throws an InvalidMarkException.

The following formula must hold during the lifetime of a buffer:

0 <= mark <= position <= limit <= capacity

The following code shows Mark, Position, Limit, and Capacity of a New Buffer


import java.nio.ByteBuffer;
import java.nio.InvalidMarkException;

public class Main {
  public static void main(String[] args) {
    // Create a byte buffer of capacity 8
    ByteBuffer bb = ByteBuffer.allocate(8);

    System.out.println("Capacity: " + bb.capacity());
    System.out.println("Limit: " + bb.limit());
    System.out.println("Position: " + bb.position());

    // The mark is not set for a new buffer. Calling the
    // reset() method throws a runtime exception if the mark is not set.
    // If the mark is set, the position is set to the mark value.
    try {//from  w w w . j  a  va 2s .c  om
      System.out.println("Mark: " + bb.position());
    } catch (InvalidMarkException e) {
      System.out.println("Mark is not set");