Java Program to Subtract Two Numbers

Introduction

In this tutorial, we will learn how to write a simple Java program to subtract two numbers. We will explore four different approaches:

  1. Using the Subtraction Operator (-): The fundamental way to perform subtraction using explicit data types.
  2. Taking Dynamic User Input (Scanner): An interactive approach that reads input values directly from the console at runtime.
  3. Using a Helper Method: A modular approach that encapsulates subtraction logic into a reusable method.
  4. Using Local Variable Type Inference (var): A modern syntax approach introduced in Java 10 that lets the compiler infer variable types.

Note: The var keyword simplifies variable declarations, but the underlying subtraction operation remains identical. Meanwhile, the method-based approach demonstrates how the subtraction logic can be separated into a reusable method.

Let’s explore each approach step by step.

Learning Objectives

After completing this tutorial, you will be able to:

  • Use the subtraction operator (-) to compute the difference between integer values.
  • Declare and initialize standard primitive variables using the int data type.
  • Utilize the Scanner class (java.util.Scanner) to capture interactive numerical input from the console at runtime.
  • Leverage Local Variable Type Inference (var) introduced in Java 10 to write concise, type-inferred code.
  • Design and call a reusable helper method with parameters and a return value to separate calculation logic.
  • Format and print computed results clearly to the standard output using System.out.println().

Subtract Two Numbers in Java Using the Subtraction (-) Operator

Problem Statement

Write a Java program to subtract two numbers without taking input from the user. You store two integer values directly in variables inside the program, subtract the second number from the first number, and display the result on the console.

Formula Used:

difference = firstNumber - secondNumber

Input Format

No user input is required. The two numbers must be assigned directly to variables in the Java program. For this exercise, use

int firstNumber = 50;
int secondNumber = 20;

Output Format

Print the computed difference to the console in the exact format shown below:

Difference = 30

Constraints

  • Do not use Scanner, BufferedReader, or command-line arguments.
  • Store values directly in predefined variables (compile-time initialization).
  • Use the int primitive type for all numeric variables.
  • Use the standard subtraction operator (-).
  • Subtract the second number from the first number (firstNumber – secondNumber).
  • The program must execute within a standard public static void main(String[] args) method.

Expected Solution Approach of the Program

You can solve this program in four simple, straightforward steps:

  • Declare an integer variable named firstNumber and assign it the value 50.
  • Declare an integer variable secondNumber and assign it the value 20.
  • Subtract secondNumber from firstNumber using the arithmetic subtraction operator (-), and assign the calculated result to a new integer variable difference.
  • Print the value of difference to the console using System.out.println().

Core Calculation Statement

int difference = firstNumber - secondNumber;

To solve this program, no input, loop, conditional statement, array, or method is necessary.

Complete Java Program to Subtract Two Numbers

public class SubtractTwoNumbers {

    public static void main(String[] args) {
        // Step 1: Declare and initialize variables
        int firstNumber = 50;
        int secondNumber = 20;

        // Step 2: Perform subtraction
        int difference = firstNumber - secondNumber;

        // Step 3: Display the formatted result
        System.out.println("First Number  : " + firstNumber);
        System.out.println("Second Number : " + secondNumber);
        System.out.println("Difference    : " + difference);
    }
}

Console Output:

First Number  : 50
Second Number : 20
Difference    : 30

Step-by-Step Code Explanation

Step 1: Define the Class

public class SubtractTwoNumbers { ... }

In Java, all executable code must reside inside a class. The public access modifier makes the class accessible from anywhere. The class name SubtractTwoNumbers follows Java’s PascalCase naming convention.

Step 2: Define the main() Method

public static void main(String[] args) { ... }

The main method serves as the entry point of any standalone Java application. When the program runs, the Java Virtual Machine (JVM) looks for this exact method signature to start execution.

Step 3: Declare and Initialize the Variables

int firstNumber = 50;
int secondNumber = 20;

The data type (int) specifies that the variables will store 32-bit signed integer values. The variable names (firstNumber, secondNumber) are descriptive identifiers written in standard camelCase. The assignment operator (=) allocates memory for both variables and assigns the initial values 50 and 20.

Step 4: Perform the Subtraction Operation

int difference = firstNumber - secondNumber;

The subtraction operator (-) computes the difference between firstNumber (50) and secondNumber (20). The evaluated result (30) is stored in a newly declared integer variable named difference.

Step 5: Format and Print the Output

System.out.println("First Number : " + firstNumber);
System.out.println("Second Number : " + secondNumber);
System.out.println("Difference : " + difference);

System.out.println() prints the specified text to the standard console and moves the cursor to a new line. The + operator inside println() acts as a string concatenation operator, joining the string label with the variable’s value.

Java Program to Subtract Two Numbers Using Scanner (User Input)

Problem Statement

Write a Java program that reads two integers from the user and calculates their difference. The program should subtract the second number from the first number and display the result. For example, if the user enters 25 and 10, the result should be 15.

Expected Solution Approach of the Program

