简体   繁体   English

在Java中为double变量赋值整数

[英]Assigning an integer literal to a double variable in Java

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? 因为0是一个整数文字,它使用32位,而d是一个使用64位的双变量,剩下的32位是用随机垃圾填充的,还是Java正确地提升了文字?

Java promotes it correctly, otherwise there'd be a rather large body of code that was problematic :-) Java正确地推广它,否则会有一大堆代码存在问题:-)

Section 5.1.2 of the Java language spec details this: Java语言规范的5.1.2节详细说明了这一点:

The following 19 specific conversions on primitive types are called the widening primitive conversions: 以下19种基本类型的特定转换称为扩展基元转换:

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; 实际上,从一个整数类型扩展到另一个整数类型以及从float到double的转换不会丢失任何信息; the numeric value is preserved exactly. 数值完全保留。 Conversions widening from float to double in strictfp expressions also preserve the numeric value exactly; 在strictfp表达式中从float扩展到double的转换也完全保留了数值; 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. 将int或long值转换为float,或将long值转换为double,可能会导致精度损失 - 也就是说,结果可能会丢失该值的一些最低有效位。 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. 在这种情况下,使用IEEE 754舍入到最接近模式,得到的浮点值将是整数值的正确舍入版本。

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. 从32位Java int转换为double (在Java中,具有50+位精度),不会失去幅度任何精度。 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. 如果由于其值而使用的常量被强制为long ,则可能会失去精度,因为long具有64位精度。

java automatically converts double to integer.ie upcast java自动将double转换为integer.ie upcast
so memory is automatically managed by jvm. 所以内存由jvm自动管理。
but it can not automatically cast double to integer ie.downcast. 但它不能自动将double转换为整数ie.downcast。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM