What is the DoubleBuffer rewind() method in Java?

The rewind() method of the class java.nio.DoubleBuffer is used to rewind a buffer. Rewinding a buffer means setting the buffer position to zero.

Note:

  • Limit remains unaffected
  • Any position previously marked is discarded

Declaration

The DoubleBuffer.rewind() method is declared as follows:

buff.rewind()
  • buff: The DoubleBuffer to rewind.

Return value

The DoubleBuffer.rewind() method returns the DoubleBuffer buff after rewinding.

Code

Consider the code snippet below, which demonstrates the use of the DoubleBuffer.rewind() method:

import java.nio.*;
import java.util.*;
public class main {
public static void main(String[] args) {
int n1 = 4;
int n2 = 4;
try {
DoubleBuffer buff1 = DoubleBuffer.allocate(n1);
buff1.put(1.5);
buff1.put(4.6);
System.out.println("buff1: " + Arrays.toString(buff1.array()));
System.out.println("position at(before rewind): " + buff1.position());
System.out.println("rewind()");
buff1.rewind();
System.out.println("position at(after rewind): " + buff1.position());
buff1.put(1.9);
System.out.println("buff1: " + Arrays.toString(buff1.array()));
} catch (IllegalArgumentException e) {
System.out.println("Error!!! IllegalArgumentException");
} catch (ReadOnlyBufferException e) {
System.out.println("Error!!! ReadOnlyBufferException");
}
}
}

Explanation

  • A DoubleBuffer buff1 is declared in line 8.
  • Two elements are added to buff1 using the put() method in lines 9-10. After adding the first element, the position of buff1 is incremented from 0 to 1. After adding the second element, the position of buff1 is incremented from 1 to 2.
  • The position of buff1 before rewind is 2. After calling the rewind() method in line 16, the position of buff1 is set to 0. This is why calling the put() method on buff1 adds the element at the 0th index of buff1.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved