Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can't a switch use final parameters?

 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic