Java Program to Find the Smallest of Three Numbers
A number is the smallest of three if it is less than or equal to each of the other two. This page shows four ways to find it in Java, from if-else to Math.min().
1. Smallest Number Using if-else and &&
Each condition compares one number with both others. <= makes the program correct when two of the numbers are equal.
public class SmallestOfThree {
public static void main(String[] args) {
int a = 70, b = 85, c = 92;
int smallest;
if (a <= b && a <= c) {
smallest = a;
} else if (b <= a && b <= c) {
smallest = b;
} else {
smallest = c;
}
System.out.println("Numbers: " + a + ", " + b + ", " + c);
System.out.println(smallest + " is the smallest number.");
}
}
Output
Numbers: 70, 85, 92 70 is the smallest number.
2. Smallest Number Using Nested if-else and User Input
import java.util.Scanner;
public class SmallestOfThreeInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double a = scanner.nextDouble();
System.out.print("Enter the second number: ");
double b = scanner.nextDouble();
System.out.print("Enter the third number: ");
double c = scanner.nextDouble();
scanner.close();
double smallest;
if (a <= b) {
smallest = (a <= c) ? a : c;
} else {
smallest = (b <= c) ? b : c;
}
System.out.println(smallest + " is the smallest number.");
}
}
Output (with sample input)
Enter the first number: 40 Enter the second number: 10 Enter the third number: 70 10.0 is the smallest number.
3. Smallest Number Using the Ternary Operator
public class SmallestTernary {
public static void main(String[] args) {
int a = 18, b = 7, c = 11;
int smallest = (a <= b) ? (a <= c ? a : c) : (b <= c ? b : c);
System.out.println("Smallest of " + a + ", " + b + " and " + c + " is " + smallest);
}
}
Output
Smallest of 18, 7 and 11 is 7
4. Smallest Number Using Math.min()
Math.min(x, y) returns the smaller of two values, so two calls find the smallest of three.
public class SmallestMathMin {
public static void main(String[] args) {
double a = 4.5, b = -1.25, c = 0.0;
double smallest = Math.min(a, Math.min(b, c));
System.out.println("Smallest of " + a + ", " + b + " and " + c + " is " + smallest);
}
}
Output
Smallest of 4.5, -1.25 and 0.0 is -1.25
5. Summary
- A number is the smallest when it is less than or equal to both other numbers.
- Use
<=so equal values are handled correctly. - Nested
if-elseand the ternary operator need only two comparisons. Math.min(a, Math.min(b, c))is the simplest solution in practice.
Related Programs
Was this tutorial helpful?