Java Reference
In-Depth Information
An example of such an illegal chain would be:
Integer, Comparable<Integer>, Comparable, Comparable<String>
The first three elements of the chain are related by widening reference conversion,
while the last entry is derived from its predecessor by unchecked conversion.
However, this is not a valid assignment conversion, because the chain contains two
parameterized types,
Comparable<Integer>
and
Comparable<String>
, that are not subtypes.
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
.
The compile-time narrowing of constants means that code such as:
byte theAnswer = 42;
is allowed. Without the narrowing, the fact that the integer literal
42
has type
int
would mean that a cast to
byte
would be required:
byte theAnswer = (byte)42; // cast is permitted but not required
A value of the null type (the null reference is the only such value) may be assigned to any
reference type, resulting in a null reference of that type.
If the type of the expression cannot be converted to the type of the variable by a conversion
permitted in an assignment context, then a compile-time error occurs.
If the type of an expression can be converted to the type of a variable by assignment con-
version, we say the expression (or its value) is
assignable to
the variable or, equivalently,
that the type of the expression is
assignment compatible with
the type of the variable.
If the type of the variable is
float
or
double
, then value set conversion (§
5.1.13
)
is applied to
the value
v
that is the result of the type conversion: