Question:
I noticed in many books it is used: System.in.read()
is to get something from the keyboard. Why is the Scanner
class not used there? Because System.in.read()
is faster than creating an instance of the Scanner
class and then creating a construct like this:
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
or
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
I searched on Stackoverflow and did not find the difference between System.in.read and the Scanner class.
Answer:
There is a difference, and a significant one at that. System.in.read()
can only read 1 character as char
.
At the same time, Scanner
is a universal thing that allows you to read in the format you need.
If you need to count character by character, then you should not bother, but use System.in.read()
. In other cases, these are, in particular, files, we use Scanner
.