I am mystified by the behavior of the Java compiler when assigning primitives to wrapper class references. Please see the code below. The lines with comments don\'t compile.
Let's look at the types of conversions allowed in an assignment context.
Principally:
Assignment contexts allow the use of one of the following:
an identity conversion
a widening primitive conversion
a widening reference conversion
a boxing conversion optionally followed by a widening reference conversion
an unboxing conversion optionally followed by a widening primitive conversion.
(Note my emphasis on one.)
Most of your examples that do not compile, for example
Integer s11 = (short)7;
require a widening primitive conversion followed by a boxing conversion. This is not a permitted conversion.
But then you might wonder why the following example does compile:
Byte s9 = (short)7;
This is a narrowing primitive conversion followed by a boxing conversion.
This is a special case:
In addition, if the expression is a constant expression of type
byte
,short
,char
, orint
[...] 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 typebyte
.
Short
and the value of the constant expression is representable in the typeshort
.
Character
and the value of the constant expression is representable in the typechar
.
This special case is necessary because there is no way to express an integer literal of a type narrower than int
.