Next: The switch statement. Up: Bits and pieces. Previous: Parameters.


Conditional operator

Textbook: Section 7.3

I wanted to quickly tell you about this new operator, since the textbook has covered it by this point. It's called the conditional operator. (Sometimes it's called the ternary operator, because it is peculiar in that it actually works with three arguments. The other operators are all either binary (like *) or unary (like ++).)

The conditional operator gives you a way of putting an if-then-else into an expression.

IO.println(m > n ? m : n);
Both the question mark and the colon are parts of the conditional operator. The part before the question mark is the condition. The computer will evaluate this to see whether the condition is true or false. If it is true, the computer evaluates the expression between the question mark and the colon, and the result is the value of the overall conditional expression. If the condition is false, then the computer evaluates the expression after the colon, and the result is the value of the overall conditional expression.

So in the above line, the conditional expression is m if m exceeds n and n otherwise. In other words, this line will display the larger of m and n.

In the order of operations, the conditional operator ranks just above the assignment operator. Usually this is what you want, but it's good practice to use parentheses here even when you don't need them, to make things more readable.

int max = m > n ? m : n;   // UGLY: don't do this.
int max = (m > n ? m : n); // much better

The conditional operator is never necessary when you program, but it's occassionally convenient. But you should be aware that it's extremely controversial. Many people say it should be banned. But many others use it. So it's worth knowing about.


Next: The switch statement. Up: Bits and pieces. Previous: Parameters.