For all the numeric primitive types, when you downcast a number (in this case from long to float) it looses its actual value. In this case you are assigning value contained in long ( 64 bit ) number to a float (32 bit )variable. So the last 32 bits are lost and thats why it allows you to downcast in case of numeric types without an explicit cast.
However that is not the case when you assign number to char variable.
i.e int i = 10; char c = (char) i; // will allow char c = i; // will give compilation error
Thanks and Regards,<br />Dhaval Shah<br />SCJP 1.4<br />SCWCD 1.4
float stores numbers in a completely different way than long. The type float can store all the numbers that are in the range of long, but with limited precision.
Converting a long to a float is a widening primitive conversion, so that no cast is necessary.
The Java Language Specification says, in section 5.1.2:
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).
Originally posted by dhaval shah: For all the numeric primitive types, when you downcast a number (in this case from long to float) it looses its actual value. In this case you are assigning value contained in long ( 64 bit ) number to a float (32 bit )variable.
This is not really correct in this case; a float stores numbers in the single-precision IEEE 754 format, while a long stores numbers in two's complement format.
In the conversion from long to float, it is not so that simply the lower 32 bits are discarded. Converting a long to a float is more complicated than that. But you do loose precision.
So the last 32 bits are lost and thats why it allows you to downcast in case of numeric types without an explicit cast.
This is not correct at all. Narrowing primitive conversions (from a larger to a smaller number of bits) normally require a cast, precisely because bits are thrown away. Only widening primitive conversions do not require a cast, because the original value will fit in the result without throwing away bits. [ September 19, 2007: Message edited by: Jesper Young ]