Conditional ternary operations

First, I recently stumbled across this question and could not find a good explanation for this:

int x = (30 > 15)?(14 > 4) ? 1 : 0 : 2; 

      

I have used ternary expression before so that I am familiar with them, to be honest, I don't even know what to call this expression ... I think it breaks 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

      

As I said, I really don't know, so I might be a million miles away.

+3


source to share


2 answers


Due to operator precedence in Java , this code:

int x = (30 > 15)?(14 > 4) ? 1 : 0 : 2;

      

will be parsed as if it were enclosed in parentheses like this:

int x = (30 > 15) ? ((14 > 4) ? 1 : 0) : 2;

      

(The only operators with a lower priority than the triple ?:

are different assignment operators: =

, +=

etc). Your code can be expressed orally as:



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

EDIT. Nested ternary operators are often formatted in a special way to make things easier to read, especially 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

      

It's not that clean if you want to use a ternary expression for one of the <<26> parts. It is common to change the meaning of the condition to keep nesting in " :

" parts , but sometimes you want to nest in both branches. Thus, your example declaration could be rewritten as:

int x = (30 <= 15) ? 2 :
        (14 > 4)   ? 1 :
                     0 ;

      

+4


source


This is int x = (30 > 15)?((14 > 4) ? 1 : 0): 2;

:



if (30 > 15) {
    if (14 > 4) 
        x = 1;
    else 
        x = 0;
} else {
    x = 2;
}

      

+4


source







All Articles