Java ternary operator examples and problems to solve
- Categories Java, Java Operators, Operators
- Rewrite the following using ternary operator :
if(x%2 == 0)
c = ‘E’;
else
c = ‘O’;
Ans:
c = (x % 2 == 0) ? ‘E’ : ‘O’;
- Rewrite the following program segment using the if-else statements instead of the ternary operator.
String grade = (mark >= 90) ? “A” : (mark >= 80) ? “B” : “C”;
Ans.
String grade;
if(marks >= 90) {
grade = “A”;
} else if( marks >= 80 ) {
grade = “B”;
} else {
grade = “C”;
}
- Rewrite the following statements using ternary operator.
if(ch> “C”)
value = 200;
else
value =100;
Ans.
value = (ch> “C”) ? 200 : 100 ;
- What is output of the above program code?
class conditional{
public static void main(String args[ ]){
int i=20;
int j= 55;
int z= 0;
z= i < j ? i : j;
System.out.printin(“The final value assigned to z = ” + z);
}
}
Ans.
The final value assigned to z= 20
- Evaluate the value of n if the value of p=5 and q=19:
int n = (q-p)>(p-q)?(q-p):(p-q);
Ans.
n=14
Explanation:
p=5, q=16
n= (16-5) > (5-16)? (16-5) : (5-16)
= 11 > (-11) ? (14) : (-14) [(expression) ? expressionTrue : expressinFalse;]
n= 14 [as 11 is greater than (-11) so given expression is true.]
- What are the values of x and y when the following statements are executed?
int a = 63, b = 36;
boolean x = (a < b ) ? true : false;
int y= (a > b ) ? a : b;
Ans.
x=false y=63
- Rewrite the following using ternary operator:
if (bill >10000 )
discount = bill * 10.0/100;
else
discount = bill * 5.0/100;
Ans.
discount=(bill >10000 ) ? bill * 10.0/100: bill * 5.0/100;
- Rewrite the following program segment using the if ..else statement.
comm = (sale>15000)?sale*5/100:0;
Ans.
if (sale>15000)
comm=sale*5/100
else
comm=0;
- Rewrite the following statement using suitable ‘if()’ statement.
int ans = res > 365 ? 180/3:90/ 3;
Ans:
int ans;
if( res > 365)
ans= 180/3;
else
ans= 90/ 3;
- Rewrite the following statement using suitable ternary operator.
if(number > 0.0)
System.out.println(“positive”);
else
System.out.println(“not positive”);
Ans.
System.out.println( (number > 0.0) ? “positive” : “not positive”);
- What will be the output of the following code?
char x = ‘E’ ; int m;
m=(x==’e’) ? ‘E’ : ‘e’;
System.out.println(“m=”+m);
Ans.
m= 101