Ternary operator

前端 未结 5 1632
野性不改
野性不改 2020-12-19 08:44

Why the output of following code is 9.0 and not 9 ? If ternary operator is nothing but short form of if-else branch then why java compiler is promoting int to double ?

5条回答
  •  时光说笑
    2020-12-19 09:29

    Actually the ternary operator is not strictly speaking a short form of if/else as it does perform type conversion if required. In particular, in your case, JLS 15.25 requires that:

    binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.

    If you follow the link to §5.6.2:

    If either operand is of type double, the other is converted to double.

提交回复
热议问题