You can solve this program in five simple, straightforward steps:

  1. Import java.util.Scanner and create a Scanner object to read input from the keyboard.
  2. Prompt the user and read two integer values from the console, storing them in variables `firstNumber` and `secondNumber` using scanner.nextInt().
  3. Subtract secondNumber from firstNumber using the arithmetic subtraction operator (-) and store the result in an integer variable named difference.
  4. Print the entered numbers and the computed difference using System.out.println().
  5. Close the Scanner object to prevent memory and resource leaks.

Complete Java Program to Subtract Two Numbers Using Scanner

import java.util.Scanner;
public class SubtractUserInput {

    public static void main(String[] args) {
        // Step 1: Create Scanner object for standard input
        Scanner scanner = new Scanner(System.in);

        // Step 2: Read input values from the user
        System.out.print("Enter first number  : ");
        int firstNumber = scanner.nextInt();

        System.out.print("Enter second number : ");
        int secondNumber = scanner.nextInt();

        // Step 3: Perform subtraction
        int difference = firstNumber - secondNumber;

        // Step 4: Display the formatted result
        System.out.println("-------------------------");
        System.out.println("First Number  : " + firstNumber);
        System.out.println("Second Number : " + secondNumber);
        System.out.println("-------------------------");
        System.out.println("Difference    : " + difference);

        // Step 5: Explicitly close the scanner
        scanner.close();
    }
}

Console Output:

Enter first number  : 25
Enter second number : 10
-------------------------
First Number  : 25
Second Number : 10
-------------------------
Difference    : 15

Java Subtraction Program Using a Helper Method

In modular programming, it is good practice to separate the calculation logic from input and output operations. In this approach, we define a dedicated helper method named subtract() to perform the subtraction.

The main() method handles user input, calls the subtract() method with the two numbers as arguments, and displays the returned result. This separation makes the calculation logic easier to understand, test, maintain, and reuse in other parts of the application.

Complete Java Program

import java.util.Scanner;
public class SubtractUsingHelperMethod {

    // Helper method to calculate the difference between two numbers.
    public static int subtract(int firstNumber, int secondNumber) {
        return firstNumber - secondNumber;
    }

    public static void main(String[] args) {
        // Step 1: Initialize Scanner for user input
        Scanner scanner = new Scanner(System.in);

        // Step 2: Read two integer values
        System.out.print("Enter first number  : ");
        int firstNumber = scanner.nextInt();

        System.out.print("Enter second number : ");
        int secondNumber = scanner.nextInt();

        // Step 3: Call the helper method to perform subtraction
        int difference = subtract(firstNumber, secondNumber);

        // Step 4: Display the formatted result
        System.out.println("-------------------------");
        System.out.println("First Number  : " + firstNumber);
        System.out.println("Second Number : " + secondNumber);
        System.out.println("-------------------------");
        System.out.println("Difference    : " + difference);

        // Step 5: Close the scanner resource
        scanner.close();
    }
}

Console Output:

Enter first number  : 50
Enter second number : 30
-------------------------
First Number  : 50
Second Number : 30
-------------------------
Difference    : 20

Subtraction Program Using Local Variable Type Inference (var)

Introduced in Java 10 through JEP 286, the var keyword enables local variable type inference. Instead of explicitly specifying the type of a local variable, such as int, the compiler infers the variable’s type based on assigned values at compile time.

The inferred type is still fixed and statically checked, so var does not make Java dynamically typed. Look at the program code below.

Complete Java Program

import java.util.Scanner;
public class SubtractUsingVar {

    public static void main(String[] args) {
        // Step 1: Initialize Scanner using 'var' (inferred as java.util.Scanner)
        var scanner = new Scanner(System.in);

        // Step 2: Read two integer values using 'var' (inferred as int)
        System.out.print("Enter first number  : ");
        var firstNumber = scanner.nextInt();

        System.out.print("Enter second number : ");
        var secondNumber = scanner.nextInt();

        // Step 3: Compute the difference (inferred as int)
        var difference = firstNumber - secondNumber;

        // Step 4: Display the formatted result
        System.out.println("-------------------------");
        System.out.println("First Number  : " + firstNumber);
        System.out.println("Second Number : " + secondNumber);
        System.out.println("-------------------------");
        System.out.println("Difference    : " + difference);

        // Step 5: Close the scanner resource
        scanner.close();
    }
}

Expected Output:

Enter first number  : 30
Enter second number : 10
-------------------------
First Number  : 30
Second Number : 10
-------------------------
Difference    : 20

Follow-up Challenge

Challenge 1: Subtract Two Double Values Using User Input

After solving these programs, try modifying the program to read two double values instead of integers and calculate their difference. For example:

Input:

double firstNumber = 25.5
double secondNumber = 10.25

Output:

Difference = 15.25

Challenge 2: Subtract Three Numbers Using User Input

Modify the program so that it accepts three integers from the user and calculates their difference.

Read the three numbers in order and subtract the second and third numbers from the first number.

Calculation:

result = firstNumber - secondNumber - thirdNumber

For example, if the user enters:

100
30
20

The calculation should be:

100 - 30 - 20 = 50

Expected output:

Result = 50

Goal: Practice reading multiple values using Scanner, storing them in variables, and applying arithmetic operations in the correct order.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.