Java Reference
In-Depth Information
a language construct known as a
cast
. Perform a cast by placing the name of the
desired type in parentheses before the value to be converted. For example:
int
i
=
13
;
byte
b
=
(
byte
)
i
;
// Force the int to be converted to a byte
i
=
(
int
)
13.456
;
// Force this double literal to the int 13
Casts of primitive types are most often used to convert floating-point values to inte‐
gers. When you do this, the fractional part of the floating-point value is simply trun‐
cated (i.e., the floating-point value is rounded toward zero, not toward the nearest
integer). The static methods
Math.round()
,
Math.floor()
, and
Math.ceil()
per‐
form other types of rounding.
a
x
The
char
type acts like an integer type in most ways, so a
char
value can be used
anywhere an
int
or
long
value is required. Recall, however, that the
char
type is
unsigned
, so it behaves differently than the
short
type, even though both are 16 bits
wide:
short
s
=
(
short
)
0xffff
;
// These bits represent the number -1
char
c
=
'\uffff'
;
// The same bits, as a Unicode character
int
i1
=
s
;
// Converting the short to an int yields -1
int
i2
=
c
;
// Converting the char to an int yields 65535
Table 2-3
shows which primitive types can be converted to which other types and
how the conversion is performed. The letter N in the table means that the conver‐
sion cannot be performed. The letter Y means that the conversion is a widening
conversion and is therefore performed automatically and implicitly by Java. The let‐
ter C means that the conversion is a narrowing conversion and requires an explicit
cast.
Finally, the notation Y* means that the conversion is an automatic widening conver‐
sion, but that some of the least significant digits of the value may be lost in the con‐
version. This can happen when converting an
int
or
long
to a floating-point type—
see the table for details. The floating-point types have a larger range than the integer
types, so any
int
or
long
can be represented by a
float
or
double
. However, the
floating-point types are approximations of numbers and cannot always hold as
many significant digits as the integer types (see
Chapter 9
for some more detail
about floating-point numbers).
Table 2-3. Java primitive type conversions
Convert to:
Convert from:
boolean byteshortcharintlongfloatdouble
-
N
N
N
N
N
N
N
boolean
N
-
Y
C
Y
Y
Y
Y
byte
N
C
-
C
Y
Y
Y
Y
short