3

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.

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
CDVN
  • 171
  • 1
  • 1
  • 11
  • I selected Ted Hopp answer as it gives a little bit more clarity.. Thanks, but just to be clear is this called a nested ternary condition? – CDVN Jun 05 '15 at 11:43
  • I don't think there's a specific standard name for this construct, but, yes, "nested ternary operators" or similar language would be clear to most people. The idea is that the structure of the ternary operator — ` ? : ` — allows any expression after the `?` or the `:`, including other ternary operator expressions. – Ted Hopp Jun 05 '15 at 12:40

2 Answers2

4

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;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
4

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:

  • if (con1) and (con2) assign 1 to x
  • if (con1) and (not con2) assign 0 to x
  • otherwise assign 2 to x

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 ;
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521