1. Introduction
Adding two numbers is a fundamental and introductory exercise for those delving into the world of Java programming. This program will give beginners a glimpse into variable declaration, taking user input, conducting arithmetic operations, and displaying output.
2. Program Steps
1. Import the Scanner class from the java.util package.
2. Define the main class named AddTwoNumbers.
3. Inside the main class, define the main method.
4. Inside the main method, create an object of the Scanner class to take user input.
5. Prompt the user to enter the first number and store it in a variable.
6. Prompt the user to enter the second number and store it in another variable.
7. Add the two numbers and store the result in a third variable.
8. Print the result to the console.
3. Code Program
import java.util.Scanner; // 1. Importing Scanner class for user input
public class AddTwoNumbers { // 2. Defining the main class
public static void main(String[] args) { // 3. Defining the main method
Scanner input = new Scanner(System.in); // 4. Creating Scanner object to take user input
System.out.print("Enter the first number: "); // 5. Prompting user for the first number
int num1 = input.nextInt(); // Storing the first number in variable num1
System.out.print("Enter the second number: "); // 6. Prompting user for the second number
int num2 = input.nextInt(); // Storing the second number in variable num2
int sum = num1 + num2; // 7. Adding num1 and num2, storing the result in variable sum
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum); // 8. Printing the result
input.close(); // Closing the Scanner object to avoid memory leak
}
}
Output:
Enter the first number: 12 Enter the second number: 8 The sum of 12 and 8 is: 20
4. Step By Step Explanation
– Step 1: The Scanner class from the java.util package is imported for taking user input.
– Step 2: The main class AddTwoNumbers is defined.
– Step 3: The main method, the entry point of the Java program, is defined inside the main class.
– Step 4: An object of the Scanner class named "input" is created to read user input.
– Step 5: The user is prompted to enter the first number, 12, which is read by the Scanner object and stored in the variable num1.
– Step 6: Similarly, the user is prompted to enter the second number, 8, which is stored in the variable num2.
– Step 7: The variables num1 and num2 are added together, and the result, 20, is stored in a new variable named sum.
– Step 8: Finally, the sum of the two numbers is printed to the console.
– The Scanner object is then closed to prevent resource leak.