What is the data type of x + y?
double x = 39.21;
float y = 2.1;
Explanation:
This is actually a trick question, as this code will not compile! As you may remember from Chapter 1, floating-point literals are assumed to be double, unless postfixed with an f, as in 2.1f. If the value was set properly to 2.1f, then the promotion would be similar to the last example, with both operands being promoted to a double, and the result would be a double value.
But I don't understand. If float y = 2.1; was assumed to be double there would be no need for the promotion of variable y to the double. And I'm more confused by the next problem, which is:
What is the data type of x * y / z?
short x = 14; float y = 13; double z = 30;
书上说这甚至可以编译 float y = 13;不是 float y = 13f。如果 float 是十进制,我是否只在 float 旁边添加 f ?我真的看不出这个问题和上述问题之间的区别。
最佳答案
忽略 char
,Java 将提升数字类型,如下所示:
byte > short > int > long > float > double
这些称为扩大转换。参见 JLS §5.1.2. Widening Primitive Conversion详细信息。
二元运算符将提升为int
、long
、float
或double
,以最接近的为准运算符的两个值,即结果永远不会是 byte
或 short
。示例:byte + Short
会将两边提升为 int
。参见 JLS §5.6.2. Binary Numeric Promotion详细信息。
赋值运算符还将对值进行加宽转换,并附加一条规则,即 byte
类型的常量表达式,short
或 int
将经过 narrowing conversion如果变量的类型是byte
或short
,并且常量表达式的值可以用该类型表示。请注意,没有将 double 常量缩小为 float 的规则。参见 JLS §5.2. Assignment Contexts详细信息。
所以,对于你的代码:
double x = 39.21; // double constant to double (identity conversion)
float y = 2.1; // fails because double constant cannot promote to float
如果代码已编译,x + y
的数据类型是什么?
x + y // double + float promotes to double
答案:双
下一部分:
short x = 14; // narrowing conversion of int constant to short
float y = 13; // widening conversion of int constant to float
double z = 30; // widening conversion of int constant to double
现在,x * y/z
的数据类型是什么?
x * y // short * float promotes to float
(x * y) / z // (float) / double promotes to double
答案:双
关于java - 需要帮助来理解为什么这段代码无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44058168/