我想知道方法add()中的2个声明之间的区别,如下所示.
final int c;
c = 20;
和
final int c = 20;
我认为两者都是最终变量,我无法重新分配任何新值.以下是以不同方式处理上述声明的方法.
void add() {
final int a = 30;
final int b = 10;
final int c;
c = 20;
switch (a) {
case b + c:
System.out.println("In case b+c");
break;
default:
break;
}
}
抱怨,上面的方法根本没有编译
constant expression required case b+c
如果变量c在一行中声明并初始化,如final int c = 30;.有用.
解决方法:
JLS #4.12.4将常量变量定义为(强调我的):
A variable of primitive type or type String, that is final and initialized with a compile-time constant expression, is called a constant variable.
在你的情况下,最终int c = 20;是一个常量变量但是最终的int c; c = 20;不是.
标签:java,final,switch-statement,java-7
来源: https://codeday.me/bug/20190722/1506905.html