The
a ? b : c syntax denotes a single operator, also known as the conditional operator (or the ternary operator, because it is the only operator in
Java that takes three operands). It first evaluates the boolean expression before the
?. If the expression evaluates to true, it evaluates the expression after the
?. Otherwise it evaluates the expression after the
:.
It helps when we break the condition up in separate statements:
First we evaluate
luck > 10. Because
luck is 10, the condition is false and we evaluate the expression after the
: which is
--luck. So
luck is decremented by one, and because we used the prefix decrement operator, the value 9 is assigned to the
intermediateResult variable.
The
intermediateResult is less than 10, so we print
"Shark". After decrementing
luck it is also less than 10, so we print
"Bear".
This code was designed to be tricky. In general, don't use the ternary operator or the increment, decrement or assignment operators inside larger expressions.