Java Programs›Basics & I/O›Subtract Two Numbers

Subtract Two Numbers in Java

beginner·  Basics & I/O  ·  Arithmetic

Problem

Subtracting two numbers with the - operator finds the difference between them.

Given two integers, subtract the second from the first and print the result.

Input
10, 4
Output
Difference: 6

Java Program

Java
public class SubtractTwoNumbers { public static void main(String[] args) { int a = 10; int b = 4; int difference = a - b; // order matters here System.out.println("Difference: " + difference); } }

Output

Difference: 6

Core Logic

The - operator subtracts the second value from the first, evaluated left to right just like standard arithmetic.

How It Works
  1. 1a holds 10 and b holds 4.
  2. 2a - b evaluates to 6, the result of subtracting b from a.
  3. 3The result is stored in difference and printed alongside a label.
With a = 10 and b = 4, a - b evaluates to 6, so the program prints "Difference: 6".
💡

Key Point: Order matters with subtraction — a - b and b - a give different (often negatively signed) results, unlike addition or multiplication.

Key Concepts

- operatorintarithmetic

Approach 2: Java 8

Java
import java.util.function.IntBinaryOperator; public class SubtractTwoNumbersLambda { public static void main(String[] args) { int a = 10; int b = 4; // Order still matters inside the lambda — this computes a - b, not b - a IntBinaryOperator subtract = (x, y) -> x - y; int difference = subtract.applyAsInt(a, b); System.out.println("Difference: " + difference); } }

Output

Difference: 6

Core Logic

Subtraction can be captured the same way as addition — a lambda stored in an IntBinaryOperator instead of an inline expression.

How It Works
  1. 1IntBinaryOperator subtract = (x, y) -> x - y; stores the subtraction logic as a value.
  2. 2subtract.applyAsInt(a, b) runs the lambda with a and b, in that order, since subtraction isn't commutative.
  3. 3The result is stored and printed exactly as before.
With a = 10 and b = 4, subtract.applyAsInt(10, 4) evaluates x - y and returns 6.
💡

Key Point: Order still matters inside the lambda body — subtract.applyAsInt(b, a) would silently give the wrong sign, same trap as writing b - a directly.

Key Concepts

IntBinaryOperatorfunctional interfacelambda expression

Interview Questions

Can subtraction overflow?

Yes, for example Integer.MIN_VALUE - 1 wraps to Integer.MAX_VALUE. Math.subtractExact throws instead.

How do you get the difference regardless of order?

Math.abs(a - b) returns a non-negative difference.

Learn the Concept

Related Programs