Every time I think I understand about casting and conversions, I find another strange behavior.
long l = 123456789L;
float f = l;
System.out.println(f); // outputs 1.23456792E8
Given that a long has greater bit-depth than a float, I would expect that an explicit cast would be required in order for this to compile. And not surprisingly, we see that we have lost precision in the result.
Why is a cast not required here?
The same question could be asked of
longtodouble– both conversions may lose information.Section 5.1.2 of the Java Language Specification says:
In other words even though you may lose information, you know that the value will still be in the overall range of the target type.
The choice could certainly have been made to require all implicit conversions to lose no information at all – so
intandlongtofloatwould have been explicit andlongtodoublewould have been explicit. (inttodoubleis okay; adoublehas enough precision to accurately represent allintvalues.)In some cases that would have been useful – in some cases not. Language design is about compromise; you can’t win ’em all. I’m not sure what decision I’d have made…