Why final byte variable cannot be converted to Integer during auto-boxing?

220 Views Asked by At

There is no error when I try to autobox i2 to Byte,but when I do vise-versa(b1 to Integer),then an error occurs.

        final byte b1 = 1;
        Integer i1 = b1; //error

        final int i2 = 1;
        Byte b2 = i2;// no error

        byte b3 = 1;
        int i3 = b3; // no error
1

There are 1 best solutions below

0
On

Can I suggest that you read JLS Sec 5.2, that I linked in my answer to your previous similar question.

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.

...

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

  • A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:

    • Byte and the value of the constant expression is representable in the type byte.
    • ...

Taking your cases in reverse order:

    byte b3 = 1;
    int i3 = b3; // no error

Assigning a byte to an int is simply a widening conversion.

    final int i2 = 1;
    Byte b2 = i2;// no error

This is exactly the same as your previous question: you can assign a constant-valued int to a Byte, provided the value of that int fits into a byte.

    final byte b1 = 1;
    Integer i1 = b1; //error

You're trying to do a widening primitive conversion, followed by a boxing conversion. That's not one of the cases listed here, so it's an error.

You can fix this with an explicit widening cast:

    Integer i1 = (int) b1; //ok