This program finds the largest of three numbers using ternary operator. Before going through the program, lets understand what is a ternary Operator:
Ternary operator evaluates a boolean expression and assign the value based on the result.
variable num = (expression) ? value if true : value if false
If the expression results true then the first value before the colon (:) is assigned to the variable num else the second value is assigned to the num.
Example: Program to find the largest number using ternary operator
In this Program, we have used the ternary operator twice to compare the three numbers, however you can compare all three numbers in one statement using ternary operator like this:
result = num3 > (num1>num2 ? num1:num2) ? num3:((num1>num2) ? num1:num2);
However if you are finding it difficult to understand then use it like I have shown in the example below:
import java.util.Scanner; public class JavaExample { public static void main(String[] args) { int num1, num2, num3, result, temp; /* Scanner is used for getting user input. * The nextInt() method of scanner reads the * integer entered by user. */ Scanner scanner = new Scanner(System.in); System.out.println("Enter First Number:"); num1 = scanner.nextInt(); System.out.println("Enter Second Number:"); num2 = scanner.nextInt(); System.out.println("Enter Third Number:"); num3 = scanner.nextInt(); scanner.close(); /* In first step we are comparing only num1 and * num2 and storing the largest number into the * temp variable and then comparing the temp and * num3 to get final result. */ temp = num1>num2 ? num1:num2; result = num3>temp ? num3:temp; System.out.println("Largest Number is:"+result); } }
Output:
Enter First Number: 89 Enter Second Number: 109 Enter Third Number: 8 Largest Number is:109
Leave a Reply