1. Introduction
Subtracting two numbers is another foundational exercise for Java beginners. This program demonstrates variable declaration, user input, arithmetic operations, and output display, offering a practical way to understand Java’s basic building blocks.
2. Program Steps
1. Import the Scanner class from the java.util package.
2. Define the main class named SubtractTwoNumbers.
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. Subtract the second number from the first number 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 SubtractTwoNumbers { // 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 difference = num1 - num2; // 7. Subtracting num2 from num1, storing the result in variable difference
System.out.println("The difference between " + num1 + " and " + num2 + " is: " + difference); // 8. Printing the result
input.close(); // Closing the Scanner object to avoid memory leak
}
}
Output:
Enter the first number: 15 Enter the second number: 8 The difference between 15 and 8 is: 7
4. Step By Step Explanation
– Step 1: The Scanner class from the java.util package is imported. It is used to take user input.
– Step 2: The main class named SubtractTwoNumbers is defined.
– Step 3: The main method is defined inside the main class. This method is the entry point of the Java program.
– 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, 15, 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 num2 is subtracted from num1, and the result, 7, is stored in a new variable named difference.
– Step 8: Finally, the difference of the two numbers is printed to the console.
– The Scanner object is then closed to prevent resource leak.