The rules associated with Switch statements are :
- The legal argument to switch is primitive int. That means only variables and values that can be automatically promoted to (implicitly casted) an int are acceptable.
- You can use either of byte, short, char or int. You can not use any of float, double, long.
- The case argument must be final. The case argument has to be resolved at compile time, so that means you can only use a literal or final variable.
- The switch can only check for equality and NOT any other relational operators.
A simple question and explanation on the same :
class Switch1 { public static void main(String args[]) { final int a = 1; final int b; b= 2; int x = 1; switch (x) { case a: case b: } } }
When compiling an error comes like this:
Error: Switch1.java:13: constant expression required case b: // ^ 1 error
This reveals the fact that Case constant must be compile time constant.
Reference from JavaRanch Threads:
* Original Query: http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=34&t=009070
* The reply from Jim Yingst in a different thread but for the same query (earlier): http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=33&t=023680&p=1
The precise note is :
In order for b (or any variable) to be a compile-time constant, it is necessary but not sufficient that it be final. Additionally, it must be a primitive type or String, and it must be initialized in the same line it is declared, using another compile-time constant expression. That last is the requirement that is not met here, as b was only set to 2 one line after the declaration.
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.
final int b; // insert complex logic here b = 2;
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:
final int b = 2;
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.
Hope this helps!