Java Scanner nextBoolean() Method

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

Definition

In Java, sc.nextBoolean() parses the next token into a boolean. It matches only the words "true" and "false", ignoring letter case (so "TRUE", "True", and "false" all work).

Any other text—including "1", "0", "yes", or "no"—throws InputMismatchException.

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.nextBoolean(...).

Syntax

Read strict true/false flags with nextBoolean().

Java
Scanner sc = new Scanner("true FALSE True");
boolean a = sc.nextBoolean();   // true
boolean b = sc.nextBoolean();   // false
boolean c = sc.nextBoolean();   // true
CallWhat it does
sc.nextBoolean()Parses case-insensitive "true" or "false".
sc.hasNextBoolean()Checks whether the next token is "true" or "false" first.

nextBoolean() does not depend on locale() or radix(). Unlike Boolean.parseBoolean("yes") (which quietly returns false), Scanner.nextBoolean() rejects anything other than true/false with an exception.

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

Parameters

ParameterDescription
NonenextBoolean() takes no parameters.

Return Value

Return ValueDescription
booleantrue or false.
Throws InputMismatchExceptionIf the next token is anything other than case-insensitive "true" or "false".
Throws NoSuchElementExceptionIf no more tokens exist.
Throws IllegalStateExceptionIf the scanner has been closed.

Compare with Similar Methods

Boolean parsing choices:

MethodHow it differs
hasNextBoolean()Checks for true/false before consuming.
next()Best for yes/no or Y/N prompts.
Boolean.parseBoolean(s)Never throws; returns false for everything except "true".

Java Examples

Example 1 — Parse Feature Flags in Any Letter Case

Read configuration booleans written in lowercase, uppercase, and mixed case.

Java
import java.util.Scanner;

public class ScannerNextBooleanFlags {
    public static void main(String[] args) {
        String config = "true FALSE True";
        try (Scanner sc = new Scanner(config)) {
            boolean darkMode = sc.nextBoolean();
            boolean beta = sc.nextBoolean();
            boolean alerts = sc.nextBoolean();
            System.out.println("darkMode=" + darkMode + ", beta=" + beta + ", alerts=" + alerts);
        }
    }
}

How It Works

  1. Case-insensitive matching. "true", "FALSE", and "True" all match the boolean token pattern.
  2. No locale dependency. English true and false work identically regardless of region settings.
  3. Three booleans stored. Each nextBoolean() returns a primitive boolean ready for if conditions.

Example 2 — Why "yes" and "1" Fail nextBoolean() (and How to Handle Them)

Catch InputMismatchException on "yes" and "1", then map text manually with next().

Java
import java.util.InputMismatchException;
import java.util.Scanner;

public class ScannerNextBooleanYesNo {
    public static void main(String[] args) {
        String answers = "yes 1 false";
        try (Scanner sc = new Scanner(answers)) {
            while (sc.hasNext()) {
                try {
                    System.out.println("Strict boolean: " + sc.nextBoolean());
                } catch (InputMismatchException e) {
                    String word = sc.next();
                    boolean ok = word.equalsIgnoreCase("yes") || word.equals("1");
                    System.out.println("Fallback for \"" + word + "\": " + ok);
                }
            }
        }
    }
}

How It Works

  1. Strict token check. Neither "yes" nor "1" counts as a boolean for nextBoolean(), so both raise InputMismatchException.
  2. Read and interpret in catch. Calling sc.next() retrieves the unconsumed token so your code can treat "yes" and "1" as true.
  3. Standard false passes. On the third token, nextBoolean() succeeds directly and prints false.

Example 3 — Count Correct True/False Quiz Answers

Use a hasNextBoolean() loop to tally how many answers are true.

Java
import java.util.Scanner;

public class ScannerNextBooleanQuiz {
    public static void main(String[] args) {
        String quiz = "true false true true false";
        int yesCount = 0;
        int total = 0;
        try (Scanner sc = new Scanner(quiz)) {
            while (sc.hasNextBoolean()) {
                if (sc.nextBoolean()) {
                    yesCount++;
                }
                total++;
            }
        }
        System.out.println("True answers: " + yesCount + " of " + total);
    }
}

How It Works

  1. Loop until non-boolean or EOF. hasNextBoolean() keeps the loop running across all five valid tokens.
  2. Direct boolean condition. Because nextBoolean() returns a boolean, you can place it straight inside if (...).
  3. Final tally. Three true values out of five tokens print 3 of 5.

Frequently Asked Questions

Only "true" and "false", ignoring case (such as "TRUE" or "False").
Scanner only recognizes "true" and "false". For yes/no prompts, read a String with next() and compare with equalsIgnoreCase("yes").
Yes, it throws NoSuchElementException when no token remains. Check hasNextBoolean() first.
No. It always checks for English "true" and "false" regardless of the scanner locale.
Boolean.parseBoolean("maybe") silently returns false, while Scanner.nextBoolean() throws InputMismatchException so typos are not mistaken for false.

Next: nextByte()

Read the next token as a byte (-128 to 127).

nextByte() 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.

10 people found this page helpful