First off, I came across this question recently and haven't being able to find a good explanation for it:
int x = (30 > 15)?(14 > 4) ? 1 : 0 : 2;
I have used ternary expression before so I am familiar with them, to be honest I don't even know what to call this expression... I think that it breaks down like this
if (con1) or (con2) return 1 // if one is correct
if (!con1) and (!con2) return 0 // if none are correct
if (con1) not (con2) return 2 // if one but not the other
Like I said I don't really know so I could be a million miles away.
Because of operator precedence in Java, this code:
int x = (30 > 15)?(14 > 4) ? 1 : 0 : 2;
will be parsed as if it were parenthesized as follows:
int x = (30 > 15) ? ((14 > 4) ? 1 : 0) : 2;
(The only operators with lower precedence than ternary ?: are the various assignment operators: =, +=, etc.) Your code can be expressed verbally as:
EDIT: Nested ternary operators are often formatted in a special way to make the whole thing easier to read, particularly when they are more than two deep:
int x = condition_1 ? value_1 :
condition_2 ? value_2 :
.
.
.
condition_n ? value_n :
defaultValue; // for when all conditions are false
This doesn't work quite as cleanly if you want to use a ternary expression for one of the '?' parts. It's common to reverse the sense of a condition to keep the nesting in the ':' parts, but sometimes you need nesting in both branches. Thus, your example declaration could be rewritten as:
int x = (30 <= 15) ? 2 :
(14 > 4) ? 1 :
0 ;
It's int x = (30 > 15)?((14 > 4) ? 1 : 0): 2; :
if (30 > 15) {
if (14 > 4)
x = 1;
else
x = 0;
} else {
x = 2;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With