# Mock question

Anonymous
Ranch Hand
Posts: 18944
Hi!
I don�t understand this question:
10. Select the equivalent answer for the code given below?
boolean b = true;
if ( b ) {
x = y;
} else {
x = z;
}
A) x = b ? x = y : x = z ;
B) x = b ? y : z ;
C) b = x ? y : z ;
D) b = x ? x = y : x = z ;
The answer is B but why x = b??? I think that the correct answer will be (x == true) ? y : z;

Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
Hi jordi,
The ternary operator x=(a?b:c) allows to replace an if-else statement of this form:
if(a)
x=b
else
x=c
Thus, a has to be a boolean expression.
B is the correct answer because b is a boolean expression and x gets assigned y if b is true and z otherwise.
In this example b is true since it is declared and initialized as such at the top of the code...
Hope that helps
Val

leena rane
Ranch Hand
Posts: 280
Hi Jordi,
x = b ? y : z ;
consider only this:
b ? y : z
means if b is true - y
else - z
now
x = b ? y : z ;
means if b is true - x=y
else - x=z
I think i have not made it very clear.
Ask if u still have doubt.

Anonymous
Ranch Hand
Posts: 18944
Thank you, I understand now