Java Reference
In-Depth Information
the value stored will be 2.5, since
three/two
will be executed as an integer operation and will produce
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
double
before the divide operation takes
place. Then rule 1 applies for the divide operation, and the operand
two
is also converted to
double
before the divide is executed. Hence the value of
result
will be 3.0.
You can cast any of the basic types to any other, but you need to take care that you
don't lose information when you do so. Obviously casting from a larger integer type to
a smaller has the potential for losing information, as does casting any floating point
value to an integer. Casting from
double
to
float
can also produce effective infinity
when the original value is greater than the maximum value for a
float
.
Casting in Assignments
When the type of the result of an expression on the right of an assignment statement differs from the
type of the variable on the left, an automatic cast will be applied as long as there is no possibility of
losing information. If you think of the basic types that we have seen so far as being in the sequence:
byte
short
int
long
float
double
then an automatic conversion will be made as long as it is upwards through the sequence, that is, from
left to right. If you want to go in the opposite direction, from
double
to
float
or
long
, for example,
then you must use an explicit cast.
The op= Operators
The
op=
operators are used in statements of the form:
lhs op= rhs;
where
op
can be any of the operators
+
,
-
,
*
,
/
,
%
, plus some others you haven't seen yet. The above is
basically a shorthand representation of the statement:
lhs = lhs op (rhs);
The right hand side is in brackets because it is worked out first - then the result is combined with the
left hand side using the operation,
op
. Let's look at a few examples of this to make sure it's clear. To
increment an
int
variable
count
by 5 you can write:
count += 5;