final variable case in switch statement

后端 未结 3 2046
北海茫月
北海茫月 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:08

    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;
    }
    

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

提交回复
热议问题