Java Scanner nextInt() Method

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

Definition

In Java, sc.nextInt() scans the next token and converts it into a 32-bit signed int (from -2147483648 to 2147483647). The second form, nextInt(int radix), parses digits in a chosen number base such as 2 (binary) or 16 (hexadecimal).

When the next token is not a valid integer in range, nextInt() throws InputMismatchException without consuming the bad token, so validation loops must discard it with sc.next().

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

Syntax

Call nextInt() for base 10 (or the scanner's configured radix), or pass a specific radix between 2 and 36.

Java
Scanner sc = new Scanner("42 1010 ff");
int decimal = sc.nextInt();     // 42
int binary = sc.nextInt(2);     // 10
int hex = sc.nextInt(16);       // 255
CallWhat it does
sc.nextInt()Parses the next token as an int using the current radix (default 10).
sc.nextInt(2)Parses a binary integer token like "1010" into 10.
sc.nextInt(16)Parses a hexadecimal token like "ff" or "FF" into 255.
sc.hasNextInt()Checks safely before calling nextInt().

In base 10, nextInt() is locale-aware for thousands separators: with Locale.US, "1,234" parses as 1234. Passing a radix below Character.MIN_RADIX (2) or above Character.MAX_RADIX (36) throws IllegalArgumentException.

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

Parameters

ParameterDescription
radix (optional)The number base (2 to 36) used to interpret the token digits.

Return Value

Return ValueDescription
intThe parsed 32-bit integer value.
Throws InputMismatchExceptionIf the next token is not a valid integer or overflows int range.
Throws NoSuchElementExceptionIf the input has no more tokens.
Throws IllegalStateExceptionIf the scanner is closed.

Compare with Similar Methods

Integer scanning overloads and lookahead:

MethodHow it differs
hasNextInt()Tests whether the next token is a valid int first.
nextLong()Reads larger 64-bit whole numbers.
useRadix(r)Sets a default base for future nextInt() calls.
Integer.parseInt(s)Parses an existing String; throws NumberFormatException.

Java Examples

Example 1 — Read Decimal, Binary, and Hex Numbers

Combine default base-10 reading (including a Locale.US grouped number) with binary and hexadecimal calls.

Java
import java.util.Locale;
import java.util.Scanner;

public class ScannerNextIntRadix {
    public static void main(String[] args) {
        try (Scanner sc = new Scanner("1,234 1010 ff").useLocale(Locale.US)) {
            int grouped = sc.nextInt();
            int fromBinary = sc.nextInt(2);
            int fromHex = sc.nextInt(16);
            System.out.println("US grouped: " + grouped);
            System.out.println("Binary 1010: " + fromBinary);
            System.out.println("Hex ff: " + fromHex);
        }
    }
}

How It Works

  1. Locale grouping in base 10. Under Locale.US, the comma inside "1,234" acts as a thousands separator, yielding 1234.
  2. Binary argument. Passing 2 restricts valid digits to 0 and 1, turning "1010" into 10 without modifying the scanner's stored radix.
  3. Case-insensitive hex. nextInt(16) accepts both lowercase "ff" and uppercase "FF", returning 255.

Example 2 — Recover from InputMismatchException Without Looping Forever

When bad input arrives, catch InputMismatchException and call sc.next() to discard the offending token.

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

public class ScannerNextIntRecover {
    public static void main(String[] args) {
        String raw = "10 abc 25 9999999999 5";
        int sum = 0;
        try (Scanner sc = new Scanner(raw)) {
            while (sc.hasNext()) {
                try {
                    sum += sc.nextInt();
                } catch (InputMismatchException e) {
                    String bad = sc.next();
                    System.out.println("Skipped invalid int: " + bad);
                }
            }
        }
        System.out.println("Valid sum: " + sum);
    }
}

How It Works

  1. Words and overflows both mismatch. Both "abc" and "9999999999" (larger than Integer.MAX_VALUE) trigger InputMismatchException.
  2. Advance inside catch. Calling sc.next() consumes the rejected token so the while (sc.hasNext()) loop moves forward instead of spinning forever.
  3. Valid integers accumulate. Only 10, 25, and 5 parse cleanly, producing 40.

Example 3 — Read a Menu Choice from the Keyboard (System.in)

Ask the user to pick a numbered option via System.in and echo their selection.

Java
import java.util.Scanner;

public class ScannerNextIntMenu {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("1. Start  2. Settings  3. Exit");
        System.out.println("Enter option number:");
        int choice = sc.nextInt();
        System.out.println("Selected option #" + choice);
    }
}

How It Works

  1. Menu prompt first. Printing both the choices and the prompt ensures the user sees the options before nextInt() pauses for input.
  2. Numeric conversion on read. Typing 2 and pressing Enter parses directly into the int variable choice.
  3. Single-pass exit. Leaving the System.in scanner unclosed avoids closing standard input before the JVM exits.

Frequently Asked Questions

It throws InputMismatchException and leaves the letters in the scanner buffer. Either check with hasNextInt() first, or consume the bad token with sc.next() inside catch.
Pass the base as an argument: sc.nextInt(2) for binary, sc.nextInt(8) for octal, or sc.nextInt(16) for hexadecimal.
In base 10, Scanner recognizes the locale grouping separator. In Locale.US, commas followed by three digits are treated as thousands separators, so "1,234" reads as 1234.
Scanner throws InputMismatchException because the value overflows a 32-bit signed int. Use nextLong() or nextBigInteger() instead.
nextInt() leaves the trailing newline from pressing Enter in the buffer, so the following nextLine() reads that empty line. Add an extra sc.nextLine() to discard it.

Next: nextLine()

Read the rest of the current line and skip the line separator.

nextLine() 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