Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Case Argument in Switch

 
Sujatha Musunuri
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • 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
 
Freddy Wong
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out this article
http://www.codeguru.com/java/tij/tij0071.shtml
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
@Freddy Wong : Thanks for the link.
@Kelvin Lim: Thanks for the example. I got it now.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic