Java Program to Find the Largest Among Three Numbers

In this program, you’ll learn to find the largest among three numbers using if else and nested if..else statement in Java.

Example 1: Find Largest Among three numbers using if..else statement

  1. public class Largest {
  2. public static void main(String[] args) {
  3. double n1 = -4.5, n2 = 3.9, n3 = 2.5;
  4. if( n1 >= n2 && n1 >= n3)
  5. System.out.println(n1 + " is the largest number.");
  6. else if (n2 >= n1 && n2 >= n3)
  7. System.out.println(n2 + " is the largest number.");
  8. else
  9. System.out.println(n3 + " is the largest number.");
  10. }
  11. }

When you run the program, the output will be:

3.9 is the largest number.

In the above program, three numbers -4.5, 3.9 and 2.5 are stored in variables n1, n2 and n3 respectively.

Then, to find the largest, the following conditions are checked using if else statements

  • If n1 is greater or equals to both n2 and n3, n1 is the greatest.
  • If n2 is greater or equals to both n1 and n3, n2 is the greatest.
  • Else, n3 is the greatest.

The greatest number can also be found using a nested if..else statement.


Example 2: Find the largest number among three using nested if..else statement

  1. public class Largest {
  2. public static void main(String[] args) {
  3. double n1 = -4.5, n2 = 3.9, n3 = 5.5;
  4. if(n1 >= n2) {
  5. if(n1 >= n3)
  6. System.out.println(n1 + " is the largest number.");
  7. else
  8. System.out.println(n3 + " is the largest number.");
  9. } else {
  10. if(n2 >= n3)
  11. System.out.println(n2 + " is the largest number.");
  12. else
  13. System.out.println(n3 + " is the largest number.");
  14. }
  15. }
  16. }

When you run the program, the output will be:

5.5 is the largest number.

In the above program, instead of checking for two conditions in a single if statement, we use nested if to find the greatest.

Then, to find the largest, the following conditions are checked using if else statements

  • If n1 is greater or equals to n2,
    • and if n1 is greater or equals to n3, n1 is the greatest.
    • else, n3 is the greatest.
  • Else,
    • if n2 is greater or equals to both n3, n2 is the greatest.
    • else, n3 is the greatest.