为什么我不能将 final long 分配给 int?
Why can't I assign a final long to an int?
据我了解,变量评估是在 运行 时间完成的。但是,类型评估是在编译时在 Java.
中完成的
此外,如我所见,将变量设置为常量(我使用的是局部变量,但它对上述概念没有任何改变),将在编译时使其值已知。
我提供了两个例子来验证这个概念。第一个有效,第二个无效。
有人可以向我解释为什么使变量常量允许我将 short 变量分配给 int 变量,而我不能将 int 变量分配给 long 吗?
// Working example
final int x = 10;
short y = x;
// Non-working example
final long a = 10L;
int b = a;
语言规范的相关部分是 JLS 5.2, Assignment Contexts:
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.
使 a
和 x
变量 final
使它们成为常量表达式(因为它们也是用常量值初始化的)。
第一个示例有效,因为 x
是一个常量 int
,您正试图将其分配给 short
变量,并且该值可以在 short
;第二个示例不是因为 x
是常量 long
,而您正试图将其分配给 int
变量(该值是可表示的,但这并不重要,因为它已经被取消隐式缩小转换的资格。
据我了解,变量评估是在 运行 时间完成的。但是,类型评估是在编译时在 Java.
中完成的此外,如我所见,将变量设置为常量(我使用的是局部变量,但它对上述概念没有任何改变),将在编译时使其值已知。
我提供了两个例子来验证这个概念。第一个有效,第二个无效。
有人可以向我解释为什么使变量常量允许我将 short 变量分配给 int 变量,而我不能将 int 变量分配给 long 吗?
// Working example
final int x = 10;
short y = x;
// Non-working example
final long a = 10L;
int b = a;
语言规范的相关部分是 JLS 5.2, Assignment Contexts:
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.
使 a
和 x
变量 final
使它们成为常量表达式(因为它们也是用常量值初始化的)。
第一个示例有效,因为 x
是一个常量 int
,您正试图将其分配给 short
变量,并且该值可以在 short
;第二个示例不是因为 x
是常量 long
,而您正试图将其分配给 int
变量(该值是可表示的,但这并不重要,因为它已经被取消隐式缩小转换的资格。