Java Program to Find the Largest of Three Numbers
Finding the largest of three numbers is a good exercise in conditions. A number is the largest if it is greater than or equal to each of the other two. This page shows four ways to write the check in Java.
1. Largest Number Using if-else and &&
Each condition compares one number with both of the others, joined with the logical AND operator &&. Using >= instead of > makes the program work when two numbers are equal.
public class LargestOfThree {
public static void main(String[] args) {
int a = 40, b = 70, c = 25;
int largest;
if (a >= b && a >= c) {
largest = a;
} else if (b >= a && b >= c) {
largest = b;
} else {
largest = c;
}
System.out.println("Numbers: " + a + ", " + b + ", " + c);
System.out.println(largest + " is the largest number.");
}
}
Numbers: 40, 70, 25 70 is the largest number.
2. Largest Number Using Nested if-else and User Input
A nested if first compares a and b, then compares the winner with c. This version reads double values from the user.
import java.util.Scanner;
public class LargestOfThreeInput {
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 largest;
if (a >= b) {
largest = (a >= c) ? a : c;
} else {
largest = (b >= c) ? b : c;
}
System.out.println(largest + " is the largest number.");
}
}
Enter the first number: 30 Enter the second number: 80 Enter the third number: 60 80.0 is the largest number.
3. Largest Number Using the Ternary Operator
Two nested ternary expressions fit the whole comparison into one statement.
public class LargestTernary {
public static void main(String[] args) {
int a = 12, b = 45, c = 33;
int largest = (a >= b) ? (a >= c ? a : c) : (b >= c ? b : c);
System.out.println("Largest of " + a + ", " + b + " and " + c + " is " + largest);
}
}
Largest of 12, 45 and 33 is 45
4. Largest Number Using Math.max()
Math.max(x, y) returns the larger of two values. Calling it twice gives the largest of three. This is the shortest and clearest version.
public class LargestMathMax {
public static void main(String[] args) {
int a = -5, b = -2, c = -9;
int largest = Math.max(a, Math.max(b, c));
System.out.println("Largest of " + a + ", " + b + " and " + c + " is " + largest);
}
}
Largest of -5, -2 and -9 is -2
5. Summary
- A number is the largest when it is greater than or equal to both other numbers.
- Use
>=so equal values are handled correctly. - Nested
if-elseor the ternary operator need only two comparisons. Math.max(a, Math.max(b, c))is the simplest solution in practice.