00:00

Java Program to Subtract Two Numbers

Last updated:

Subtraction finds the difference between two numbers with the - operator: difference = first - second. The order matters: 150 - 50 is 100, but 50 - 150 is -100.

1. Subtract Two Numbers with Fixed Values

SubtractNumbers.java
public class SubtractNumbers {
    public static void main(String[] args) {
        int a = 150;
        int b = 50;
        System.out.println(a + " - " + b + " = " + (a - b));
        System.out.println(b + " - " + a + " = " + (b - a));

        double x = 150.55;
        double y = 50.25;
        System.out.printf("%.2f - %.2f = %.2f%n", x, y, x - y);
    }
}
Output
150 - 50 = 100
50 - 150 = -100
150.55 - 50.25 = 100.30
Note: printf("%.2f") rounds the result to two decimals. Printing x - y directly would show 100.30000000000001, because most decimal fractions cannot be stored exactly in a double.

2. Subtract Two Numbers with User Input

SubtractNumbersInput.java
import java.util.Scanner;

public class SubtractNumbersInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number: ");
        double first = scanner.nextDouble();
        System.out.print("Enter second number: ");
        double second = scanner.nextDouble();
        scanner.close();

        System.out.println("Difference: " + (first - second));
    }
}
Output (with sample input)
Enter first number: 100.5
Enter second number: 50.5
Difference: 50.0

3. Exact Subtraction Using BigDecimal

For money and other values that must be exact, use BigDecimal. Create it from a String so the value is stored exactly, and call subtract() instead of using -.

SubtractBigDecimal.java
import java.math.BigDecimal;

public class SubtractBigDecimal {
    public static void main(String[] args) {
        System.out.println("double:     " + (150.55 - 50.25));

        BigDecimal a = new BigDecimal("150.55");
        BigDecimal b = new BigDecimal("50.25");
        System.out.println("BigDecimal: " + a.subtract(b));
    }
}
Output
double:     100.30000000000001
BigDecimal: 100.30

4. Summary

  • Use the - operator to subtract; the order of the numbers changes the sign of the result.
  • Wrap the subtraction in brackets when printing it together with text.
  • double results can show tiny rounding errors; format them with printf().
  • BigDecimal.subtract() gives exact results for money calculations.

Related Programs