Java文字值赋值行为 [英] Java literal value assignment behaviour
问题描述
在Kathy Sierra的SCJP指南中,在作业章节中,我们了解到我们可以声明类似 byte b = 7;
的内容。在场景后面,代码是 byte b =(byte)7;
。这是因为在java中,数字7被认为是文字int值,因此必须转换为int。
In the book of SCJP guide by Kathy Sierra, in the assignments chapter, we learn that we can declare something like this byte b = 7;
. Behind the scene the code is byte b = (byte) 7;
. This is so because in java, number 7 is considered a literal int value so has be to cast to int.
现在是其他情况。 Double可以包含float值中包含的每个字节,因为它是一个更大的数据类型。所以我们可以说 float f = 10.543;
因为10.543是一个很小的值,应该适合浮点数。此类数字的字面值也被视为Double,因此编译器应隐式将其强制转换为float。但事实并非如此,编译器阻止了我们。我们必须在该值之后附加 F
或 f
。
Now other situation. Double can include every byte contained within a float value as it is a bigger datatype. So can we say float f = 10.543;
As 10.543 is quite a small value and should fit within a float. Also literal value for such number is considered a Double so compiler should implicitly cast it to float. But it's not so, compiler stops us. We have to append an F
or f
after that value.
为什么这两个冲突行为存在字面值赋值?简而言之,如果字节b = 7
是可能的。为什么浮动f = 10.543
不可能?
Why are these two conflicting behaviour there for literal value assignment? In short if byte b = 7
is possible. Why is float f = 10.543
not possible?
推荐答案
你可以阅读 JLS 5.2分配转换
常量的编译时缩小意味着代码如:
The compile-time narrowing of constants means that code such as:
byte theAnswer = 42;
是允许的。如果没有缩小,整数文字42具有int类型的事实意味着需要转换为字节:
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.
如果变量的类型是float或double,然后将值集转换(第5.113节)应用于值v
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
浮点文字的类型为float,如果后缀为ASCII字母F或f;否则它的类型是双重的,它可以选择带有ASCII字母D或d
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
从double到float的缩小原语转换由IEEE 754舍入规则控制(§4.2.4 )。这种转换可能会失去精度,但也会失去范围,导致从非零双精度浮点零和从有限双精度浮点无穷大。双NaN转换为浮动NaN,双无穷大转换为相同符号的浮点无穷大。
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文字值赋值行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!