Scanner scanner = new Scanner(System.in);
System.out.println("enter number :");
int number = scanner.nextInt();
System.out.println("Number is " + number);
let me go through step by step to explain my understanding,
Scanner scanner = new Scanner(System.in);
The Scanner is one of the java In-built classes and it is one of the ways we can use it to read user input.
scanner is the identifier of the object we created.
Using
new, we create an instance of the object.System.inhelps us to take the inputs from the console(keyboard)System.out.println("enter number :");
prints the " enter number : ".
int number = scanner.nextInt();
Reads the input given to the system.in from console(keyboard) and parse(convert) the input to an int and stores it in the variable number.
System.out.println("Number is " + number);
prints the statement "Number is " + number(input stored in the variable number));
this is my vague understanding I think and I am not certain of my knowledge.
my questions are;
Scanner class is used to read user input, then System.in also is used to read input? isn't it? it will be a help to explain the clear distinction between these two terms?
when we type(enter) input from the console, where is it going? to the System.in?
does System.in storing the values?
- nextInt() method is also used to read inputs? how it works? is it read input that is already been read by the System.in and then parses to an int?
The scanner reads, System.in reads, nextInt() reads, everything reads? I can't able to distinguish the workings of these?
System.inis anInputStreamthat (by default) provides user input from the console. You can read from it directly by usingread:Note that this reads an unsigned byte (Java doesn't have a type for unsigned bytes, so the type is
int). For example, if I entered1in my console, the above will store 49 intosomeByte, because 49 is the first byte that the character1is encoded as.If you want to
someByteto be 1 instead, usingSystem.in.readis clearly not very helpful, is it? We don't want to just read the bytes. We want to read the bytes, and use a particular encoding to convert those bytes to characters and then parse the string of characters to a number. This is whatScannerdoes.A
Scannercan take an input stream, and read bytes from it on demand, understands them as characters using a default encoding, then it groups chunks of characters together into tokens. One way for aScannerto read stuff is by callingnextInt. WhatnextIntdoes is: read bytes until it finds a complete token, and parses it to an integer.In short,
System.ingives you the raw bytes,Scannergives you tokens, parsed or otherwise. Hopefully that answers your first and third question.Yes, at this level of abstraction, you can say that's the first place it will go. Then the bytes you inputted then get passed to
Scanner, which then transforms them into tokens, and then parsed.