What is Scanner.nextInt() in Java?

Java includes a built-in method named Scanner.nextInt() that is a part of the java.util.Scanner class.

It reads an integer input from the user via standard input, which frequently comes from the keyboard.

Syntax

int nextInt()

This function reads the next token from the input as an integer and returns that integer value when called on a Scanner object.

Note: The nextInt() method does not take any arguments.

Code example

import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Simulating user input by providing a hardcoded value
int hardcodedInput = 42;
System.out.println("Simulating user input: " + hardcodedInput);
int number = scanner.nextInt();
System.out.println("You entered: " + number);
scanner.close();
}
}

Enter the input below

Note: To run the above code, we have to type an input in the above widget.

Explanation

  • Line 1: The Scanner class from the java.util package is imported in this line. It enables us to read user input via the Scanner class.

  • Line 3: The Main class declaration is started. The main method, which is the Java program’s entry point, is contained in this class.

  • Line 4: Starting place for running the program. The program logic is written in the main method.

  • Line 5: Creates a new Scanner object with the name scanner. It is used to read user input. The scanner will read input from the standard input stream, according to the System.in value.

  • Line 10: The hardcodedInput variable’s value is sent to the console after the statement "Simulating user input: ".

  • Line 11: Uses the Scanner class nextInt() function to read an integer input from the user. Before assigning that value to the number variable, it waits for the user to input an integer value.

  • Line 13: Prints the message "You entered: " followed by the value of the number.

  • Line 15: Closes the Scanner object scanner.

Conclusion

Overall, Scanner.nextInt() is a convenient method for reading integer values from different input sources in Java. It simplifies the process of parsing and converting user input into integer data for further processing in your program.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved