Java Reference
In-Depth Information
In all, seven different kinds of conversions might apply when an expres-
sion is evaluated:
•
Widening or narrowing primitive conversions
•
Widening or narrowing reference conversions
•
Boxing or unboxing conversions
•
String conversions
You have previously seen all of these. There are then five different con-
texts in which these conversions might be applied, but only some con-
versions apply in any given context:
•
Assignment
This occurs when assigning the value of an expres-
sion to a variable and can involve the following: a widening
primitive conversion; a widening reference conversion; a boxing
conversion optionally followed by a widening reference conver-
sion; or an unboxing conversion optionally followed by a widening
primitive conversion.
If the resulting expression is of type
byte
,
char
,
short
, or
int
, and
is a constant expression, then a narrowing primitive conversion
can be applied if the variable is of type
byte
,
short
, or
char
and the
value will fit in that typefor example, the assignment of the
int
literal 27 to a
short
variable that we saw previously. If the type of
the variable is
Byte
,
Short
, or
Character
, then after the narrowing
primitive conversion a boxing conversion can be applied:
Short s1 = 27; // implicit int to short to
Short
•
Method invocation
This occurs when the type of an expression be-
ing passed as an argument to a method invocation is checked.
Basically, the same conversions apply here as they do for as-
signment, with the exception that the narrowing primitive con-
versions are not applied. This means, for example, that a method
expecting a
short
parameter will not accept the argument 27 be-