The conditional operator ?:
uses the boolean
value of its first operand to decide which of the other two expressions will be evaluated. (See §15.25, "Conditional Operator ? :
," of the Java Language Specification [JLS 20052011].)
The general form of a Java conditional expression is operand1 ? operand2 : operand3
.
...
Rule | Operand 2 | Operand 3 | Resultant type |
---|---|---|---|
1 | type T | type T | type T |
2 |
|
|
|
3 |
|
|
|
4 |
|
|
|
5 |
|
|
|
6 |
|
|
|
7 |
|
|
|
8 |
|
|
|
9 |
|
|
|
10 | other numeric | other numeric | promoted type of the 2nd and 3rd operands |
11 | T1 = boxing conversion(S1) | T2 = boxing conversion(S2) | apply capture conversion to lub(T1,T2) |
See §5.1.7, "Boxing Conversion", "§5.1.10, "Capture Conversion," and §15.12.2.7, "Inferring Type Arguments Based on Actual Arguments," of the Java Language Specification for additional information on the final table entry.
...
Writing the conditional expression as ((i & 1) == 0) ? (short) (i-1)) : workingVal
also complies with this guideline because both the second and third operands in this form have type short
. However, this alternative is less efficient because it forces unboxing of workingVal
on each even iteration of the loop and autoboxing of the result of the conditional expression (from short
to Short
) on every iteration of the loop.
...
Applicability
When the second and third operands of a conditional expression have different types, they can be subject to unexpected type conversions.
...
Guideline
...
Severity
...
Likelihood
...
Remediation Cost
...
Priority
...
Level
...
EXP55-JG
...
low
...
unlikely
...
medium
...
P2
...
Automated
...
Automated detection of condition expressions whose second and third operands are of different types is straightforward.
...
Puzzle 8: Dos Equis | |
"Bx: Primitive value is unboxed and coerced for ternary operator" | |
§15.25, "Conditional Operator ? : " |
...