“Wrong” return type when using if vs. ternary opertator in Java

Basically it’s following the rules of section 15.25 of the JLS, specifically:

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.

So section 5.6.2 is followed, which will basically involves unboxing – so this makes your expression work as if longValue and doubleValue were of types long and double respectively, and the widening promotion is applied to the long to get an overall result type of double.

That double is then boxed in order to return an Object from the method.

Leave a Comment