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 ? :
".)
...
Operand 2 | Operand 3 | Resultant type |
---|---|---|
type T | type T | type T |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
other numeric | other numeric | promoted type of the 2nd and 3rd operands |
T1 = boxing conversion (S1) | T2 = boxing conversion(S2) | apply capture conversion to lub(T1,T2) |
See JLS , Section 5.1.7, "Boxing Conversion"; JLS , Section 5.1.10, "Capture Conversion"; and JLS , Section 15.12.2.7, "Inferring Type Arguments Based on Actual Arguments" 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 indeed prints A
, because the compiler applies the eighth rule in from the result type determination table above 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 value of alpha
as an int
. The first matching rule from the table above is the tenth rule; consequently, the compiler promotes the value of alpha
to type int
.
...