我明白为什么以下是错误的:
byte a = 3;
byte b = 8;
byte c = a + b; // compile error
它不会编译。表达式总是产生 int
。所以我们应该进行显式转换:
byte c = (byte) (a + b); // valid code
但是我不明白为什么以下是正确的:
byte d = 3 + 8; // it's valid! why?
因为文字整数(例如 3 或 8)总是隐含的 int
。而 int-or-smaller
表达式也总是会产生一个 int
。谁能解释这里发生了什么?
我唯一能猜到的是编译器将此表达式等同于以下内容:
byte d = 11;
并且不认为这是一个表达式。
最佳答案
这 less† 与 3 + 8
在编译时是否被评估为 11
以及 更多 与编译器被明确允许在某些情况下将 int
s 隐式缩小到 byte
s 的事实有关。特别是,语言规范明确允许在编译时将 int
类型的常量表达式隐式缩小转换为 byte
,这些表达式可以适合 byte
.
JLS here is section §5.2: 的相关部分
In addition, if the expression is a constant expression (§15.28) of type
byte
,short
,char
, orint
:
- A narrowing primitive conversion may be used if the type of the variable is
byte
,short
, orchar
, and the value of the constant expression is representable in the type of the variable.The compile-time narrowing of constants means that code such as:
byte theAnswer = 42;
is allowed. Without the narrowing, the fact that the integer literal42
has typeint
would mean that a cast tobyte
would be required:
†:显然,根据规范,需要评估常量表达式以查看它是否适合更窄的类型。 但重点是,如果没有这部分规范,编译器将不允许进行隐式缩小转换。
让我们在这里说清楚:
byte a = 3;
byte b = 8;
允许这些的原因是规范的上述部分。也就是说,允许编译器将文字 3
隐式缩小转换为 byte
。这不是因为编译器在编译时将常量表达式 3
计算为其值 3
。
关于java - Java 中的原始类型转换和赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17110918/