Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 646
Furlando Avatar asked Apr 27 '13 17:04

Furlando


People also ask

Can we use final variable in switch case?

The value for a case must be of the same data type as the variable in the switch. The value for a case must be constant or literal. Variables are not allowed.

Which is the last statement of the switch case?

Finally, the break statement terminates the switch statement.

How do you end a switch case?

You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.

What variables are used in a switch statement?

Syntax. The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.


2 Answers

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.

like image 73
Rahul Bobhate Avatar answered Oct 16 '22 10:10

Rahul Bobhate


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.

like image 32
Bozho Avatar answered Oct 16 '22 08:10

Bozho