Section 5.2 of the JLS covers the types of conversions that are allowed in assignment contexts.
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
Additionally,
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.
Short and the value of the constant expression is representable in the type short.
Character and the value of the constant expression is representable in the type char.
Byte b = 10
compiles ok because 10
is a constant expression and is representable as a byte
.
Byte b = new Byte(10)
won't compile because 10
is an int
literal, and method invocation conversion won't perform primitive narrowing conversions. To get this call to a Byte
constructor to compile, you can explicitly cast 10
to byte
:
Byte b = new Byte( (byte) 10);
Long l = new Long(10)
compiles because method invocation conversion will perform primitive widening conversions, including from int
to long
.
Long l = 10
won't compile, because Java will not specifically allow a widening conversion followed by a boxing conversion, as I discussed in a recent answer. To get this to compile, you can use a long
literal, so only boxing is necessary.
Long l = 10L;
new Byte(int)
won't compile? Because there is no constructor in the classByte
that except integer values as an argument. The compiler could also cast an integer argument, but no one implemented this feature yet. Whynew Long(10)
compiles? Because there is a suitable constructor available that excepts integer arguments. To assign long values you should write anl
behind the number:Long l = 10L
. – Individualism