java - 需要帮助来理解为什么这段代码无法编译

标签 java syntax type-conversion operands

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详细信息。

二元运算符将提升为intlongfloatdouble,以最接近的为准运算符的两个值,即结果永远不会是 byteshort。示例:byte + Short 会将两边提升为 int。参见 JLS §5.6.2. Binary Numeric Promotion详细信息。

赋值运算符还将对值进行加宽转换,并附加一条规则,即 byte 类型的常量表达式shortint 将经过 narrowing conversion如果变量的类型是byteshort,并且常量表达式的值可以用该类型表示。请注意,没有将 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/

相关文章:

java - 为什么我需要向 Java 接口(interface)添加方法,以便在 Junit 单元测试中访问它?

java - Alfresco 5.0 : AuthenticationUtils. startSession 生成 404

Markdown 表语法的正则表达式?

java - 机器人 : if(); do not caused any prohibition

c# - 无法将 IQueryable<> 转换为 IOrderedQueryable 错误

java - 如何在Java中设置Grpc连接最大限制?

java - 无法从 Azure api 管理中的开发人员门户访问新的 api 服务

syntax - 如何在~/.lldbinit中编写多行宏?

c# - 如何使用空检查优化一系列 as-operations?

c++ - 将 vector 值复制到 char*