Page 164 - ComputerScience_Class_11
P. 164
4. int x = 90;
char c = (x<=90)? 'Z': 'I';
Ans. Z
5. int 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)
c = a*b;
else
c = a-b;
2. result = (marks > 40)? "pass" : "fail";
if(marks>40)
result = "pass";
else
result = "fail";
3. System.out.println((sal<=10000)? 0.25*sal : 0.03*sal);
if(sal<=10000)
System.out.println(0.25 * sal);
else
System.out.println(0.03 * sal);
162 Touchpad Computer Science (Ver. 3.0)-XI

