Furlando
Furlando

Reputation: 367

final variable case in switch statement

        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.

Upvotes: 19

Views: 21238

Answers (3)

Rahul Bobhate
Rahul Bobhate

Reputation: 5082

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

final int b=2

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

final int b;
b = 2;

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

Upvotes: 15

rozar
rozar

Reputation: 1078

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.

Upvotes: 3

Bozho
Bozho

Reputation: 597324

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.

Upvotes: 11

Related Questions