Java ProgramsControl FlowFind Smallest of Three Numbers

Find Smallest of Three Numbers in Java

intermediate·  Control Flow  ·  Conditional Statements

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.

Input
34, 12, 27
Output
Smallest number: 12

Java Program

Java
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

Smallest number: 12

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.

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

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 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

Smallest number: 12

Core Logic

The same three-way comparison is exactly what Stream's min() 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.min(Integer::compareTo) compares them using natural integer ordering and keeps the smallest.
  3. 3.get() unwraps the Optional&lt;Integer&gt; that min() returns, which is safe here since the stream is never empty.
Streaming 34, 12, and 27 through 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().

Key Concepts

StreamStream.of()min()

Related Programs