Java Reference
In-Depth Information
cause it is of type
int
an explicit cast must be used. This restric-
tion makes it easier to determine which method to invoke when
overloaded forms of it existfor example, if you try to pass a
short
to a method that could take an
int
or a
byte
, should the
short
get
widened to an
int
, or narrowed to a
byte
?
•
Numeric promotion
Numeric promotion, as discussed in
Section
expression are of the appropriate type by performing widening
primitive conversions, preceded if necessary by unboxing conver-
sions.
•
Casts
Casts potentially allow for any of the conversions, but may
fail at runtimethis is discussed in the next section.
•
String conversions
String conversions occur when the string con-
further in "
String Conversions
" on page
220
.
9.4.2. Explicit Type Casts
When one type cannot be assigned to another type with implicit conver-
sion, often it can be explicitly
cast
to the other typeusually to perform a
narrowing conversion. A cast requests a new value of a new type that is
the best available representation of the old value in the old type. Some
casts are not allowedfor example, a
boolean
cannot be cast to an
int
but
explicit casting can be used to assign a
double
to a
long
, as in this code:
double d = 7.99;
long l = (long) d;
When a floating-point value is cast to an integer, the fractional part is
lost by rounding toward zero; for instance,
(int)-72.3
is
-72
. Methods
available in the
Math
and
StrictMath
classes round floating-point values
to integers in other ways. See "
Math and StrictMath
"
on page
657
for
details. A floating-point NaN becomes the integer zero when cast. Val-