Find Smallest of Two Numbers in Java
beginner· Control Flow · Conditional Statements
Problem
The smaller of two numbers is whichever one falls short of the other — a single comparison settles it.
Given two integers, determine which one is the smaller.
Input
23, 9
Output
Smallest number: 9
Java Program
Java
public class SmallestOfTwoNumbers {
public static void main(String[] args) {
int a = 23, b = 9;
int smallest;
if (a < b) {
smallest = a;
} else {
smallest = b; // also covers the tie case, where either value is a valid answer
}
System.out.println("Smallest number: " + smallest);
}
}Output
Smallest number: 9
Core Logic
Comparing the two numbers directly with a single less-than check picks out the smaller one in one step.
How It Works
- 1
a < bchecks whether the first number is strictly less than the second. - 2If true,
ais assigned tosmallest. - 3Otherwise,
bis used instead — this covers both the case wherebis smaller and the case where the two are equal.
For 23 and 9,
a < b is false, so smallest takes b's value, 9.💡
Key Point: Falling through to b in the else branch also correctly handles a tie — when both numbers are equal, either one is a valid 'smallest', so returning b is fine.
Key Concepts
if/elsecomparison operator
Approach 2: Using Math.min()
Java
public class SmallestOfTwoNumbersMathMin {
public static void main(String[] args) {
int a = 23, b = 9;
// Math.min() picks the smaller of the two directly
int smallest = Math.min(a, b);
System.out.println("Smallest number: " + smallest);
}
}
Output
Smallest number: 9
Core Logic
Java's own Math.min() already performs this exact comparison internally, so there's no need to write the if/else out by hand.
How It Works
- 1
Math.min(a, b)compares the two arguments and returns whichever is smaller. - 2It handles a tie the same way the manual version does — returning either value when they're equal, since both are correct.
Math.min(23, 9) returns 9 directly.💡
Key Point: Math.min() is overloaded for int, long, float, and double, so the exact same call works regardless of which numeric type is being compared.
Key Concepts
Math.min()built-in method