How to Accept Values of Two Numbers and Print their Addition

In this Java program, we will take an integer input from the user and perform addition on those numbers. 
The program utilizes the Scanner class from the java.util package to read input from the user.

How to Accept Values of Two Numbers and Print their Addition

In this program

  1. We import the java.util.Scanner class to use for user input.
  2. We declare variables for the two numbers to be added (firstNumber and secondNumber) and a variable to store the result (sum).
  3. We create a Scanner object named scanner to read input from the user.
  4. We display a message to prompt the user to enter the first number using System.out.print.
  5. We use scanner.nextInt() to read an integer from the user, which is then assigned to the firstNumber variable.
  6. We repeat the process to get the second number.
  7. We calculate the sum of the two numbers and store it in the sum variable.
  8. Finally, we display the result using System.out.println and close the Scanner object to release resources.


import java.util.Scanner;

public class AdditionProgram {
    public static void main(String[] args) {
        int a, b, ans;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Addition Program");
        System.out.print("Enter 1st number: ");
        a = scanner.nextInt();

        System.out.print("Enter 2nd number: ");
        b = scanner.nextInt();

        ans = a + b;

        System.out.println("Addition is: " + ans);

        scanner.close();
    }
}
Join Now


Previous Year Questions Now to Boost Your Exam Performance

LOADS OF LOGIC