Wrong type in Java conditional assignment

前端 未结 2 1880
再見小時候
再見小時候 2020-12-30 02:38

In the following code I have two identical conditional assignment operations, one returns an object of type Double, and the second returns the String \"Integer\".

         


        
2条回答
  •  心在旅途
    2020-12-30 03:03

    Well, that is because of the JLS specs for the conditional operator:

    Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:

    • ...
    • Otherwise, 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.

    Numeric promotion is defined here in §5.6.2. It says:

    Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

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

提交回复
热议问题