Java Program to Print an Integer (Entered by the User)

In this program, you’ll learn to print a number entered by the user in Java. The integer is stored in a variable using System.in, and is displayed on the screen using System.out.

Example: How to Print an Integer entered by an user

  1. import java.util.Scanner;
  2. public class HelloWorld {
  3. public static void main(String[] args) {
  4. // Creates a reader instance which takes
  5. // input from standard input - keyboard
  6. Scanner reader = new Scanner(System.in);
  7. System.out.print("Enter a number: ");
  8. // nextInt() reads the next integer from the keyboard
  9. int number = reader.nextInt();
  10. // println() prints the following line to the output screen
  11. System.out.println("You entered: " + number);
  12. }
  13. }

When you run the program, the output will be:

Enter a number: 10
You entered: 10

In this program, an object of Scanner class, reader  is created to take inputs from standard input, which is keyboard.

Then, Enter a number prompt is printed to give the user a visual cue as to what they should do next.

reader.nextInt() then reads all entered integers from the keyboard unless it encounters a new line character \n (Enter). The entered integers are then saved to the integer variable number.

If you enter any character which is not an integer, the compiler will throw an InputMismatchException.

Finally, number is printed onto the standard output (System.out) – computer screen using the function println().