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.
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.
Finally, the break statement terminates the switch statement.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With