Java Reference
In-Depth Information
front of the value to be converted. For example, to convert
money
to an integer
value, we could put a cast in front of it:
dollars = (
int
) money;
The cast returns the value in
money
, truncating any fractional part. If
money
contained the value
84.69
, then after the assignment,
dollars
would contain
the value
84
. Note, however, that the cast does not change the value in
money
.
After the assignment operation is complete,
money
still contains the value
84.69
.
Casts are helpful in many situations where we need to treat a value tem-
porarily as another type. For example, if we want to divide the integer value
total
by the integer value
count
and get a floating point result, we could do
it as follows:
result = (
float
) total / count;
First, the cast operator returns a floating point version of the value in
total
.
This operation does not change the value in
total
. Then,
count
is treated as a
floating point value via arithmetic promotion. Now the division operator will per-
form floating point division and produce the intended result. If the cast had not
been included, the operation would have performed integer division and truncated
the answer before assigning it to
result
. Also note that because the cast operator
has a higher precedence than the division operator, the cast operates on the value
of
total
, not on the result of the division.
SELF-REVIEW QUESTIONS
(see answers in Appendix N)
SR 2.31
Why are widening conversions safer than narrowing conversions?
SR 2.32
Identify each of the following conversions as either a widening conver-
sion or a narrowing conversion.
a.
int
to
long
b.
int
to
byte
c.
byte
to
short
d.
byte
to
char
e.
short
to
double
SR 2.33
Assuming
result
is a
float
variable and
value
is an
int
variable,
what type of variable will
value
be after the following assignment
statement is executed? Explain.
result = value;
Search WWH ::
Custom Search