...
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 previous definition) respectively. In the table, constant int
refers to constant expressions of type int
(such as '0'
or variables declared final
).
Rule | Operand 2 | Operand 3 | Resultant typeType |
---|---|---|---|
1 | type Type Ttype | Type T | type Type T |
2 |
|
|
|
3 |
|
|
|
4 |
|
|
|
5 |
|
|
|
6 |
|
|
|
7 |
|
|
|
8 |
|
|
|
9 |
|
|
|
10 | other Other numericother | Other numeric | promoted Promoted type of the 2nd and 3rd operands |
11 | T1 = boxing conversion(S1) | T2 = boxing conversion(S2) | apply 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.
...
In this noncompliant code example, the programmer expects that both print statements will print the value of alpha
as a char
—A
. The first print statement prints A
because the compiler applies the eighth rule 8 from the result type determination table to determine that the second and third operands of the conditional expression are, or are converted to, type char
. However, the second print statement prints 65
— the —the value of alpha
as an int
. The first matching rule from the table is the tenth rule 10. Consequently, the compiler promotes the value of alpha
to type int
.
Code Block | ||
---|---|---|
| ||
public class Expr { public static void main(String[] args) { char alpha = 'A'; int i = 0; /* otherOther code. Value of i may change */ boolean trueExp = ...; // some expression that evaluates to true System.out.print(trueExp ? alpha : 0); // prints A System.out.print(trueExp ? alpha : i); // prints 65 } } |
...
Bibliography
Puzzle 8: , "Dos Equis" | |
"Bx: Primitive value is unboxed and coerced for ternary operatorValue Is Unboxed and Coerced for Ternary Operator" | |
[JLS 2011] | §15.25, "Conditional Operator ? : " |
...