Java ProgramsControl FlowFind Largest of Three Numbers

Find Largest of Three Numbers in Java

intermediate·  Control Flow  ·  Conditional Statements

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.

Input
12, 45, 7
Output
Largest number: 45

Java Program

Java
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

Largest number: 45

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.

How It Works
  1. 1a >= b && a >= c checks whether a is at least as large as both of the other two.
  2. 2If that fails, b >= a && b >= c checks whether b takes the top spot instead.
  3. 3If neither a nor b qualifies, c must be the largest by elimination — no further check is needed.
For 12, 45, and 7, the first check fails since 12 isn't at least as large as 45, but the second check succeeds — 45 is at least as large as both 12 and 7.
💡

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

nested if/elsecomparison chaining

Approach 2: Java 8

Java
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

Largest number: 45

Core Logic

The same three-way comparison is exactly what Stream's max() operation is built for — no manual branching required.

How It Works
  1. 1Stream.of(a, b, c) wraps the three numbers into a stream of exactly three elements.
  2. 2.max(Integer::compareTo) compares them using natural integer ordering and keeps the largest.
  3. 3.get() unwraps the Optional<Integer> that max() returns, which is safe here since the stream is never empty.
Streaming 12, 45, and 7 through 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().

Key Concepts

StreamStream.of()max()

Related Programs