final variable case in switch statement(switch 语句中的最终变量大小写)
问题描述
final int a = 1;
final int b;
b = 2;
final int x = 0;
switch (x) {
case a:break; // ok
case b:break; // compiler error: Constant expression required
}
/* COMPILER RESULT:
constant expression required
case b:break;
^
1 error
*/
为什么会出现这种错误?如果我做了 final int b = 2
,一切正常.
Why am I getting this sort of error? If I would have done final int b = 2
, everything works.
推荐答案
b
可能没有被初始化,可能被分配了多个值.在您的示例中,它显然已初始化,但编译器可能不知道(而且它不能).想象一下:
b
may not have been initialized and it is possible to be assigned multiple values. In your example it is obviously initialized, but probably the compiler doesn't get to know that (and it can't). Imagine:
final int b;
if (something) {
b = 1;
} else {
b = 2;
}
编译器在switch
中需要一个常量,但是b
的值取决于一些外部变量.
The compiler needs a constant in the switch
, but the value of b
depends on some external variable.
这篇关于switch 语句中的最终变量大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:switch 语句中的最终变量大小写


- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01