Java allows implicit conversion of int to float. Why?

You are probably wondering:

Why is this an implicit conversion when there is a loss of information? Shouldn't this be an explicit conversion?

And you of course have a good point. But the language designers decided that if the target type has a range large enough then an implicit conversion is allowed, even though there may be a loss of precision. Note that it is the range that is important, not the precision. A float has a greater range than an int, so it is an implicit conversion.

The Java specification says the following:

A widening 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.

Tags:

Java