The conditional operator ?:
uses the boolean
value of its first operand to decide which of the other two expressions will be evaluated (see JLS Section 15.25, "Conditional Operator ? :
".)
The general form of a Java conditional expression is operand1 ? operand2 : operand3
.
- If the value of the first operand (
operand1
) istrue
, then the second operand expression (operand2
) is chosen. - If the value of the first operand is
false
, then the third operand expression (operand3
) is chosen.
The conditional operator is syntactically right-associative; for example, a?b:c?d:e?f:g
is equivalent to a?b:(c?d:(e?f:g))
.
The JLS-defined rules for determining the type of the result of a conditional expression (tabulated below) are complicated; programmers could be surprised by the type conversions required for expressions they have written.
Result type determination begins from the top of the table; the compiler applies the first matching rule. The "Operand 2" and "Operand 3" columns refer to operand2
and operand3
(from the above definition), respectively. In the table, constant int
refers to constant expressions of type int
(such as '0' or variables declared final
).
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
EXP12-J |
low |
unlikely |
medium |
P2 |
L3 |
Automated Detection
Automated detection of condition expressions whose second and third operands are of different types is straightforward.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Bibliography
[[Bloch 2005]] Puzzle 8: Dos Equis
[[Findbugs 2008]] "Bx: Primitive value is unboxed and coerced for ternary operator"
[[JLS 2005]] Section 15.25, "Conditional Operator ? :
"