Assigning an integer literal to a double variable

2019-01-26 14:43发布

问题:

If I do the following

double d = 0;

since 0 is an integer literal, which uses 32 bits, and d is a double variable that uses 64 bits, will the remaining 32 bits be filled with random garbage, or does Java promote the literal correctly?

回答1:

Java promotes it correctly, otherwise there'd be a rather large body of code that was problematic :-)

Section 5.1.2 of the Java language spec details this:

The following 19 specific conversions on primitive types are called the widening primitive conversions:

byte to short, int, long, float, or double
short to int, long, float, or double
char to int, long, float, or double
int to long, float, or double
long to float or double
float to double 

Widening primitive conversions do not lose information about the overall magnitude of a numeric value. Indeed, conversions widening from an integral type to another integral type and from float to double do not lose any information at all; the numeric value is preserved exactly. Conversions widening from float to double in strictfp expressions also preserve the numeric value exactly; however, such conversions that are not strictfp may lose information about the overall magnitude of the converted value.

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.

Converting from a 32-bit Java int to a double (which, in Java, has 50+ bits of precision), will not lose the magnitude or any precision. If the constant you use is forced to a long due to its value, you may lose precision, since a long has 64 bits of precision.



回答2:

java automatically converts double to integer.ie upcast
so memory is automatically managed by jvm.
but it can not automatically cast double to integer ie.downcast.