I was preparing for the SCJP using K & B SCJP 1.5 Certification textbook. Page 184 in Chapter 3 states the following:
double d = 100L; // Implicit cast
In the preceding statement, a double is initialized with a long value (as denoted by
the L after the numeric value). No cast is needed in this case because a double can
hold every piece of information that a long can store.
I wrote the following snippet to test this assertion using an implicit cast from "long" to "double":
I got the follwing output after successfully compiling the program.
This converts to 9,223,372,036,854,776,000. Obviously, the binary number above doesn't end in three zeros. It appears that the "double" value has lost precision. I don't know if this is an automatic rounding error in the System.out.println() method, or whether the double has indeed lost precision. How can a 64-bit "long" fit into a 64-bit "double" that has a mantissa and exponent?
No cast is needed in this case because a double can hold every piece of information that a long can store.
This statement isn't really true. Java will allow the implicit cast because the range of a long is smaller than (and within) the range of a double. Some precision will be lost, but precision lost is allowed for an implicit cast.
Which is odd because the compiler complains about a "possible loss of precision" when trying to implicitly convert a long to an int, yet this exact same possible loss of permission is allowed when converting from a long to a float or double.
They really should change that error message: "possible range violation" seems better.