Java Program to Find Largest of Three Numbers
if-else statements to compare the numbers and print the largest, like if (a >= b && a >= c) System.out.println(a); else if (b >= a && b >= c) System.out.println(b); else System.out.println(c);.Examples
How to Think About It
>=. If it is greater or equal to both, it is the largest. Otherwise, compare the second number with the third. The one that is greater or equal is the largest.Algorithm
Code
public class LargestOfThree { public static void main(String[] args) { int a = 5, b = 10, c = 3; int largest; if (a >= b && a >= c) { largest = a; } else if (b >= a && b >= c) { largest = b; } else { largest = c; } System.out.println("Largest number is " + largest); } }
Dry Run
Let's trace the example where a=5, b=10, c=3 through the code.
Compare a with b and c
Check if 5 >= 10 and 5 >= 3. This is false because 5 is not >= 10.
Compare b with c
Check if 10 >= 5 and 10 >= 3. This is true because 10 >= 5 and 10 >= 3.
Assign largest
Set largest = 10.
Print result
Output: Largest number is 10.
| Step | Condition | Result | Largest |
|---|---|---|---|
| 1 | a >= b && a >= c (5 >= 10 && 5 >= 3) | false | undefined |
| 2 | b >= a && b >= c (10 >= 5 && 10 >= 3) | true | 10 |
| 3 | Assign largest = b | - | 10 |
| 4 | Print largest | - | 10 |
Why This Works
Step 1: Compare first number
We use if (a >= b && a >= c) to check if the first number is the largest by comparing it to the other two.
Step 2: Compare second number
If the first number is not largest, we check if the second number is larger or equal to the third using else if (b >= a && b >= c).
Step 3: Assign and print largest
Based on the comparisons, we assign the largest number to a variable and print it with System.out.println.
Alternative Approaches
public class LargestOfThree { public static void main(String[] args) { int a = 5, b = 10, c = 3; int largest = Math.max(a, Math.max(b, c)); System.out.println("Largest number is " + largest); } }
public class LargestOfThree { public static void main(String[] args) { int a = 5, b = 10, c = 3; int largest = a; if (b > largest) { largest = b; } if (c > largest) { largest = c; } System.out.println("Largest number is " + largest); } }
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of comparisons regardless of input size, so it runs in constant time O(1).
Space Complexity
Only a few variables are used to store input and the largest number, so space complexity is O(1).
Which Approach is Fastest?
All approaches run in constant time, but using Math.max is concise and readable, while if-else gives more control.
| Approach | Time | Space | Best For |
|---|---|---|---|
| If-else comparisons | O(1) | O(1) | Clear logic and beginner understanding |
| Math.max method | O(1) | O(1) | Concise and clean code |
| Nested if updates | O(1) | O(1) | Stepwise comparison and easy to extend |
Math.max for a concise way to find the largest number among multiple values.