Subtract Two Numbers in Java
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.
Java Program
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
Core Logic
The - operator subtracts the second value from the first, evaluated left to right just like standard arithmetic.
- 1
aholds10andbholds4. - 2
a - bevaluates to6, the result of subtractingbfroma. - 3The result is stored in
differenceand printed alongside a label.
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
Approach 2: Java 8
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
Core Logic
Subtraction can be captured the same way as addition — a lambda stored in an IntBinaryOperator instead of an inline expression.
- 1
IntBinaryOperator subtract = (x, y) -> x - y;stores the subtraction logic as a value. - 2
subtract.applyAsInt(a, b)runs the lambda withaandb, in that order, since subtraction isn't commutative. - 3The result is stored and printed exactly as before.
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
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.