java.util.Scanner nextBoolean()

Description :

This java tutorial shows how to use the nextBoolean method of Scanner class of java.util package. This method returns boolean data type which corresponds to the interpreted boolean value of the scanner input.

Method Syntax :

public boolean nextBoolean()

Parameter Input :


DataType Parameter Description


Method Returns :

This method simply returns the next token of the input boolean value.

Compatibility Version :

Requires Java 1.5 and up

Exception :


– will be thrown by this Scanner class if the token is not a valid boolean. A valid boolean is either “true” or “false” regardless of case.


– The NoSuchElementException will be thrown by the nextBoolea method is invoked after all the scanner tokens are already exhausted.


– will be thrown by the nextBoolean method if the method is invoked after the scanner is already closed.

Discussion :

The Scanner nextBoolean() method is usually used to as a flag in java code logic. Like for instance, we are reading a file and there is a specific token to look at in order for our code to proceed further in reading the file and the scanner object nextboolean method is a very convenient way to handle the boolean token. Well of course there is an old way to handle this kind of scenario like doing the if and else condition, however using this method is much easier for implementation purposes.

Java Code Example :

This java example source code demonstrates the use of nextBoolean method of Scanner class. Basically the example used a boolean token to validate the printing of contents or halt the program.

File Contents:

Sample Output :

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

java scanner nextboolean method example

java scanner nextboolean method example

Exception Scenario :

Similar Method :

  • N/A

Suggested Reading List :

References :