Home > DeveloperSection > Forums > Trouble with ternary tester
ben reitman
ben reitman

Total Post:96

Points:676
Posted on    April-28-2015 12:30 AM

 Java Java 
Ratings:


 1 Reply(s)
 437  View(s)
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 ) 


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    April-28-2015 7:21 AM

 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


Don't want to miss updates? Please click the below button!

Follow MindStick