English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to use if else and nested if..else statements in Java to find the largest number among three numbers.
public class Largest { public static void main(String[] args) { double n1 = -4.5, n2 = 3.9, n3 = 2.5; if(n1 >= n2 && n1 >= n3) System.out.println(n1 + "is the largest number."); else if (n2 >= n1 && n2 >= n3) System.out.println(n2 + "is the largest number."); else System.out.println(n3 + "is the largest number."); } }
When running the program, the output is:
3.9 is the largest number.
In the above program, three numbers-4.5,3.9and2.5and store them separately in variables n1, n2and n3.
Then, to find the largest number, use the if...else statement to check the following conditions
if n1is greater than or equal to n2and n3, n1is the largest.
if n2is greater than or equal to n1and n3, n2is the largest.
otherwise, n3is the largest.
You can also find the largest number using nested if-else statements.
public class Largest { public static void main(String[] args) { double n1 = -4.5, n2 = 3.9, n3 = 5.5; if(n1 >= n2) { if(n1 >= n3) System.out.println(n1 + "is the largest number."); else System.out.println(n3 + "is the largest number."); } else { if(n2 >= n3) System.out.println(n2 + "is the largest number."); else System.out.println(n3 + "is the largest number."); } } }
When running the program, the output is:
5.5 is the largest number.
In the above program, we are not checking two conditions in a single if statement, but using nested if to find the maximum condition.
Then, to find the largest number, use the if-else statement to check the following conditions
if n1is greater than or equal to n2,
if n1is greater than or equal to n3, n1is the largest.
otherwise, n3is the largest.
in other cases,
if n2is greater than or equal to both n3, n2is the largest.
otherwise, n3is the largest.