Why does Java implicitly (without cast) convert a `long` to a `float`?

The same question could be asked of long to double – both conversions may lose information.

Section 5.1.2 of the Java Language Specification says:

Widening primitive conversions do not
lose information about the overall
magnitude of a numeric value. Indeed,
conversions widening from an integral
type to another integral type do not
lose any information at all; the
numeric value is preserved exactly.
Conversions widening from float to
double in strictfp expressions also
preserve the numeric value exactly;
however, such conversions that are not
strictfp may lose information about
the overall magnitude of the converted
value.

Conversion of an int or a long value
to float, or of a long value to
double, may result in loss of
precision-that is, the result may lose
some of the least significant bits of
the value. In this case, the resulting
floating-point value will be a
correctly rounded version of the
integer value, using IEEE 754
round-to-nearest mode (ยง4.2.4).

In other words even though you may lose information, you know that the value will still be in the overall range of the target type.

The choice could certainly have been made to require all implicit conversions to lose no information at all – so int and long to float would have been explicit and long to double would have been explicit. (int to double is okay; a double has enough precision to accurately represent all int values.)

In some cases that would have been useful – in some cases not. Language design is about compromise; you can’t win ’em all. I’m not sure what decision I’d have made…

Leave a Comment