FloatBuffer reset() methods in Java with Examples

The reset() method of java.nio.FloatBuffer Class is used to reset the position of this buffer to a position which was previously-marked. In this, the marked value is neither changed nor discarded. It helps to recover the previously marked value in the buffer.
Syntax:
public final FloatBuffer reset()
Parameters: The method does not take any parameters.
Return Value: This method returns this buffer.
Below are the examples to illustrate the reset() method:
Examples 1:
// Java program to demonstrate// reset() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { try { float[] farr = { 10.5f, 20.5f, 30.5f, 40.5f }; // creating object of FloatBuffer // and allocating size capacity FloatBuffer fb = FloatBuffer.wrap(farr); // try to set the position at index 2 fb.position(2); // Set this buffer mark position // using mark() method fb.mark(); // try to set the position at index 4 fb.position(4); // display position System.out.println("position before reset: " + fb.position()); // try to call reset() to restore // to the position we marked fb.reset(); // display position System.out.println("position after reset: " + fb.position()); } catch (InvalidMarkException e) { System.out.println("new position is less than " + "the position we" + " marked before "); System.out.println("Exception throws: " + e); } }} |
Output:
position before reset: 4 position after reset: 2
Examples 2:
// Java program to demonstrate// reset() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { try { float[] farr = { 10.5f, 20.5f, 30.5f, 40.5f }; // creating object of FloatBuffer // and allocating size capacity FloatBuffer fb = FloatBuffer.wrap(farr); // try to set the position at index 2 fb.position(2); // Set this buffer mark position // using mark() method fb.mark(); // try to set the position at index 4 fb.position(1); // display position System.out.println("position before reset: " + fb.position()); // try to call reset() to restore // to the position we marked fb.reset(); // display position System.out.println("position after reset: " + fb.position()); } catch (InvalidMarkException e) { System.out.println("\nnew position is less than " + "the position we" + " marked before "); System.out.println("Exception throws: " + e); } }} |
Output:
position before reset: 1 new position is less than the position we marked before Exception throws: java.nio.InvalidMarkException
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/FloatBuffer.html#reset–



