java 中的推广和转化
Promotion and conversion in java
提升意味着将较小的类型文字提升或转换为更高的类型。此提升用于评估表达式。现在我对此有疑问。当我键入此语句时
byte var1 = 56 + 10;
给出答案66,这怎么可能?
根据提升规则,每个byte、short和char都被提升为int。所以这个 56 和 10 将被提升为 int,因此答案 66 将是 int。然后将这个 66 存储在字节类型的变量中。然而,要存储从 int 到 byte 的内容,需要进行转换。但是此代码无需强制转换即可完美运行。
在许多情况下,这可以在 Java Language Specification § 5.2:
中找到
In addition, if the expression is a constant expression (§15.28) of type byte
, short
, char
, or int
:
- A narrowing primitive conversion may be used if the variable is of type
byte
, short
, or char
, and the value of the constant expression is representable in the type of the variable.
这意味着编译器首先扩大到 int
然后缩小到目标类型,因为 66 在目标类型(字节)中确实是可表示的。
请注意,这仅适用于 constant 表达式。例如,以下代码会产生编译时错误:
static int get() {
return 10;
}
public static final main(String[] args) {
byte var1 = 56 + get();
}
这没关系,因为您给出的是恒定值。参见 compile-time narrowing of constants。
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
提升意味着将较小的类型文字提升或转换为更高的类型。此提升用于评估表达式。现在我对此有疑问。当我键入此语句时
byte var1 = 56 + 10;
给出答案66,这怎么可能? 根据提升规则,每个byte、short和char都被提升为int。所以这个 56 和 10 将被提升为 int,因此答案 66 将是 int。然后将这个 66 存储在字节类型的变量中。然而,要存储从 int 到 byte 的内容,需要进行转换。但是此代码无需强制转换即可完美运行。
在许多情况下,这可以在 Java Language Specification § 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 variable is of type
byte
,short
, orchar
, and the value of the constant expression is representable in the type of the variable.
这意味着编译器首先扩大到 int
然后缩小到目标类型,因为 66 在目标类型(字节)中确实是可表示的。
请注意,这仅适用于 constant 表达式。例如,以下代码会产生编译时错误:
static int get() {
return 10;
}
public static final main(String[] args) {
byte var1 = 56 + get();
}
这没关系,因为您给出的是恒定值。参见 compile-time narrowing of constants。
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