Find Largest of Three Numbers in Java
Problem
The largest of three numbers is whichever one is not smaller than either of the other two.
Given three integers, determine which one is the largest.
Java Program
public class LargestOfThreeNumbers {
public static void main(String[] args) {
int a = 12, b = 45, c = 7;
int largest;
if (a >= b && a >= c) {
largest = a;
} else if (b >= a && b >= c) {
largest = b;
} else {
largest = c; // neither a nor b won, so c must be the largest by elimination
}
System.out.println("Largest number: " + largest);
}
}Output
Core Logic
Comparing each number against both of the others, and keeping whichever one is never smaller, finds the largest without needing to sort anything.
- 1
a >= b && a >= cchecks whetherais at least as large as both of the other two. - 2If that fails,
b >= a && b >= cchecks whetherbtakes the top spot instead. - 3If neither
anorbqualifies,cmust be the largest 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 LargestOfThreeNumbersStream {
public static void main(String[] args) {
int a = 12, b = 45, c = 7;
// max() compares every element pairwise and keeps the largest
int largest = Stream.of(a, b, c).max(Integer::compareTo).get();
System.out.println("Largest number: " + largest);
}
}
Output
Core Logic
The same three-way comparison is exactly what Stream's max() 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
.max(Integer::compareTo)compares them using natural integer ordering and keeps the largest. - 3
.get()unwraps theOptional<Integer>thatmax()returns, which is safe here since the stream is never empty.
max() compares them internally and returns 45, 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().