wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Can't a switch use final parameters? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can Watch "Can New topic

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?

Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, 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!
jQuery in Action, 2nd edition
subject: Can't a switch use final parameters?
Similar Threads
Case constant must be compile time constant?
Apply function names as parameters in other functions
The CASE of the STATIC initializer
uninitialized final variable!