First, you should note that hasNextInt()
actually does two tasks.
- Checks whether there is another token in the underlying stream.
- When there is one, it checks whether that token is in fact a valid
int
.
So the first thing it tries to do is get a complete token, based on the Scanner's delimiter. It checks if the data collected so far in memory is a complete token - that is, we have hit a delimiter or the end of the stream - and if so, it can move on to matching and deciding whether it is an int.
Suppose so far it had "12" in the input. You don't know if it's going to be 12, 123, 12.5, 12A etc. until you hit the delimiter or the end of the stream.
Now, if it can't find the delimiter, it tries to read more data from the underlying stream. When it does so, it can block. The block can be for a short time (when the underlying stream is a file, it may block momentarily until a block is fetched from disk), slightly longer (waiting for a packet to arrive from a network connection), or very long - in case the underlying stream is a console.
Input streams that come from console do not retrieve data until the user presses Return. So if the user typed something like 123 dog cat
- but did not press Return, the underlying stream won't return from read()
, and hasNextInt()
will block until the user presses Return.
Once the user presses return, you actually have three tokens available, so the current hasNextInt()
will return true
, and then you'll be able to read that token and call hasNextInt()
again, and it will not block, but rather return false
immediately (there is a token, but it is not an integer). The same will be true for the next one, and then it will block again, as the user needs to input another line and press Return again.
So to sum up:
hasNextInt()
will block whenever the underlying stream blocks.
- When the underlying stream is a file or network, blocks are usually very short.
- When the underlying stream is from a console, it will block for long periods when the previous line has already been scanned, but the user has not pressed Return to send the next line.
- If there is more than one token on a single line when scanning from console, then it will block once for the first token on that line, and not block for the others.