What is the FloatBuffer mark() method in Java?

FloatBuffer is a built-in class available in the java.nio.FloatBuffer package.

FloatBuffer implements a float-point buffer and allows the user to perform various categories of operations upon buffers of datatype float.

mark() is a method defined in the FloatBuffer class. The following is the function prototype:

public final FloatBuffer mark()

Functionality

The mark() method sets the current position of the FloatBuffer as its mark.

Once the mark is set, the position returns to the mark after calling the reset() method.

However, we cannot invoke the reset() method after setting a mark and moving to a position behind the mark. Doing so throws an InvalidMarkException.

The mark() and reset() methods

Parameters and return value

The mark() method takes no input parameters. The current position is marked by default.

The method returns the FloatBuffer after setting the buffer’s mark at the current position.

Code

The code below shows an example of the mark() method.

import java.nio.*;
import java.util.*;
class Edpresso {
public static void main( String args[] ) {
// Creating a Floatbuffer
FloatBuffer buff = FloatBuffer.allocate(5);
// Populating FloatBuffer
buff.put(3.14F);
buff.put(7.86F);
buff.put(4.67F);
buff.put(11.33F);
buff.put(63.03F);
// Print buffer
System.out.println(Arrays.toString(buff.array()));
// Jump to 3rd index of buffer
buff.position(3);
System.out.println("Current position is: " + buff.position());
// Mark current position
buff.mark();
System.out.println("Marked position: " + buff.position());
// Jump to 5th index of buffer
buff.position(5);
System.out.println("Current position is: " + buff.position());
// Invoking reset()
buff.reset();
// Print position after reset
System.out.println("Position after reset is: " + buff.position());
// Jumping to a position behind the mark
buff.position(1);
System.out.println("Current position is: " + buff.position());
// Invoke reset()
buff.reset();
}
}

In the above example, we create a FloatBuffer and populate it with random float values.

We jump to the 3rd index of the buffer and invoke the mark() method. As shown in the output, the position is successfully marked.

Next, we jump to the 5th index of the buffer and call reset(). As the 3rd index was already marked, calling reset() brings the current position back to the mark.

Then, we jump to the 1st index. This position is behind the mark which is set at the 3rd index.

Invoking reset() now throws an InvalidMarkException as our current position (1) is less than the mark (3).

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved