Table of Contents

About

The ternary is a:

Many people call it the ternary operator, because it's the only ternary (three operand) operator in many language.

The first expression must be of type boolean or Boolean, or a compile-time error occurs.

Ternary means that the number of argument (arity) of this operator is three. See Arity

Syntax

The conditional operator has three operand expressions:

firstBooleanOperand ? SecondOperand : ThirdOperand

where:

  • the first operand expression must be of type boolean or Boolean
  • the second or the third operand expression must not be an invocation of a void method.

At run time, the first operand expression of the conditional expression is evaluated first. The resulting boolean value is then used to choose either the second or the third operand expression:

  • If the value of the first operand is true, then the second operand expression is chosen.
  • If the value of the first operand is false, then the third operand expression is chosen.

Example:

String myName = mustBeShortName ? getShortName() : getLongName();

Associativity

The conditional operator is syntactically right-associative (it groups right-to-left).

a?b:c?d:e?f:g

means the same as

a?b:(c?d:(e?f:g))

Specification

Documentation / Reference