Java Scanner hasNextBoolean() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Scanner

Definition

In Java, sc.hasNextBoolean() checks whether the next delimited token matches "true" or "false" (ignoring letter case), without advancing the scanner.

Other common yes/no forms such as "yes", "no", "1", or "0" return false.

An instance method of java.util.Scanner, available since Java 5 (JDK 1.5). A Scanner reads from any source (System.in for keyboard, a String, or a file) with identical parsing logic; pass the source to new Scanner(...) after import java.util.Scanner; and call sc.hasNextBoolean(...).

Syntax

Check strict boolean tokens with hasNextBoolean() before calling nextBoolean().

Java
Scanner sc = new Scanner("TRUE maybe false");
boolean a = sc.hasNextBoolean();  // true
CallWhat it does
sc.hasNextBoolean()Returns true for case-insensitive "true" or "false".
sc.nextBoolean()Consumes the verified boolean token.

hasNextBoolean() is completely independent of locale and radix settings.

Library declarations
Java
// java.util.Scanner
public boolean hasNextBoolean()

Parameters

ParameterDescription
NonehasNextBoolean() takes no parameters.

Return Value

Return ValueDescription
booleantrue if the next token equals "true" or "false" ignoring case.
Throws IllegalStateExceptionIf the scanner has been closed.

Compare with Similar Methods

Boolean checking vs reading:

MethodHow it differs
nextBoolean()Consumes the validated boolean.
hasNext(pattern)Matches custom words like yes or no.
hasNextInt()Checks numeric flags like 0 and 1.

Java Examples

Example 1 — Test hasNextBoolean() on Mixed Case, "yes", and "1"

Check five tokens to see precisely which strings qualify as booleans.

Java
import java.util.Scanner;

public class ScannerHasNextBoolCheck {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("true FALSE True yes 1")) {
            while (sc.hasNext()) {
                boolean ok = sc.hasNextBoolean();
                System.out.println(sc.next() + " -> " + ok);
            }
        }
    }
}

How It Works

  1. Any case of true/false passes. Lowercase, uppercase, and title case all evaluate to true.
  2. Synonyms return false. Neither "yes" nor numeric "1" matches the strict boolean pattern.
  3. Advance with next(). Consuming each tested token prints the result across the whole line.

Example 2 — Separate Boolean Flags from Action Commands

Read a stream mixing boolean flags and command names without triggering exceptions.

Java
import java.util.Scanner;

public class ScannerHasNextBoolToggles {
    public static void main(String[] args) {
        String script = "true pause false reset true";
        try (Scanner sc = new Scanner(script)) {
            while (sc.hasNext()) {
                if (sc.hasNextBoolean()) {
                    System.out.println("Flag:    " + sc.nextBoolean());
                } else {
                    System.out.println("Command: " + sc.next());
                }
            }
        }
    }
}

How It Works

  1. Peek decides branch. hasNextBoolean() routes true/false tokens to nextBoolean().
  2. Words fall through cleanly. "pause" and "reset" hit the else block and are read as commands.
  3. Zero crashes. Guarding every boolean read keeps mixed command scripts safe.

Example 3 — Accept Either true/false or yes/no Safely

Use hasNextBoolean() first, then fall back to checking "yes"/"no" via next().

Java
import java.util.Scanner;

public class ScannerHasNextBoolFallback {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("false yes maybe")) {
            while (sc.hasNext()) {
                if (sc.hasNextBoolean()) {
                    System.out.println("Boolean: " + sc.nextBoolean());
                } else {
                    String s = sc.next();
                    System.out.println("Text \"" + s + "\" -> yes? " + s.equalsIgnoreCase("yes"));
                }
            }
        }
    }
}

How It Works

  1. Strict boolean handled first. "false" enters the if branch directly.
  2. Custom mapping for yes. "yes" fails hasNextBoolean(), so the fallback reads it and evaluates equalsIgnoreCase("yes").
  3. Unrecognized words handled. "maybe" evaluates to false without any exception.

Frequently Asked Questions

Only "true" and "false" in any letter case (like "TRUE" or "False").
No. Both return false because Scanner requires the words true or false.
No. Call nextBoolean() afterwards to read it.
It returns false cleanly.
No. It works identically in every locale.

Next: hasNextByte()

Check whether the next token fits in a signed byte (-128 to 127).

hasNextByte() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P πŸ”—

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful