Keyboard Input BufferedReader Java

Keyboard Input BufferedReader Java

The previous program (KeyboardReading1.java) of reading keyboard input, using DataInputStream, raises a deprecation warning. To overcome this, in the following program, the readLine() method of BufferedReader is used.

Example on Keyboard Input BufferedReader Java

The following program takes input from keyboard to fill the array elements. The elements and their average are printed.

Importance of InpustStreamReader in Keyboard Input BufferedReader Java

Following statement raises compilation error.

BufferedReader br = new BufferedReader(System.in);

The System.in is a byte stream and cannot be chained to BufferedReader as BufferedReader is a character stream (this problem, we did not face with DataInputStream as DataInputStream and System.in are both byte streams, as in KeyboardReading1.java). The byte stream System.in is to be converted (wrapped) into a character stream and then passed to BufferedReader constructor. This is done by InputStreamReader. InputStreamReader, as the name indicates, is neither an input stream nor a reader. It is not a carrier of data. It is simply a wrapper around input stream to give a reader functionality. The InputStreamReader is used to link an input stream with character stream on reading-side. Similar stream, you get later on writing-side, OutputStreamWriter that links a FileInputStream with BufferedReader.

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

The above statement can be replaced with one statement using anonymous object of InputStreamReader as follows.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Note: This program does not raise deprecation warning while compilation as readLIne() method of BufferedReader is not deprecated.

int x = Integer.parseInt(s1);
marks[i] = x;

The data read with readLine() method is in the form of a string. It must be parsed as per the code requirement. The string s1 is parsed to an int value as the elements of the marks array are integers.

One thought on “Keyboard Input BufferedReader Java

Leave a Reply

Your email address will not be published. Required fields are marked *