How to use the IntBuffer mark() method in Java

The IntBuffer mark() method sets the current position of an integer buffer as its mark.

The program needs to import the following module to use the IntBuffer mark() method:

java.nio.IntBuffer

Syntax

Parameter and return value

The IntBuffer mark() method accepts no parameters and returns an integer buffer with a mark at the current position.

Example

The following example shows how to use the IntBuffer mark() method in Java:

  • The program creates an array and uses it to create a buffer using the IntBuffer wrap function.
  • It then sets the buffer’s position to 3 and sets this position as the buffer’s mark.
  • The program again sets the buffer’s position to 4.
  • Upon displaying the position, the program prints 4, but after resetting the buffer, the program displays 3 as the buffer’s position.
// Java program to demonstrate
// mark() method
import java.nio.*;
import java.util.*;
public class main {
public static void main(String[] args)
{
try {
int[] arr = { 11,22,33,44,55,66 };
//create an Int Buffer
IntBuffer buf = IntBuffer.wrap(arr);
//set position to index 3
buf.position(3);
//set the current position as the buffer's mark
buf.mark();
// try to set the position at index 2
buf.position(5);
// display position
System.out.println("position before reset: "+ buf.position());
//reset will set the position to mark
buf.reset();
// display position
System.out.println("position after reset: " + buf.position());
}
catch (InvalidMarkException e) {
System.out.println("New postion is less than the previous position");
System.out.println("Exception throws: "
+ e);
}
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved