java - Java 中的原始转换和赋值

标签 java casting primitive

为什么下面的方法有效

float f = 10l // OK  32 bits to 64 ?

float 只有 32 位,long 为 64 位,因此 long 中没有 float 的空间

而这个没有

long l = 10f    //compile error 

有人可以向我解释一下选角是如何进行的吗?

最佳答案

longfloat的转换是特别允许由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/

相关文章:

c# - 显式地将基类转换为派生类

java - switch 语句中使用的 char 数组

java - 在Junit中的afterclass中添加代码

java - 将用 C 编写的 CRC 8 函数转换为 Java

c++ - 警告 : ISO C++ forbids variable length array

我可以将变量转换为在 C 中执行期间决定的类型吗

java - 数组的 ArrayList 每次都会被覆盖

java - 从 Android 中的链接问题启动应用程序

javascript - 为什么闭包编译器偏爱 !0 而不是 true?

Java 数组列表 : Adding primitive type or its wrapper-class: What's the difference?