final variable case in switch statement

case, final, java, switch-statement

Solution

`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.

Problem

``` 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.

Original source