为什么下面的方法有效
float f = 10l // OK 32 bits to 64 ?
float 只有 32 位,long 为 64 位,因此 long 中没有 float 的空间
而这个没有
long l = 10f //compile error
有人可以向我解释一下选角是如何进行的吗?
最佳答案
从long
到float
的转换是特别允许由JLS, Section 5.1.2进行赋值的。 :
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
还有
A widening primitive conversion from int to float, or from long to float, or from long 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).
因此,值的范围已被覆盖,但可能会损失精度。这是允许的,也是预期的。
另一行:
long l = 10f;
是primitive narrowing conversion ,其中 JLS, Section 5.2 "Assignment Contexts" ,并没有明确允许:
Assignment contexts allow the use of one of the following:
an identity conversion (§5.1.1)
a widening primitive conversion (§5.1.2)
a widening reference conversion (§5.1.5)
a boxing conversion (§5.1.7) optionally followed by a widening reference conversion
an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
请注意,显式强制转换将允许缩小原始转换范围。
long l = (long) 10f; // Compiles
关于java - Java 中的原始转换和赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26046571/