请原谅我的无知。我无法理解以下看似相似的代码行之间的区别。
final int num1 = 1;
final int num2;
num2 = 2;
是什么让 num2
不符合 switch case 常量的条件?
switch (expression) {
case num1:
System.out.println("Case A");
case num2:
System.out.println("Case B");
}
我们开始学习 Java 语言规范。 switch
语句的 case
标签定义为
SwitchLabel:
case ConstantExpression :
case EnumConstantName :
default :
您的 num
变量没有引用 enum
常量名称,所以让我们忽略它。什么是 ConstantExpressions
? JLS再次定义它
A compile-time 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:
- Literals of primitive type and literals of type String
- [...]
- Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).
因此原始 int
值 2
是一个常量表达式。你可以做
switch {
case 2:
}
现在我们想知道使用final
的关系和常量变量。
A blank final
is a final
variable whose declaration lacks an initializer.
[...]
A variable of primitive type or type String
, that is final
and
initialized with a compile-time constant expression (§15.28), is
called a constant variable.
所以最后一个引用是指一个非空白 final
变量,即。一个有初始化器的。
所以
final int num1 = 1;
是常量变量。
和
final int num2;
num2 = 2;
不是,因此不能在 case
标签中使用。