Java Scanner hasNextInt() Method

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

Definition

In Java, sc.hasNextInt() checks whether the next token can be parsed as an int (-2147483648..2147483647) without advancing the scanner. Passing a radix checks whether the token is valid in that base (for example base 2 or 16).

Use hasNextInt() before nextInt() to avoid InputMismatchException whenever input could contain words, decimals, or out-of-range numbers.

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

Syntax

Guard nextInt() with hasNextInt(), and remember to consume rejected tokens if looping past bad input.

Java
Scanner sc = new Scanner("25 abc ff");
if (sc.hasNextInt()) {
    int n = sc.nextInt();    // 25
}
boolean isHex = sc.hasNextInt(16);
CallWhat it does
sc.hasNextInt()Returns true if the next token parses as an int in current radix.
sc.hasNextInt(16)Checks whether the next token is a valid signed hexadecimal int.
while (!sc.hasNextInt()) { sc.next(); }Validation loop discarding bad tokens until an integer arrives.

hasNextInt() does not consume the token—even when it returns false. Calling it inside a while loop without sc.next() on the false branch causes an infinite loop.

Library declarations
Java
// java.util.Scanner
public boolean hasNextInt()
public boolean hasNextInt(int radix)

Parameters

ParameterDescription
radix (optional)Number base (2 to 36) used when checking the token.

Return Value

Return ValueDescription
booleantrue if a token exists and parses as an int within range; false otherwise.
Throws IllegalStateExceptionIf the scanner has been closed.
Throws IllegalArgumentExceptionIf radix is below 2 or above 36.

Compare with Similar Methods

Integer lookahead versus other checks:

MethodHow it differs
nextInt()Consumes the verified integer token.
hasNextLong()Accepts larger 64-bit integers beyond 2.14 billion.
hasNextDouble()Accepts decimal points like 3.5 as well.
useRadix(r)Changes the default radix used by hasNextInt().

Java Examples

Example 1 — Sum Scores Until a Non-Number Appears

Use while (sc.hasNextInt()) to read integers until the word "done" stops the loop without consuming it.

Java
import java.util.Scanner;

public class ScannerHasNextIntStop {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("85 90 78 done 100")) {
            int sum = 0;
            while (sc.hasNextInt()) {
                sum += sc.nextInt();
            }
            System.out.println("Sum before stop: " + sum);
            System.out.println("Stopped at token: " + sc.next());
        }
    }
}

How It Works

  1. Reads only consecutive ints. 85, 90, and 78 satisfy hasNextInt() and sum to 253.
  2. Non-consuming stop. On "done", hasNextInt() returns false and leaves "done" in the input.
  3. Verify remaining token. Calling sc.next() after the loop reads "done", proving 100 after it was never reached.

Example 2 — Check Binary Tokens and Out-of-Range Numbers

Test hasNextInt(2) on binary vs decimal digits and see why 3000000000 returns false.

Java
import java.util.Scanner;

public class ScannerHasNextIntRadix {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("1010 1020 3000000000")) {
            System.out.println("1010 base 2? " + sc.hasNextInt(2));
            sc.next();
            System.out.println("1020 base 2? " + sc.hasNextInt(2) + ", base 10? " + sc.hasNextInt());
            sc.next();
            System.out.println("3000000000 fits int? " + sc.hasNextInt() + ", fits long? " + sc.hasNextLong());
        }
    }
}

How It Works

  1. Radix 2 rejects digit 2. 1010 passes base-2 validation, whereas 1020 fails base 2 and passes base 10.
  2. Overflow returns false cleanly. Because 3000000000 exceeds Integer.MAX_VALUE, hasNextInt() returns false instead of throwing.
  3. Wider check agrees. Without advancing past 3000000000, hasNextLong() immediately returns true.

Example 3 — Prompt Until the User Enters a Valid Integer (System.in)

Loop over System.in with hasNextInt(), discarding invalid words until a whole number is typed.

Java
import java.util.Scanner;

public class ScannerHasNextIntKeyboard {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your age (whole number):");
        while (!sc.hasNextInt()) {
            String bad = sc.next();
            System.out.println("'" + bad + "' is not a whole number. Try again:");
        }
        int age = sc.nextInt();
        System.out.println("Accepted age: " + age);
    }
}

How It Works

  1. Reject without crashing. Typing twenty makes hasNextInt() return false rather than throwing InputMismatchException.
  2. Clear invalid entry. Calling sc.next() inside the while body removes "twenty" so the loop pauses for fresh input.
  3. Read verified age. Once 24 is entered, the loop exits and sc.nextInt() reads 24 safely.

Frequently Asked Questions

No. It only looks ahead; you must call nextInt() to read and move past the token.
When hasNextInt() returns false, the bad token stays in the buffer. Call sc.next() inside the loop to discard it before checking again.
false, because 3.5 has a decimal point and is not a whole integer.
Yes. Pass the radix as an argument: sc.hasNextInt(16) or sc.hasNextInt(2).
false, without throwing NoSuchElementException.

Next: hasNextLine()

Check whether another line exists in the input (even an empty line).

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

9 people found this page helpful