TROUBLE WITH TERNARY TESTER

ben reitman

Total Post:96

Points:676
Posted by  ben reitman
Java 
 717  View(s)
Ratings:
Rate this:
Could someone please help me make sense of this ternary operator. I checked the web and couldn't find any examples to clear it up for me. All the examples I saw included only one boolean expression followed by expression1 : expression 2. 

  int x = 5;
   System.out.println(x > 2 ? x < 4 ? 10 : 8 :7);
}}

It looks like it is ( booleanExpression ? booleanExpression ? not sure here : expression1 : expression2 ) 
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Trouble with ternary tester

     the ternary syntax is: 


    booleanExpression ? value if true : value if false; 


    which is shorthand for an if statement 


    if (booleanExpression){
      value = valueIfTrue;
    } else {
      value = valueIfFalse;
    }


    In this example it looks like their "value if true" expression is itself a ternary expression. 
    I'll add some brackets to make it obvious how it is evaluating: 

    x > 2 ?  (x < 4 ? 10 : 8) :7


    i.e. the equivalent of a nested if/else statement 


    int answer;
    if (x > 2){
      if (x<4) {
        answer = 10;
      } else {
        answer = 8;
      }
    } else {
      answer = 7;
    }


    Of course if I ever saw anybody actually WRITING code like this, I would probably (not so) politely suggest that they rewrite their code to make it more readable

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!