Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java CharArrayReader reset() Method

In this tutorial, we will learn about the reset() method of the CharArrayReader class in Java. The call of this method, resets the stream either, to the most recently marked position by, or to the beginning of the stream, if the stream is not marked before.

Syntax

Following is the syntax of this method, no parameter is required, and also, no value is returned by it.

public void reset()

Example: Reset Stream in Java

In this example we are going to demonstrate the use of the reset() method, firstly we marked the position while reading then we call the reset() method so it will reset the stream at the most recently marked position by mark() method and from that point, we will start reading again from the stream.

import java.io.CharArrayReader;
class StudyTonight
{
	public static void main(String[] args)  
	{ 
		try 
		{
			char[] arr = {'s', 't', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g', 'h', 't'}; 
			char c;
			CharArrayReader reader = new CharArrayReader(arr); 
			c=(char)reader.read();
			System.out.println(c);  
			reader.mark(1);  
			c=(char)reader.read();
			System.out.println(c);  
			reader.reset();  
			c=(char)reader.read();
			System.out.println(c);  

			reader.close();			
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e.toString());
		}
	} 
}


s
t
t

Example 2: Reset Stream in Java

Here, we are marking the position in the stream by mark() method and we reset it using the reset() method just after this so it will not affect the position of the stream because the current position and last marked position are the same so it will read continuously from the stream.

import java.io.CharArrayReader;
class StudyTonight
{
	public static void main(String[] args)  
	{ 
		try { 
            char[] arr = {'S', 't', 'u', 'd', 'y', 't', 'o', 'n', 'i', 'g', 'h', 't'}; 
  
            CharArrayReader reader = new CharArrayReader(arr);   

            int ch; 
  
            for (int i = 0; i < 5; i++) { 
                ch = reader.read(); 
                System.out.print((char)ch); 
            } 
  
            System.out.println(); 
  
            reader.mark(1); 
  
            reader.reset(); 

            for (int i = 0; i < 7; i++) 
            { 
                ch = reader.read(); 
                System.out.print((char)ch); 
            } 
        } 
        catch (Exception e)
		{ 
            System.out.println("Error: "+e.toString()); 
        } 
	} 
}


Study
tonight

Conclusion

In this tutorial, we learned about the reset() method of the CharArrayReader class in Java, which is used to reposition the stream to the last marked point by mark() method, else, to the starting of the stream, if not marked previously.