java.util.Scanner nextInt()

Description :

This java tutorial shows how to use the nextInt method of Scanner class of java.util package. This method returns the int data type which corresponds to the integer token on the scanner buffer.

Method Syntax :

There are two overloaded method of Scanner nexInt() java method 

java scanner nextint overload method
Overloaded methods are those method with same name but with different method signatures

Method 1:

public int nextInt()

Method 2:

public int nextInt(int radix)

Parameter Input :


DataType Parameter Description
int radix the base number to scan


Method Returns :

This method simply returns the tokens of int data type.

Compatibility Version :

Requires Java 1.5 and up

Exception :


if the next token does not match the Integer regular expression, or is out of range (more than the maximum value or less than the minimum value.


if input is exhausted and we still invoked the nextInt() method.


if the java scanner is closed and we still invoked the nextInt() method.

Discussion :

The Scanner nextInt() method simply returns int if the token on the scanner buffer can be interpreted or translated into int data type. There are two overloaded method of nextInt method, which accomplishes the same task. The method without a method argument is the same as calling nextInt(radix) which is the default radix of the Scanner object. The radix currently set by the Scanner object is defined using the method useRadix(radix) and can be determine using the radix() method. The radix integer on the method argument nextInt(radix) will override the default radix already defined to the Scanner object.

Make a note that since we are scanning tokens in int data type, there is limit on the maximum and minimum value possible. The Integer.MAX_VALUE and Integer.MIN_VALUE will show what is the maximum and minimum possible int value than can be evaluated.

Java Code Example :

This java example source code demonstrates the use of nextInt method of Scanner class. Basically the code just prints those tokens of int data type derived from the input string declared on the Scanner constructor. The radix used on the example below is 16, means to say we have scanned data type in hexadecimal base number and then prints the equivalent in decimal format.

Sample Output :

Running the nextInt() method example source code of Scanner class will give you the following output

java scanner nextInt method example

java scanner nextInt method example

Exception Scenario :

Similar Method :

  • N/A

Suggested Reading List :

References :