As the hasNext() returns True when there is a token in buffer otherwise false And hasNextInt() return true if the token in buffer can be interpreted as int otherwise false.
If in case, the buffer is empty then they should return false, but when I do this in my code they hold the screen for taking input from the user. Why so?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println(input.hasNext());
}
}
OUTPUT : console Waits for my input,when i provide input it get closed.
The methods of scanner will block for more input if there is no current token and the source (in this case
System.in) hasn't reached end-of-stream yet. This will then result in it waiting for your input.This is also explicitly mentioned in the documentation of
hasNext()(and the other blocking methods):This can also be seen in the actual implementation of
hasNext():As you can see, it will loop as long as the source isn't closed, and if there is no token in the buffer, it will call
readInput()to find the next token. This read will block if there is currently nothing to read from the source at this time, but it hasn't reached end-of-stream/end-of-file yet.