在 Definite Assignment 上的 Java 语言规范一章中, Example 16-2说是
A Java compiler must produce a compile-time error for the code:
{ int k; int n = 5; if (n > 2) k = 3; System.out.println(k); /* k is not "definitely assigned" before this statement */ }
even though the value of n is known at compile time, and in principle it can be known at compile time that the assignment to k will always be executed (more properly, evaluated). A Java compiler must operate according to the rules laid out in this section. The rules recognize only constant expressions; in this example, the expression n > 2 is not a constant expression as defined in §15.28.
但是,如果我们看一下 §15.28,它是这样说的
the relational operators <, <=, >, and >=
可以贡献常量表达式。
表达式 n > 2
是否是常量表达式?我们如何确定这一点?
最佳答案
之所以这么说是因为n
不是 constant expression .
A constant expression is an expression denoting a value of primitive type or a
String
that does not complete abruptly and is composed using only the following:
- [...]
- Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).
和
A constant variable is a
final
variable of primitive type or typeString
that is initialized with a constant expression (§15.28).
n
不是 final
因此不是常量变量。因此它不是常量表达式。因此 n < 2
不是常量表达式。
关于java - 为什么 Java 语言规范说表达式 (n > 2) 不是常量表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34660442/