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 InputMismatchExceptionwithout 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
Call
What 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
Parameter
Description
radix (optional)
The number base (2 to 36) used to interpret the token digits.
Return Value
Return Value
Description
int
The parsed 32-bit integer value.
Throws InputMismatchException
If the next token is not a valid integer or overflows int range.
Menu prompt first. Printing both the choices and the prompt ensures the user sees the options before nextInt() pauses for input.
Numeric conversion on read. Typing 2 and pressing Enter parses directly into the int variable choice.
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.