gpt4 book ai didi

Java 文字值赋值行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:53:29 24 4
gpt4 key购买 nike

在 Kathy Sierra 的 SCJP 指南一书中,在作业一章中,我们了解到我们可以声明这样的东西 byte b = 7;。幕后代码是 byte b = (byte) 7;。之所以如此,是因为在 Java 中,数字 7 被视为文字 int 值,因此必须转换为 int。

现在其他情况。 Double 可以包括 float 值中包含的每个字节,因为它是更大的数据类型。那么我们可以说 float f = 10.543; 因为 10.543 是一个很小的值,应该适合一个 float 。此类数字的字面值也被视为 Double,因此编译器应将其隐式转换为 float 。但事实并非如此,编译器阻止了我们。我们必须在该值之后附加 Ff

为什么字面值赋值会出现这两种相互冲突的行为?简而言之,如果 byte b = 7 是可能的。为什么 float f = 10.543 不可能?

最佳答案

您可以阅读 JLS 5.2 Assignment Conversion

The compile-time narrowing of constants means that code such as:

 byte theAnswer = 42;

is allowed. Without the narrowing, the fact that the integer literal 42 has type int would mean that a cast to byte would be required:

byte theAnswer = (byte)42;  // cast is permitted but not required

If the type of the expression cannot be converted to the type of the variable by a conversion permitted in an assignment context, then a compile-time error occurs.

If the type of the variable is float or double, then value set conversion (§5.1.13) is applied to the value v

JLS #3.10.2.Floating-Point Literals

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d

5.1.2. Widening Primitive Conversion

A narrowing primitive conversion from double to float is governed by the IEEE 754 rounding rules (§4.2.4). This conversion can lose precision, but also lose range, resulting in a float zero from a nonzero double and a float infinity from a finite double. A double NaN is converted to a float NaN and a double infinity is converted to the same-signed float infinity.

我希望以上能澄清你的疑问。

关于Java 文字值赋值行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12419509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com