class Test { public static void main(String[] args) { final int a = 1; final int b; b = 2; int x = 0; switch (x) { case a: // ok case b: // compiler error } } } Please explain me why the above code is giving error
generally speaking, it is of TREMENDOUS help if you post the actual text of the error message. without it, we either have to guess, or copy your code and compile it ourselves. The easier you make it for others to help you, the more likely you are to get help.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
The Values we use in switch cases must be "COMPILE TIME CONSTANT"
In your case a is defined at the compile time, but for b it is initialize at the run time..!!
Since both a and b are local Variable, following checks are done by compiler :
1) Variable are initialize before using 2) In case of final variable, see after initialization there should not be any probability of changing their value..!!
In this case compiler checks that Variable b has been given a value, but that value will be assigned at run time..so it is giving an error because it wants value at the compile time...!!
Using anything except literals or "static final" constants as switch cases is very bad form. So, while you do seem to have found a situation where the compiler is being a bit dimmer than one might hope, its real-world relevance is very slight indeed.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.