• 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

Case Argument in Switch

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
324th page of K&B:

It is not enough to be final. Case Argument should be compile time constant.

final int a = 1;
final int b;
b=2;
int x=0;
switch(x){

case a: //ok
case b: //compiler error

}

Can some one clarify me the above example? Why is it giving compiler error for the case argument 'b'. What exactly does the 'compile time constant' mean?

-Thanks
 
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Check out this article
http://www.codeguru.com/java/tij/tij0071.shtml
 
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A variable is considered a 'constant variable' only if it is declared:
(a) with the 'final' modifier
(b) with an initializer that's a compile-time constant expression

where a 'compile-time constant expression' is basically an expression that's made up of only literals and other constant expressions or constant variables. (See the Java Language Spec for a more formal definition.)

Some examples:

[ November 10, 2007: Message edited by: Kelvin Lim ]
 
Sujatha Musunuri
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Freddy Wong : Thanks for the link.
@Kelvin Lim: Thanks for the example. I got it now.
reply
    Bookmark Topic Watch Topic
  • New Topic