Sunday, June 13, 2010

[TF005] Widening primitive conversion doesn't lose any information (true/false?)

(true/false?) The reason why Java doesn't let you assign a double value to a long variable without an explicit narrowing conversion is because some information may be lost during the conversion. Conversely, the reason why Java lets you assign a long value to a double variable without an explicit widening conversion is because no information is ever lost during the conversion.


double d = 604444444444444444L; // implicit widening conversion
// prints 6.0444444444444442E17

This is cautioned in JLS 5.1.2 Widening Primitive Conversion:
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.
Recall that Long.SIZE == 64 and Float.SIZE == 32, and yet going from long to float is in fact a widening conversion. The words "widening/narrowing" here has nothing to do with bit size and/or information capacity at all.

Thus, the following two claims are both false!!!
  • A widening conversion goes from a smaller to a larger data type in terms of bits
  • ... and thus no information is ever lost

And by the way, yes, that's a World Cup reference. No, I don't watch soccer.

No comments:

Post a Comment