Incremental Java
Conditional Expression

Conditional Statements

So far, all of the conditional statements we've seen (if, if-else, and switch) are statements. They are not expressions.

You don't evaluate an if statement. You can't assign a variable to the evaluation of a switch statement.

These are all control-flow constructs. They control which statements are run and when.

(Assignment statements are ironically expressions, though one could argue that every expression is also a statement in Java).

Conditional Expression

There is an exception. The conditional expression. The syntax is particularly unusual. Almost every operator has either one or two operands. This is the only operator in Java with three operands.
 cond ? exprtrue : exprfalse 
This is called the conditional expression or the question mark-colon operator.

The two expressions, exprtrue, exprfalse should evaluate to the same type.

Semantics

  1. Evaluate the condition, cond.
  2. If cond evaluates to true, then evaluate exprtrue. That's the final result of the evaluation.
  3. If cond evaluates to false, then evaluate exprfalse. That's the final result of the evaluation.
Only one of exprtrue or exprfalse is evaluated.

One major difference between method calls and operators is that method calls always evaluate each argument. However, an expression with operators may not always evaluate each operand (an operand is basically an argument). In particular, &&, ||, and the conditional expression do not always evaluate each operand. (Recall && and || short circuits depending on the evaluation of the left operand, which may cause the right operand to be unevaluated).

Example

Here's an example that computes the absolute value of x.
  public int absVal( int x )
  {
     return x > 0 ? x : -x ;
  }
This checks to see if x is positive. If so, it evaluates x and returns it. If false, it evaluates -x and returns that. This negates a negative number (or zero), and evaluates to a positive number (or zero).

Notice at most one of the two expressions, x and -x, is evaluated. Both expressions are never evaluated.

Good or Bad?

Some people find the question mark-colon operator too obscure. Few people have seen it, and few use it. Others argue that it's quite cool, and should be used as much as is reasonable. I'm in the second camp, even though I would say I rarely use it myself.

Oh, you can also nest the operators, though it's a bit awkward looking. That is, exprtrue and exprfalse can themselves be conditional expressions, if you want. This may require parentheses to avoid problems with precedence.