java - Why final byte variable cannot be converted to Integer during auto-boxing? -
there no error when try autobox i2
byte
,but when vise-versa(b1
integer
),then 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
can suggest read jls sec 5.2, linked in answer previous similar question.
assignment contexts allow use of 1 of 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 widening reference conversion
an unboxing conversion (§5.1.8) optionally followed widening primitive conversion.
...
in addition, if expression constant expression (§15.28) of type byte, short, char, or int:
- a narrowing primitive conversion may used if type of variable byte, short, or char, , value of constant expression representable in type of variable.
a narrowing primitive conversion followed boxing conversion may used if type of variable is:
- byte , value of constant expression representable in type byte.
- ...
taking cases in reverse order:
byte b3 = 1; int i3 = b3; // no error
assigning byte
int
widening conversion.
final int i2 = 1; byte b2 = i2;// no error
this same previous question: can assign constant-valued int
byte
, provided value of int
fits byte
.
final byte b1 = 1; integer i1 = b1; //error
you're trying widening primitive conversion, followed boxing conversion. that's not 1 of cases listed here, it's error.
you can fix explicit widening cast:
integer i1 = (int) b1; //ok
Comments
Post a Comment