I\'m preparing for Java 7 certification and have the following question.
Byte b = 10
compiles ok. Looks like the compiler is narrowing int 10 to byte 10
The basic rules are:
These rules explain why Long l = 10
doesn't work, as well as new Byte(10)
. The first would require the int literal 10 to be widened to a long
and then be boxed, which isn't allowed. (More precisely, it would require a conversion from int
to Long
, which JLS 5.1.7 doesn't define.) The second would require the int literal 10 to be implicitly narrowed to a byte
, which isn't allowed.
But there are exceptions to the rule. Byte b = 10
is explicitly allowed by JLS 5.2:
In addition, if the expression is a constant expression (§15.28) 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
.
(some irrelevant parts omitted)
Lastly, new Long(10)
works because the int literal 10 can be automatically widened to a long 10L.