Page 150 - Cs_withBlue_J_C11_Flipbook
P. 150
The operator evaluates the test condition first and then the expression based on the result of the condition. If the
condition results in true, expression1 will be evaluated and if the condition returns false, expression2 will be evaluated.
Some solved examples:
1. int a = 5, b = 6, large;
large = (a > b)? a : b;
Ans. large = 6
2. double d1 = 10.5, d2 = 5.5, small;
small = (d1 + d2 > 0)? d1 : d2;
Ans. small = 10.5;
3. int c = (3 < 4)? 3 * 4 : 3 + 4;
Ans. 12
4. int x = 90;
char c = (x<=90)? ‘Z’: ‘I’;
Ans. Z
5. c = (val + 550 < 1700)? 200 : 400;
if: (a) val = 1000 (b) val = 1500
Ans. (a) 200 (b) 400
Nested Conditional Assignment Operator
When a Conditional Assignment Operator is used under another, it is known as a nested Conditional Assignment
Operator.
Example: Suppose, we want to find the largest value out of three given numbers.
int m=5, n=6, o=4, large;
large=(m>n)? ((m>o)? m:n) : ( (n>o)? n:o);
Here,
m>n – first test condition is checked
m>o – second test condition is checked if the first condition is true
n>o – third test condition is checked if the first condition is false
Some Solved Examples:
1. int c=(5>4)? ((2==4)? 5 : 4) : 6+5;
Ans. 4
2. int a=18, b=44, c=25;
int d=(a>b)?( (a>c)? a : c) : ((b>c)? b : c);
Ans. 44
Conditional Operator as a Replacement of if-else
In Java, the conditional or ternary operator can be used to replace if-else. Let us understand this with the help of some
examples.
Some Solved Examples of Conversion of Ternary Operator to if-else:
1. c = (a>b)? a : (a==b)? a*b : a-b;
if(a>b)
c = a;
else
if(a==b)
148148 Touchpad Computer Science-XI

