In this section, we will learn how to create a Java program to find the largest of three numbers. Along with this, we will also learn to find the largest of three numbers in Java using the ternary operator.
Using Ternary Operator
Before moving to the program, let's understand the ternary operator.
It is a part of the Java conditional statement. It contains three operands. It evaluates a Boolean expression and assigned a value based on the result. We can use it in place of the if-else statement. The syntax of the ternary operator is as follows:
variable_name = (expression) ? value if true:value if false
If the above expression returns true the value before the colon is assigned to the variable variable_name, else the value after the colon is assigned to the variable.
LargestNumberExample1.java
Output:
We can also compare all the three numbers by using the ternary operator in a single statement. If we want to compare three numbers in a single statement, we must use the following statement.
d = c > (a>b ? a:b) ? c:((a>b) ? a:b);
In the following program, we have used a single statement to find the largest of three numbers.
LargestNumberExample2.java
Output:
Using if-else..if
LargestNumberExample3.java
Output:
Using nested if
LargestNumberExample4.java
Output:
LargestNumberExample5.java
Output 1:
Output 2: