• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

switch question

 
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A case constant must evaluate to the same type as the switch expression can
use, with one additional�and big�constraint: the case constant must be a
compile time constant! Since the case argument has to be resolved at compile
time, that means you can use only a constant or final variable that is assigned a literal value. It is not enough to be final, it must be a compile time constant. For example:


Can anyone please explain me the sentence and why it is giving compile error for case b. Please ranchers...
 
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
because when you declared one variable as a final, is necessary that you define one value. Because with the modifier final the variable not have value default and in case switch �s necessary that each case have one value constant.
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The compiler is stupid, and cannot figure out that the two lines go together... especially since they could theoretically be hundreds of lines apart.
 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the below code you can see why a compile time constant is being insisted upon. Even though it is defined as final, it varies at runtime with each instantiation. Hope this example clarifies your question.

 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Dinesh Tahiliani:
Can anyone please explain me the sentence and why it is giving compile error for case b.


Obviously because it's not a compile-time constant.
 
reply
    Bookmark Topic Watch Topic
  • New Topic