Java Reference
In-Depth Information
There are no automatic conversions from the numeric types to
char
or
boolean
. Also,
char
and
boolean
are not compatible with each other. However, an integer literal can be
assigned to
char
.
Casting Incompatible Types
Although the automatic type conversions are helpful, they will not fulfill all programming
needs because they apply only to widening conversions between compatible types. For all
other cases you must employ a cast. A cast is an instruction to the compiler to convert one
type into another. Thus, it requests an explicit type conversion. A cast has this general form:
(target-type) expression
Here,
target-type
specifies the desired type to convert the specified expression to. For ex-
ample, if you want to convert the type of the expression
x/y
to
int
, you can write
Here, even though
x
and
y
are of type
double
, the cast converts the outcome of the ex-
pression to
int
. The parentheses surrounding
x / y
are necessary. Otherwise, the cast to
int
would apply only to the
x
and not to the outcome of the division. The cast is necessary here
because there is no automatic conversion from
double
to
int
.
When a cast involves a
narrowing conversion
, information might be lost. For example,
when casting a
long
into a
short
, information will be lost if the
long
's value is greater than