Find maximum/minimum of three numbers using ternary operator(conditional operator) in java

Ternary operator :-  It is one of the handy programming construct which is commonly used to minimize number of keystrokes.In order to find maximum of two numbers general syntax of ternary operator is:  
Number1 <comparison operator> Number2 ? <Return_this_if_true> : <Return_this_if_false>
Suppose we have to find minimum of n1 and n2 using ternary operator. int n1 = 67; int n2 = 34;
int maxOfTwo =  n1 > n2 ?  n1 : n2 ; // maxOfTwo  will store 67

Similarly for minimum finding, just reverse the operator operation
 int minOfTwo =  n1 <  n2  ? n1 : n2 ; // minOfTwo  will store 34

Now we will extend above concept to find maximum of three numbers: - 
int n1= 67, n2 =34, n3 = 134;
int maxOfThree = n1 > n2 ? (n1 > n3 ? n1 : n3) : (n2 >n3 ? n2 : n3)
When n1 > n2 is executed and outcome is true then  (n1 > n3 ? n1 : n3) will be executed else  (n2 >n3 ? n2 : n3) will be executed.Using (n1 > n3 ? n1 : n3)  we will get max of n1, n2 and n3 otherwise  (n2 >n3 ? n2 : n3) will give max of three.

Below sample program demonstrate how to find maximum and minimum of three numbers using ternary operator.
public class MaxAndMinOfThreeNoUsingTernary {

 public static void main(String[] args) {
  int n1= 67, n2 =34, n3 = 134;
  int maxOfThree = n1 > n2 ? (n1 > n3 ? n1 : n3) : (n2  <n3 ? n2 : n3);
  System.out.println("Max of three is: " + maxOfThree);
  
  int minOfThree = n1 < n2 ? (n1 < n3 ? n1 : n3) : (n2  <n3 ? n2 : n3);
  System.out.println("Min of three is: " + minOfThree);
  
 }

}
Sample output:-
Max of three is: 134
Min of three is: 34

Read also:- Java Interview questions series

1 Comments

Previous Post Next Post