Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Widening and autoboxing conversion issue

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:

  1. Narrowing conversion first from 10 to short.
  2. short would then widen to int.
  3. int would then autobox to Integer.

Instead it's a compilation error.

Example 2:

Short x = 10;
Integer y = x;

This fail too.

like image 858
yapkm01 Avatar asked Jan 13 '23 19:01

yapkm01


1 Answers

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;
like image 175
rgettman Avatar answered Jan 17 '23 06:01

rgettman