Java Utility Library

Java Scanner - nextBoolean() Method



The java.util.Scanner.nextBoolean() method is used to scan the next token of the input as a boolean. This method will throw InputMismatchException if the next token cannot be translated into a valid boolean value as described below. If the translation is successful, the scanner advances past the input that matched.

Syntax

public boolean nextBoolean()

Parameters

No parameter is required.

Return Value

Returns the boolean scanned from the input.

Exception

  • Throws InputMismatchException, if the next token does not match the Boolean regular expression, or is out of range.
  • Throws NoSuchElementException, if input is exhausted.
  • Throws IllegalStateException, if this scanner is closed.

Example:

In the example below, the java.util.Scanner.nextBoolean() method is used to scan the next token of the input as a boolean.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {

    //String to scan
    String MyString = "Hello World 10 == 20 returns false";

    //creating a Scanner
    Scanner MyScan = new Scanner(MyString);

    while(MyScan.hasNext()) {
      //if the next is a boolean
      if(MyScan.hasNextBoolean())
        System.out.println("Boolean value is: "+ MyScan.nextBoolean());
      //if the next is not a boolean
      else
        System.out.println("No Boolean Value found: "+ MyScan.next());
    }

    //close the scanner
    MyScan.close();
  }
}

The output of the above code will be:

No Boolean Value found: Hello
No Boolean Value found: World
No Boolean Value found: 10
No Boolean Value found: ==
No Boolean Value found: 20
No Boolean Value found: returns
Boolean value is: false

❮ Java.util - Scanner