Pushbackreader - Java Tutorial

Pushbackreader

BLUF: Mastering Pushbackreader is a key requirement for any Java developer. This lesson breaks down the object-oriented principles and syntax required to use this concept in real-world applications.
Write Once, Run Anywhere Tip: Pushbackreader

Java's versatility is unmatched. Learn how Pushbackreader fits into the Java ecosystem and improves your code structure in the tutorial below.

The Java PushbackReader class functions as a reader for character streams with the capability to push a character back into the stream. This class extends the FilterReader class to provide this functionality.

Class declaration

Let's examine the declaration of the Java class called PushbackReader in the java.io package:

Example

public class PushbackReader extends FilterReader

Class Methods

Method Description
int read() It is used to read a single character.
void mark(int readAheadLimit) It is used to mark the present position in a stream.
boolean ready() It is used to tell whether the stream is ready to be read.
boolean markSupported() It is used to tell whether the stream supports mark() operation.
long skip(long n) It is used to skip the character.
void unread (int c) It is used to pushes back the character by copying it to the pushback buffer.
void unread (char[] cbuf) It is used to pushes back an array of character by copying it to the pushback buffer.
void reset() It is used to reset the stream.
void close() It is used to close the stream.

Example of PushbackReader class

Example

import java.io.*;
public class ReaderExample{
	public static void main(String[] args) throws Exception {
        char ary[] = {'1','-','-','2','-','3','4','-','-','-','5','6'};
        CharArrayReader reader = new CharArrayReader(ary); 
        PushbackReader push = new PushbackReader(reader);
        int i;
            while( (i = push.read())!= -1) {
                if(i == '-') {
            	    int j;
                    if( (j = push.read()) == '-'){
                         System.out.print("#*");
                    }else {
                    	push.unread(j); // push back single character
                        System.out.print((char)i);
                    }
	            }else {
	                    System.out.print((char)i);
	            }
           }       
    }
}

Output

Output

1#*2-34#*-56

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience