Topics Index

Demo on PushbackReader - Java Example Program

Demo on PushbackReader
class PushbackReaderDemo
    public static void main(String[] args) throws IOException
        byte[] array = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
        PushbackReader reader = new PushbackReader(new InputStreamReader(new ByteArrayInputStream(array)), array.length); // LINE A
        int j;
        while((j = != -1) // LINE B
        for(int i = 0; i < array.length; i++)
            reader.unread((int)(array[i])); // LINE C
        j = 0;
        while((j = != -1)
        reader.close(); //LINE D


Hello World
dlroW olleH


In the above program at LINE A we created a PushbackReader for the InputStreamReader to read bytes of data. At LINE B we are reading data from reader. At LINE C we are unreading the bytes of data. When we unread characters the last unread character will be read first so we will get the data in the reverse order when we reread from reader.

  • Create a PushbackReader without specifying size and try to unread characters more than one to see an Pushback buffer overflow Exception. When we create a default PushbakReader we can unread only one character.
  • Comment LINE D and see the output. Output will be same since PushbackReader implements AutoCloseable.

© meritcampus 2019

All Rights Reserved.

Open In App