java – System.in.read () or Scanner?

Question:

I noticed in many books it is used: System.in.read() is to get something from the keyboard. Why isn't the Scanner class used there? Because System.in.read() is faster than creating an instance of the Scanner class and then creating such a construction:

Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();

or

Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();

Searched Stackoverflow and found no difference between System.in.read and Scanner class.

Answer:

There is a difference, and, moreover, a significant one. System.in.read() can only read 1 character as char .
At the same time, Scanner is a versatile piece that allows you to read in the format you need.
If you need to count by characters, then you should not bother, but use System.in.read() . In other cases, these are, in particular, files, we use Scanner .

Scroll to Top