next up previous
Next: Note on comparisons: equality Up: Unit 05 Previous: Eliminating the disjunction operator

Conditional expression

Java is equipped with a selection operator that allows us to construct a conditional expression. The use of a conditional expression can in some cases simplify the code with respect to the use of an if-else statement.


Conditional expression

Syntax:

condition ? expression-1 : expression-2

Semantics:

Evaluate condition. If the result is true, then evaluate expression-1 and return its value, otherwise evaluate expression-2 and return its value.

Example:

System.out.println("bigger value = " + (a > b)? a : b);

The statement in the example, which makes use of a conditional expression, is equivalent to:

if (a > b)
  System.out.println("bigger value = " + a);
else
  System.out.println("bigger value = " + b);

Note that the selection operator is similar to the if-else statement, but it works at a different syntactic level:


next up previous
Next: Note on comparisons: equality Up: Unit 05 Previous: Eliminating the disjunction operator