z is a variable, and you can switch on it.
CONSTANT is a constant, so you can case on it.
CONSTANT + 10 is an expression, but it is an expression that can be evaluated at compile-time so you can case on it.
On the other hand:
In the above example, x is treated as a variable at compile-time because, although it is known at compile time, it is not declared final so the compiler doesn't try to evaluate x or x + 10 so they are variables -- not constants, so you can't case on them. The above code would not compile.
Originally posted by asha ganapathy:
I understood that only constants can be used for case statements and not variables.But how about this code?why should this code have compiler errors?
final int a =1 ;
final int b;
case b: //compiler error;
Because b is not a compile time constant.
You may wonder why this is important, given that the variable b is definitely assigned using another compile-time constant (2) just one line after the declaration. The thing is, the compiler is not expected to analyze the code after a declaration to determine whether a variable is "really" a constant or not. It could be really simple code, or complex code; it doesn't matter.
In this case the code was really simple, and it may seem like the compiler "should have known" that b was a constant. But at the same time, since the code was so simple, the programmer could have simply initialized b on the same line it was declared:
If you want a variable to represent a compile-time constant, make sure it's initialized on the same line it's declared. If you can't do that, it's not a compile-time constant.