Introduction

Java Program to Print an Integer

In this program, you'll learn to print a predefined number aw well as a nummber 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.

To understand this example, you should have the knowledge of the following Java programming topics:

1. Print an Integer

A Java program that prints a number predefined by the user is as follows:

Example: How to Print an Integer

Input

public class PrintInteger {

    public static void main(String[] args) {

        // assing a variable to store the integer
        int number = 10;

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

Output

The number is: 10

In this program we are printing a constant integer value which is definrd from first. The integer is stored in an integer variable number using the keyword int and printed using the keyword println.

2. Print an Integer (Entered by the User)

A Java program that prints a number entered by the user is as follows:

Example: How to Print an Integer entered by an user

Input

import java.util.Scanner;

public class PrintInteger {

    public static void main(String[] args) {

        // Creates a reader instance which takes
        // 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);
    }
}

Output

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().

Try Yourself

  1. Negative Number: Try entering a negative number like -50. Does it work?
  2. Floating Point: What happens if you enter 10.5? Why?
  3. Multiple Numbers: Modify the code to read and print two integers.
  4. Text Input: Run the program and enter "Hello". Observe the error (InputMismatchException).
  5. Brain Twister: Print the largest possible integer in Java. Hint: Use Integer.MAX_VALUE.