| Author |
Can't a switch use final parameters?
|
Jeff Bosch
Ranch Hand
Joined: Jul 30, 2003
Posts: 804
|
|
I tried building a method with a configurable switch statement, to test how method-local parameters and variables work when declared final. A switch statement needs constant expressions for the case statement, and the final local variables/parameters are constant. Do I get a compiler error because the case labels are potentially not constant at compile time? Here are relevant snippets of the code: I even tried assigning a value to a local final variable through the parameters: But I had the same error in both cases: Is this because these final varables must be declared and initialized before compilation? I thought the answer was 'no' because you can initialize final variables through constructors with no problem. But my results tell me that I don't really understand when a final variable is a constant and when it's not. Note that assigning a local value to one of the final variables removes the compiler error: final int x = 2; Any help? Thanks! Regards, Jeff
|
Give a man a fish, he'll eat for one day. <br />Teach a man to fish, he'll drink all your beer.<br /> <br />Cheers,<br /> <br />Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
|
 |
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
|
|
Jeff, the thing after the case must be a ConstantExpression as in The Java Language Specification paragraph 15.8 So anything which is a formal parameter to a method is a "no-no".
|
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
|
 |
Jeff Bosch
Ranch Hand
Joined: Jul 30, 2003
Posts: 804
|
|
Thanks, Barry. I found the answer this morning and was hoping I could post a "nevermind" message before anyone took the time to respond! Regards, Jeff
|
 |
 |
|
|
subject: Can't a switch use final parameters?
|
|
|