Language - Conditional operator (ternary)
Table of Contents
1 - About
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.
2 - Articles Related
3 - Syntax
The conditional operator has three operand expressions:
firstBooleanOperand ? SecondOperand : ThirdOperand
- 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.
String myName = mustBeShortName ? getShortName() : getLongName();
4 - Associativity
The conditional operator is syntactically right-associative (it groups right-to-left).
means the same as