aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Case Argument in Switch Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Case Argument in Switch" Watch "Case Argument in Switch" New topic
Author

Case Argument in Switch

Sujatha Musunuri
Greenhorn

Joined: Oct 23, 2007
Posts: 16
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

Joined: Sep 11, 2006
Posts: 959

Check out this article
http://www.codeguru.com/java/tij/tij0071.shtml


SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
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 ]

SCJP 5.0
Sujatha Musunuri
Greenhorn

Joined: Oct 23, 2007
Posts: 16
@Freddy Wong : Thanks for the link.
@Kelvin Lim: Thanks for the example. I got it now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Case Argument in Switch