Java Program to Print an Integer (Entered by User)

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

In this example, we will 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.     

Let's check code

import java.util.Scanner;

public class HelloWorld {

    public static void main(String[] args) {

        // Creates a reader instance which will take
        // input from standard input - keyboard
        Scanner reader = new Scanner(System.in);
        System.out.print("Enter a number: ");

        // nextInt() reads the next integer from the keyboard
        int number = reader.nextInt();

        // println() prints the following line to the output screen
        System.out.println("You entered: " + number);
    }
}

When we run the program, the output will be:


Enter a number: 10

You entered: 10


 

In this example,  Scanner class object , 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 we enter any character which is not an integer, the compiler will throw an InputMismatchException.

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


Subscribe For Daily Updates

JAVA File IO examples

JAVA Date & Time Progamming Examples

JAVA Collections

Flutter Questions
Android Questions