Considering this code snippet:
int i = 0;
double d1 = (double) i;
long l = 0L;
double d2 = (double) l;
Running this on my machine prints 0.0 for both conversions. But can d1 and d2 ever be anything but 0.0?
As I understand, this is a widening primitive conversion to which the spec says:
A widening primitive conversion does not lose information about the
overall magnitude of a numeric value.
as well as
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
As I understand the spec, the above would mean that int 0 will always become double 0.0 but long 0 can be converted to something else (e.g. 1E-20 or something like that). Is my spec interpretation correct?
The full quote is:
(Emphasis mine)
This is covering the case where the
int/longvalue cannot be exactly represented infloat/double(in which case, the nearest representable value is chosen). Clearly,0can be represented, so one would not expect a loss of precision.