Find Smallest of Three Numbers in Java
Problem
The smallest of three numbers is whichever one is not larger than either of the other two.
Given three integers, determine which one is the smallest.
Java Program
public class SmallestOfThreeNumbers {
public static void main(String[] args) {
int a = 34, b = 12, c = 27;
int smallest;
if (a <= b && a <= c) {
smallest = a;
} else if (b <= a && b <= c) {
smallest = b;
} else {
smallest = c; // neither a nor b won, so c must be the smallest by elimination
}
System.out.println("Smallest number: " + smallest);
}
}Output
Core Logic
Comparing each number against both of the others, and keeping whichever one is never larger, finds the smallest without needing to sort anything.
- 1
a <= b && a <= cchecks whetherais at most as large as both of the other two. - 2If that fails,
b <= a && b <= cchecks whetherbtakes the bottom spot instead. - 3If neither
anorbqualifies,cmust be the smallest by elimination — no further check is needed.
Key Point: Using <= instead of < in every comparison means ties are still resolved correctly — the first variable satisfying the condition wins, without needing a separate tie-breaking rule.
Key Concepts
Approach 2: Java 8
import java.util.stream.Stream;
public class SmallestOfThreeNumbersStream {
public static void main(String[] args) {
int a = 34, b = 12, c = 27;
// min() compares every element pairwise and keeps the smallest
int smallest = Stream.of(a, b, c).min(Integer::compareTo).get();
System.out.println("Smallest number: " + smallest);
}
}
Output
Core Logic
The same three-way comparison is exactly what Stream's min() operation is built for — no manual branching required.
- 1
Stream.of(a, b, c)wraps the three numbers into a stream of exactly three elements. - 2
.min(Integer::compareTo)compares them using natural integer ordering and keeps the smallest. - 3
.get()unwraps theOptional<Integer>thatmin()returns, which is safe here since the stream is never empty.
min() compares them internally and returns 12, the same answer the branching version finds.Key Point: This scales cleanly to more values — extending the branching version to four or five numbers means writing more comparisons, but the stream version just needs more arguments passed to Stream.of().