java.util.Scanner hasNext()

Description :

This java tutorial shows how to use the hasNext() method of Scanner class of java.util package. This method returns a boolean data type which serves as a flag if there are still tokens to iterate over.

Method Syntax :

public boolean hasNext()

Parameter Input :


DataType Parameter Description


Method Returns :

This method returns true if the Scanner still has tokens to process

Compatibility Version :

Requires Java 1.5 and up

Exception :


The IllegalStateException will be thrown if and only if the scanner is already closed (invoking close() method) and still we invoke the hasNext() method.

Discussion :

The Scanner hasNext() method is usually used as a flag in iterating through the tokens of this scanner object. I could never remember already how many times i have used this handy method especially in dealing with codes that do complex string manipulation.

Java Code Example :

This java example source code demonstrates the use of hasNext() method of Scanner class. Basically this code just prints the tokens generated by the Scanner object.

Sample Output :

Running the hasNext() method example source code of Scanner class will give you the following output

java scanner hasnext() method example

java scanner hasnext() method example

Exception Scenario :

Similar Method :

  • N/A

Suggested Reading List :

References :