Java Scanner nextBoolean() Method

The nextBoolean() is a method of Java Scanner class which is used to scan the next token of the input into a boolean value and returns that value. If the translation is successful, the scanner past the input that matched.

Syntax

Following is the declaration of nextBoolean() method:

Parameter

This method does not accept any parameter.

Returns

The nextBoolean() method returns the boolean scanned from the input.

Exceptions

InputMismatchException- It will thrown this Exception if the next token is not a valid boolean.

NoSuchElementException- It will thrown this Exception if the input is exhausted.

IllegalStateException- It will thrown this Exception if the innvocation is done after Scanner is closed.

Compatibility Version

Java 1.5 and above

Example 1

Output:

Are you above 18?- True
You are over 18
Are you above 18?- False
You are under 18

Example 2

Output:

Not Found Boolean:Hello
Found Boolean:true
Not Found Boolean:World!
Not Found Boolean:12
Found Boolean:false
Not Found Boolean:15
Not Found Boolean:2.123

Example 3

Output:

Would you like to play? : True
Great! This will be fun.

Would you like to play? : False
Maybe next time