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 valueint 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
Scannerclass from thejava.utilpackage is imported in this line. It enables us to read user input via theScannerclass. -
Line 3: The
Mainclass declaration is started. Themainmethod, 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
mainmethod. -
Line 5: Creates a new
Scannerobject with the namescanner. It is used to read user input. The scanner will read input from the standard input stream, according to theSystem.invalue. -
Line 10: The
hardcodedInputvariable’s value is sent to the console after the statement"Simulating user input: ". -
Line 11: Uses the
ScannerclassnextInt()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 thenumber. -
Line 15: Closes the
Scannerobjectscanner.
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