Arithmetic Promotion and Binary Operations

An 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.


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified February 3, 1999