Home »
Java programming language
Java Scanner nextBoolean() Method with Example
Scanner Class nextBoolean() method: Here, we are going to learn about the nextBoolean() method of Scanner Class with its syntax and example.
Submitted by Preeti Jain, on February 18, 2020
Scanner Class nextBoolean() method
- nextBoolean() method is available in java.util package.
- nextBoolean() method is used to scans the next token of the input scanned into a boolean value.
- nextBoolean() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
-
nextBoolean() method may throw an exception at the time of returning a Boolean value.
- InputMismatchException: This exception may throw when the next token input mismatch.
- NoSuchElementException: This exception may throw when no such element exists.
- IllegalStateException: This exception may throw when this Scanner is not opened.
Syntax:
public boolean nextBoolean();
Parameter(s):
- It does not accept any parameter.
Return value:
The return type of the method is boolean, it returns true when the valid boolean value scanned from the input otherwise it returns false.
Example:
// Java program to demonstrate the example
// of boolean nextBoolean() method of Scanner
import java.util.*;
public class NextBooleanOfScanner {
public static void main(String[] args) {
String str = "Hi, true IncludeHelp! 8 + 2.0 = 10.0";
// Instantiate Scanner with the
// given str
Scanner sc = new Scanner(str);
// Loop for scanning the boolean
// token input
while (sc.hasNext()) {
// if boolean then display it
if (sc.hasNextBoolean()) {
System.out.println("Boolean Exists: " + sc.nextBoolean());
}
sc.next();
}
// close the scanner
sc.close();
}
}
Output
Boolean Exists: true