...
Determining the Result Type of a Conditional Expression
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 second and third operands |
11 | T1 = boxing conversion(S1) | T2 = boxing conversion(S2) | Apply capture conversion to lub(T1,T2) |
The complexity of the rules that determine the result type of a conditional expression can lead to unintended type conversions. Consequently, the second and third operands of each conditional expression should have identical types. This recommendation also applies to boxed primitives.
...
Automated detection of condition expressions whose second and third operands are of different types is straightforward.
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Parasoft Jtest |
| CERT.EXP55.COMT | Avoid using the conditional operator with mismatched numeric types |
Bibliography
Puzzle 8, "Dos Equis" | |
"Bx: Primitive Value Is Unboxed and Coerced for Ternary Operator" | |
[JLS 2013] | §15.25, "Conditional Operator ? : " |
...
...