• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Can't a switch use final parameters?

 
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 808
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
I'm thinking about a new battle cry. Maybe "Not in the face! Not in the face!" Any thoughts tiny ad?
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic