Find the Largest Among Four Numbers in Java

Exercise:

Write a Java Program to find the largest amongst four numbers .

Click Here to View Solution!
public class LargestNumber{
  
     public static void main(String[] args) {
  
         double n1 = 7.2, n2 = -11.9, n3 = 6.5, n4=8.9;
  
         if( n1 >= n2 && n1 >= n3 && n1>=n4)
         System.out.println(n1 + " is the largest number among all.");
  
         else if (n2 >= n1 && n2 >= n3 && n2>=n4)
         System.out.println(n2 + " is the largest number among all.");

         else if (n3 >= n1 && n3 >= n2 && n3>=n4)
         System.out.println(n3 + " is the largest number among all.");
  
         else
         System.out.println(n4 + " is the largest number among all.");
     }
 } 
Click Here to View Output!
8.9 is the largest number among all.
Click Here to View Explanation!
  • This program is created to find out the largest number among four different values using the if…else statement and prints the largest number.
  • Initially, four distinct numbers are stored in the variables n1, n2 , n3 and n4. The numbers are 7.2 , -11.9 , 6.5 and 8.9.
  • In order to identify the largest value among these four numbers, the following if…else statements are used.
  • If the value in n1 is greater or equal to all the values in the variable n2 ,n3 and n4 then the value in n1 will be the largest and print n1 is the largest among all.
  • If the value in n2 is greater or equal to all the values in the variables in n1 , n3 and n4 then the value is n2 will be the largest and print n2 is the largest among all.
  • If the value in n3 is greater or equal to all the values in the variables in n1 , n2 and n4 then the value is n3 will be the largest and print n3 is the largest among all.
  • And the final else condition, that if neither the values in the variables n1 , n2 and n3 are the greatest, then that consequently means that the value in n4 is the largest and print n4 is the largest among all.