I will describe what all of this is about, since you are confused.
Scanner input = new Scanner(System.in)
java.lang.System is a public final class extending java.lang.Object and it has static fields namely err and out being of type PrintStream and in being of type InputStream hence,
System.in
java.util.Scanner extends java.lang.Object and implements the following interfaces:
- Iterator
- Closeable
- AutoCloseable
Now that we understood the hierarchy. What happens during execution?
Execution of > Scanner input = new Scanner(System.in)
Constructs a new Scanner object passing it the source through which it should expect the input.
Execution of > input.next()
does the following steps
- Block execution while waiting for input to scan
As soon as you provide an input (assume below)
"Hello World! This is a test."
and hit Enter the following steps take place
- Scanner read the data from Input Stream
- Tokenizes the input using the delimiter (default whitespace)
- Construct an iterator similiar to
Iterator iterate = tokens.iterator()
for iteration through tokens
- Find the first complete token being "Hello" in the scanner, returns the token and waits before next token.
The reason the first complete token is returned is because that is how next()
method that is inherited from java.util.Iterator
behaves. Basically think of it a pointer pointing to bunch of tokens in scanner arranged in an order. As soon as next()
is invoked, returns first token and moves the pointer ahead.
hasNext()
on the other hand, returns true if this scanner has another token from the location the iterator is pointing to. Unlike next()
it does not advance past the token.
The documentation says the following about next()
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern. This method may block while waiting for input to
scan, even if a previous invocation of hasNext() returned true.