10

Please demonstrate how the ternary operator works with a regular if/else block. Example:

Boolean isValueBig = value > 100 ? true : false; 

Exact Duplicate: How do I use the ternary operator?

11
  • should "Java", "C" and a lot of other language be added as well? Since they all support the ternary operator pretty much the same way. Commented Jan 20, 2009 at 21:22
  • Not to be too picky but "(condition) ? :" is a conditional expression in the form of a ternary operator. It is in the form of a ternary operator because it takes 3 arguments. Commented Jan 20, 2009 at 21:26
  • This is valid use of the ternary operator, but a less-than-stellar-example, because the conditional-expression itself is boolean. Testing it to resolve to true/false is kinda redundant. This would be best written as: Boolean isValueBig = (value > 100); Commented Jan 20, 2009 at 21:30
  • That is a bad example of as it could more easily have been written as IsValueBig = value > 100; No need to assign bools based on an evaluation of a bool. Commented Jan 20, 2009 at 21:36
  • 1
    Duplicate of: stackoverflow.com/questions/392932/…. Commented Jan 20, 2009 at 21:51

13 Answers 13

30
Boolean isValueBig = ( value > 100 ) ? true : false; // above line is same as: Boolean isValueBig; if( value > 100 ) { isValueBig = true; } else { isValueBig = false; } 
Sign up to request clarification or add additional context in comments.

2 Comments

Or maybe Boolean isValueBig = (( value > 100 ) ? true : false) ? true : false; to make it even more boolean – i.o.w. this is a very pointless (though correct) use of the ternary operator.
actually, in reality I'd hope you'd just use isValueBig = ( value > 100 ) ; it work the same :P
16

The difference between the ternary operation and if/else is that the ternary expression is a statement that evaluates to a value, while if/else is not.

To use your example, changing from the use of a ternary expression to if/else you could use this statement:

Boolean isValueBig = null; if(value > 100) { isValueBig = true } else { isValueBig = false; } 

In this case, though, your statement is equivalent to this:

Boolean isValueBig = (value > 100); 

1 Comment

"The ternary expression is a statement", the ternary expression is a expression, it expresses a value, if/else is a statement, ternary could become an expression statement but I would say by itself it is an expression, this is what makes turnery pretty powerful in my opinion.
10

When I was new to C++, I found that it helped to read this construct as follows:

Boolean isValueBig = if condition ? then x else: y; 

(Notice that this isn't valid code. It's just what I trained myself to read in my head.)

Comments

6
Boolean isValueBig; if (value > 100) { isValueBig = true; } else { isValueBig = false; } 

Comments

6

I was never a fan of the ternary operator because I thought it was hard to read. As it so happens, Jon Skeet and his book, C# in Depth finally hit this old dog over the head and got it to sink in. Jon said, and I paraphrase, think of it as a question.

value > 100?

"yes" : "no"

Now the blind can see.

Hope this helps you make it second nature.

Comments

5
Boolean isValueBig; if(value > 100) { isValueBig = true; } else { isValueBig = false; } 

Comments

4

As quoted from the ?: Operator MSDN page, "the conditional operator (?:) returns one of two values depending on the value of a Boolean expression."

So you can use the ternary operator to return more than just booleans:

 string result = (value > 100 ) ? "value is big" : "value is small"; 

Comments

2

PHP Example

<?php // Example usage for: Ternary Operator $action = (empty($_POST['action'])) ? 'default' : $_POST['action']; // The above is identical to this if/else statement if (empty($_POST['action'])) { $action = 'default'; } else { $action = $_POST['action']; } ?> 

"The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE."

PHP Documentation on Comparison Operators

1 Comment

You are welcome. I'm pleased to see how quickly you got responses - I love StackOverflow!
2

Make sure you don't mix types in true/false parts in Java. It produces weird results :-(

1 Comment

I agree, although explicit casts should handle it in most cases, but it looks so ugly.
2

Bad example, because you could easily write

Boolean isValueBig = value > 100 ? true : false; 

as:

bool isValueBig = value > 100 

Beyond that, everyone else has already answered it. I would just not recommend using ternary operators to set bool values, since what you are evaluating is already a boolean value.

I realize it was just an example, but it was worth pointing out.

Comments

1

Others have answered it already but here's one thing you should really know about ternary's usage and by that I mean don't ever do it.

Lets assume that you have a piece of code which is supposed to return a different object for each possible variation of some value, lets say for simpliticy's sake an integer between 1 and 5. Your code looks like this:

if(i==1) { return new ObjectOne(); } else if(i==2) { return new ObjectTwo(); } else if(i==3) { return new ObjectThree(); } else if(i==4) { return new ObjectFour(); } else if(i==5) { return new ObjectFive(); } else { return new DefaultObject(); } 

It's easy to understand but a bit heavy. Since ternary is just another way of writing an if..else statement that can be refactored to this

return (i==1) ? new ObjectOne() : (i==2) ? new ObjectTwo() : (i==3) ? new ObjectThree() : (i==4) ? new ObjectFour() : (i==5) ? new ObjectFive() : new DefaultObject(); 

It's called nested ternary. It's evil, now that you know about it please never use it. It may seem to have its uses like the case above but it's very likely that in real life situations you would need to use it somewhere where it loses readability (think altering configurations with variable amount of parameters and such).

Bonus sector: Never set attribute values inside if(), just look at this: if(bool=true!=false) { .. }

1 Comment

Ternary is sugar anyway, and we know what sugar does to our teeth. Sugar is evil!
0

As quoted from MSDN (noted in a previous post)

string result = (value > 100 ) ? "value is big" : "value is small";

Could be read as:

Is value greater than 100? If yes, string result is "value is big", if no, string result is "value is small".

Comments

-1

the ternary operator comes from functional paradigm. To prove this makes a example in smlnj :

fun ternary(cond, trueVal, falseVal) = if cond then trueVal else falseVal;

1 Comment

Please read How to Answer. In particular, please make sure to address the question being asked. This looks like a comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.