JAVA program to find maximum between three numbers using ternary operator
In this JAVA program we find maximum between three numbers using ternary operator. For eg 11,21,12 the maximum of these numbers is 21.
So 21 should be as output.
Ternary operator :- condition?true:false
For eg a<b?System.out.println(a):System.out.println(b)
Logic
Ternary Operator is used in the following way condition?true:false.
Dry Run of the Program
We have taken 3 integer variables a,b and c.
Let us say a=11 , b=21,c=12
temp = a>b?a:b; i.e. temp = a(11)>b(21) ? a(11):b(21)
As a is less than b, hence it is false and b is stored in temp variable;
max = temp>b?temp:b;
max = temp(21)>c(12) ? temp(21):c(12)
As temp is greater than c , hence it is true and temp is stored in max variable;
So then we print the output as maximum is 21.
Program
import java.util.*; class maxTernary { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the first no"); int a = sc.nextInt(); System.out.println("Enter the second no"); int b = sc.nextInt(); System.out.println("Enter the third no"); int c = sc.nextInt(); int max,temp; temp = a>b?a:b; max = temp>b?temp:b; System.out.println("Maximum of the three numbers is "+max); } }