What is the CharBuffer rewind() method in Java?
The java.nio.CharBuffer is a class we can use to store a buffer of characters. We can use this class’s rewind() method to rewind a buffer. Rewinding a buffer sets the buffer position to zero.
Note:
- The
of the buffer remains unaffected. limit Limit of a buffer is its first index that should not be read or written. - Any position previously marked is discarded.
Declaration
The CharBuffer.rewind() method is declared as follows:
buff.rewind()
buff: TheCharBufferto rewind.
Return value
The CharBuffer.rewind() method returns the CharBuffer buff after rewinding.
Code
Consider the code snippet below, which demonstrates the use of the CharBuffer.rewind() method.
import java.nio.*;import java.util.*;public class main {public static void main(String[] args) {int n1 = 4;int n2 = 4;try {CharBuffer buff1 = CharBuffer.allocate(n1);buff1.put('a');buff1.put('c');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('d');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
CharBufferbuff1is declared in line 8. - Two elements are added to
buff1using theput()method in line 9-10 . After adding the first element, the position ofbuff1is incremented from 0 to 1. After adding the second element, the position ofbuff1is incremented from 1 to 2. - The position of buff1 before rewind is 2. After calling the
rewind()method in line 16, the position ofbuff1is set to 0. This is why calling theput()method onbuff1adds the element at the 0th index ofbuff1.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved