Java Reference
In-Depth Information
It may well be that the default treatment of mixed expressions listed in the preceding section is not what you
want. For example, suppose you have defined a
double
variable
result
, and two variables,
three
and
two
,
of type
int
with the values 3 and 2 respectively. If you compute the value of
result
with the statement
result = 1.5 + three/two;
the value stored is 2.5, because
three/two
is executed as an integer operation and produces the result 1.
You may have wanted the term
three/two
to produce the value 1.5 so the overall result would be 3.0. You
could do this using an explicit cast:
result = 1.5 + (double)three/two;
This causes the value stored in
three
to be converted to type
double
before the divide operation takes
place. Then rule 1 applies for the divide operation, and the operand
two
is also converted to type
double
before the divide operation is executed. Hence, the value of
result
in this case is 3.0.
NOTE
You can cast a value from any primitive type to any other, but you need to take care
that you don't unintentionally lose information when you do so. Obviously casting from one
integer type to another with a more limited range has the potential for losing information, as
does casting any floating-point value to an integer. Casting from type
double
to type
float
can also produce an effective infinity when the original value is greater than the maximum
value for a value of type
float
.
Automatic Type Conversions in Assignments
When the type of the result of an arithmetic expression on the right of an assignment operator differs from
the type of the variable on the left, an automatic cast is applied to the result as long as there is no possibility
of losing information. If you think of the basic types that you have seen so far as being in the sequence
byte
⇒
short
⇒
int
⇒
long
⇒
float
⇒
double
then an automatic conversion is made as long as it is upward through the sequence of types — that is, from
left to right. If you want to go in the opposite direction, from type
double
to type
float
or
long
, for ex-
ample, then you must insert an explicit cast into your code for the result of the expression on the right of the
assignment operator.
THE OP= OPERATORS
The
op=
operators are used in statements of the form
lhs op= rhs;
where
op
can be any of the arithmetic operators (
+
,
-
,
*
,
/
,
%
). It also works with some other operators you
haven't seen yet. The preceding statement is basically a shorthand representation of this statement: