Scanner and BufferReader both classes are used to read input from external system. Scanner is normally used when we know input is of type string or of primitive types and BufferReader is used to read text from character streams while buffering the characters for efficient reading of characters. Following are the important differences between Scanner class and a BufferReader class.
Sr. No. | Key | Scanner Class | BufferReader Class |
---|---|---|---|
1 | Synchronous | Scanner is not syncronous in nature and should be used only in single threaded case. | BufferReader is syncronous in nature. During multithreading environment, BufferReader should be used. |
2 | Buffer Memory | Scanner has little buffer of 1 KB char buffer. | BufferReader has large buffer of 8KB byte Buffer as compared to Scanner. |
3 | Processing Speed | Scanner is bit slower as it need to parse data as well. | BufferReader is faster than Scanner as it only reads a character stream. |
4 | Methods | Scanner has methods like nextInt(), nextShort() etc. | BufferReader has methods like parseInt(), parseShort() etc. |
5 | Read Line | Scanner has method nextLine() to read a line. | BufferReader has method readLine() to read a line. |
Example of Scanner vs BufferReader
JavaTester.java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class JavaTester { public static void main(String args[]) throws NumberFormatException, IOException { BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter an number:"); int a = Integer.parseInt(bufferReader.readLine()); System.out.printf("You entered: " + a); Scanner scanner = new Scanner(System.in); System.out.println("\nEnter an number:"); a = scanner.nextInt(); System.out.printf("You entered: " + a); } }
Output
Enter an number: 1 You entered: 1 Enter an number: 2 You entered: 2