据我了解,变量评估是在运行时完成的。但是,在 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 - 为什么我不能将 final long 分配给 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56561628/