Write a java program to find largest of three numbers using ternary operator in java. This problem can also be asked like, find maximum of three numbers using conditional operator.
Given three input numbers, Write a java code to print largest or biggest of three numbers using ternary operator.
Suppose, Given three input numbers a, b and c. If a is greater than b and c then a is the largest of three numbers. Similarly, if b is greater than a and c then b is the largest of three numbers else c is largest.
How do we find biggest of 3 numbers using ternary operator in java. Let’s first understand what is ternary operator.
What is Ternary Operator?
A ternary or conditional operator evaluates a boolean expression and assign the value based on the result. Let’s take a example for better understanding.
result = (expression) ? value if true : value if false
int result = (3 > 2) ? 3 : 2;
In the above statement, we are checking if 3 is greater than 2. If this expression evaluates to true then 3 will be assigned in a result variable else 2 is assigned.
Find largest of three numbers using ternary operator – video tutorial
Find Largest of Three Numbers using Ternary Operator in Java
In this example, we are going to write a program in java to find maximum of three numbers using conditional operator.
Given three input numbers, Let’s assume the values are assigned in variable a, b and c.
Then, we are going to use the ternary operator to first compare a with b. If this expression evaluates to true then variable a is compared with c. If it’s true then the value of a is assigned to a result variable.
Similarly, In else condition we are comparing the value b like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/** * Print largest of three numbers using ternary operator in java */ public class LargestOfThree { public static void main(String[] args) { //Three input numbers int a = 55; int b = 95; int c = 75; int result = ( a > b ) ? (a > c ? a : c) : ( b > c ? b : c); System.out.println(result); } } |
In this video tutorial, i have explained how to print largest of three numbers using ternary or conditional operator without using if else condition.