0

Long have 8 bytes in Java. Float have 4 bytes

Why I can do:

    long a = Long.MAX_VALUE;
    float b = a;

Instead of:

long a = Long.MAX_VALUE;
float b = (float) a;

The result is:

9223372036854775807 <-- LONG 9223372036854776000,000000 <-- float

So why If I lost precision I dont have to say explicite cast '(float)' ?

Thomas Banderas
  • 1,681
  • 1
  • 21
  • 43
  • 3
    [JLS-5.1.2. Widening Primitive Conversion](https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.2) - *19 specific conversions on primitive types are called the widening primitive conversions:* among them *`long` to `float` or `double`* – Elliott Frisch Jul 13 '19 at 12:06
  • Note that even for long to double, you still lose precision, even though both are 64 bit (if the long exceeds 2^53) – Andy Turner Jul 13 '19 at 12:10
  • That JLS section even makes a point of saying: “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…” – VGR Jul 13 '19 at 12:10

0 Answers0