final variable case in switch statement

后端 未结 3 2031
北海茫月
北海茫月 2020-12-16 12:20
        final int a = 1;
        final int b;
        b = 2;
        final int x = 0;

        switch (x) {
            case         


        
3条回答
  •  囚心锁ツ
    2020-12-16 13:21

    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

    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.

提交回复
热议问题