Print an Integer in Java


Write a Java Program that prints an Integer entered by the user.

Click Here to View the Solution!
// Required import statement to use nextInt()
import java.util.Scanner;
public class PrintNumber { 
    public static void main(String[] args) {
            Scanner input = new Scanner(;
            // prompt user for input
            System.out.print("Enter an Integer: ");
            // nextInt() is the built-in method that reads
            // the next integer from the keyboard
            int num = input.nextInt()

            // println() is the built-in method that 
            // prints the following line to the console screen
            System.out.println("Integer entered = " + num);
Click Here to View the Output!
Enter an Integer: 23
Integer entered = 23
Click Here to View the Explanation!
  • This program consists of two parts. Taking input and displaying the output on the screen. In the first part reader object of Scanner class is created to take input from standard input device, which is the keyboard.
  • "Enter an Integer: " is displayed via a print() statement to prompt the user to take action.
  • A variable number is already initiated to store the input in it. reader.nextInt()  is the built in function that reads all the entered integers and stores them in the variable number until \n (Enter) is encountered. Eventually the entered number will be displayed on console screen using the function println().
  • Note : If a user enter any data type other than an integer, the compiler will show an InputMismatchException.

%d bloggers like this: