posted 22 years ago
Perhaps this might help in explaining how a long value can be assigned to a float variable:
The ascii figure below depicts the widening conversions of primitives in Java. Note that intermediate datatypes can be skipped in the widening effort. For example, a short can be converted to a long without first converting to an int. Any widening conversion can occur without an explicit cast.
<pre>
byte --> short --> int --> long --> float --> double
^
| *this figure is inspired by Fig 3.1,
char------/ pg 44, Mughal & Rasmussen, "A
Programmer's Guide to Java(tm)
Certification", 2000.
</pre>
Java considers a conversion from a long to a float (or double) as a widening conversion. One may consider this unintuitive, since a long has a bit-depth of 64, and a float has a bit-depth of 32, as pointed out in a previous post. However, Java allows such a conversion, and the result is a possible loss of accuracy (inherent in floating-point numbers) in the resulting float.
On the other side of the coin, if a conversion is not a widening conversion, it is always a narrowing conversion (requiring explicit casts), which seems intuitive until the issue of converting chars to bytes and shorts (and vice-versa) comes to mind. Conversions between these three types are considered narrowing conversions, and, again, explicit casts are needed.
I hope this enlightens (and I hope this is 100% correct!).
[edited to correct ascii art!]
[This message has been edited by Ted Schrader (edited October 10, 2001).]
[This message has been edited by Ted Schrader (edited October 10, 2001).]