BufferedReader is one of the most efficient way of reading input from user in JAVA. It is part of io package of JAVA. It reads data without parsing it. So all the data is read as String.
BufferedReader exposes only one method i.e. readLine() for the purpose of reading input. This method reads entire line as a String. The programmer will have to explicitly typecast the String data to respective data types.
Please look at the below example:
In the above code snippet , 12 is read using readLine() as a String - “12”.
The code parses String “12” to Integer 12.
BufferedReader can throw IOException if there is some issue in reading input.Thus as per rules of JAVA exception handling, the main method needs to specify - throws or we can handle it using try-catch block.
Reading array elements
Usually the tricky part in BufferedReader is reading array elements. Consider the below :
From the above code, it would be clear that when we have more than one data on a line. We read it as a String and split the different data into Strings using split() method.
Look at one more example. Here user is entering a integer and String value on same line.
When to use BufferedReader?
This is the most common question! Lets understand this. BufferedReader is time and space efficient way of reading input in JAVA. As it does not parse the input. Scanner on the other hand takes more time and space for reading inputs as it provides various methods to read different dataType.
As a rule of thumb, if the input size is large, it makes sense to use BufferedReader to avoid TLE/MLE errors for some test cases. As for large inputs, Scanner will be very inefficient as it will take more time and space to read input. Thus leading your program to take longer time and more space than it is designated to !
The only drawback of BufferedReader is the complex code to read input. But with regular practice this can be easily resolved!
Comments