| Author |
final in switch case
|
sarathchandra chandala
Greenhorn
Joined: Sep 06, 2007
Posts: 9
|
|
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
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 10043
|
|
|
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.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Bill Shirley
Ranch Hand
Joined: Nov 08, 2007
Posts: 457
|
|
also, use code tags after this line of code the value of b can never be changed, it is therefore undefined what's the next line of code?  [ January 24, 2008: Message edited by: Bill Shirley ]
|
Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
|
 |
Ben Souther
Sheriff
Joined: Dec 11, 2004
Posts: 13410
|
|
Originally posted by Bill Shirley: also, use code tags after this line of code the value of b can never be changed, it is therefore undefined what's the next line of code? [ January 24, 2008: Message edited by: Bill Shirley ]
Not entirely true. You can delay the inital assignment of a final variable. Example:
|
Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
|
 |
Sunny Jain
Ranch Hand
Joined: Jul 23, 2007
Posts: 433
|
|
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...!!
|
Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
|
 |
Peter Chase
Ranch Hand
Joined: Oct 30, 2001
Posts: 1970
|
|
|
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.<br /> <br />#:^P
|
 |
 |
|
|
subject: final in switch case
|
|
|