Search code examples
javacastingimplicit-conversion

typecasting long to float implicitly not narrowing


In java the hierarchy for implicit conversion is byte -> short -> int -> long -> float -> double Long can hold 8 bytes of data. Then why it is implicitly typecasted to float which can hold only 4 bytes rather than double which can hold 8 bytes.Why it is not considered as narrowing ?

And which primitive types will be implicitly converted to char ?


Solution

  • It's not about how many bits of data are used. It's about the scale that can be represented.

    From JLS section 5.1.2 (widening primitive conversions):

    A widening primitive conversion does not lose information about the overall magnitude of a numeric value.

    ...

    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 (§4.2.4).

    The range of long is much smaller than the range of float, but with a fixed precision of 1. The precision of float varies across the range, in terms of absolute value. In other words, no long is outside the range of float, but there are long values which can't be precisely represented as float values.

    Moving to double wouldn't help this - there are long values which can't be precisely represented as double, either.