int
divided by an int
is an
int, and a double
divided by a double
is a double
, but
what about an int
divided by a double
or a double
divided by an
int
? When doing arithmetic on unlike types Java tends to widen
the types involved so as to avoid losing information. After all
3 * 54.2E18 will be a perfectly valid double
but much too big
for any int
.
The basic rule is that if either of the variables in a binary
operation (addition, multiplication, subtraction, addition,
remainder) are doubles then Java treats both values as doubles.
If neither value is a double
but one is a float
, then Java treats both
values as floats. If neither is a float or a double but one is a
long
, then Java treats both values as longs. Finally if
there are no doubles, floats or longs, then Java treats
both values as an int
, even if there aren't any ints in the
equation. Therefore the result will be a double
, float
, long
or int
depending on the types of the arguments.