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
Call
What 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
Parameter
Description
None
nextBoolean() takes no parameters.
Return Value
Return Value
Description
boolean
true or false.
Throws InputMismatchException
If the next token is anything other than case-insensitive "true" or "false".