java switch 语句中的最终变量 case

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16255270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:25:18  来源:igfitidea点击:

final variable case in switch statement

javaswitch-statementcasefinal

提问by Furlando

        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
        */

Why am I getting this sort of error? If I would have done final int b = 2, everything works.

为什么我会收到这种错误?如果我做了final int b = 2,一切正常。

采纳答案by Bozho

bmay 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:

b可能尚未初始化,并且可以分配多个值。在您的示例中,它显然已初始化,但编译器可能不知道(并且不能)。想象:

final int b;
if (something) {
   b = 1;
} else {
   b = 2;
}

The compiler needs a constant in the switch, but the value of bdepends on some external variable.

编译器在 中需要一个常量switch,但 的值b取决于一些外部变量。

回答by Rahul Bobhate

The case in the switch statements should be constants at compile time. The command

switch 语句中的 case 在编译时应该是常量。命令

final int b=2

assigns the value of 2to b, right at the compile time. But the following command assigns the value of 2to bat Runtime.

在编译时为2to赋值b。但是下面的命令在运行时分配2to的值。b

final int b;
b = 2;

Thus, the compiler complains, when it can't find a constant in one of the cases of the switchstatement.

因此,编译器会抱怨,当它在switch语句的其中一种情况下找不到常量时。

回答by rozar

The final variable without value assigned to it is called a blank variable. A blank final can only be assigned once and must be unassigned when an assignment occurs or once in the program.

没有赋值的最终变量称为空变量。空白期末只能分配一次,并且必须在分配发生时或在程序中取消分配一次。

In order to do this, a Java compiler runs a flow analysis to ensure that, for every assignment to a blank final variable, the variable is definitely unassigned before the assignment; otherwise a compile-time error occurs

为了做到这一点,Java 编译器运行了一个流程分析,以确保对于空的 final 变量的每次赋值,该变量在赋值之前肯定是未赋值的;否则会发生编译时错误

That is why when the compiler compiles the switch construct it is throwing constant expression required because the value of b is unknown to the compiler.

这就是为什么当编译器编译 switch 构造时它会抛出所需的常量表达式,因为编译器不知道 b 的值。