Java: Widening and autoboxing conversion issue
java, type-conversion
Solution
According to the JLS, Section 5.2, which deals with assignment conversion:
Assignment contexts allow the use of one of the following:
an identity conversion (§5.1.1)
a widening primitive conversion (§5.1.2)
a widening reference conversion (§5.1.5)
a boxing conversion (§5.1.7) optionally followed by a widening reference conversion
an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
It is unable to apply two conversions at once (widening primitive conversion and boxing conversion); only one conversion can apply here, so it has to result in an error.
The solution would be to cast the `short` back to an `int` (a casting conversion), which would allow the assignment conversion to be a boxing conversion:
Integer i = (int) (short) 10;
(Or here, don't cast it to `short` in the first place.)
Integer i = 10;
Problem
I don't get why java doesn't do the widening and then autoboxing. ``` Integer i = (short) 10; ``` I would think the following would take place: - Narrowing conversion first from `10` to `short`. - `short` would then widen to `int`. - `int` would then autobox to `Integer`. Instead it's a compilation error. Example 2: Short x = 10; Integer y = x; This fail too.