File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes switch question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "switch question" Watch "switch question" New topic
Author

switch question

Dinesh Tahiliani
Ranch Hand

Joined: Aug 06, 2007
Posts: 486
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...


Thanks<br />Dinesh
camilo lopes
Ranch Hand

Joined: Aug 08, 2007
Posts: 202
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.


Brazil - Sun Certified Java Programmer - SCJP 5
http://www.camilolopes.com/ About Java - Update every Week.
Guide SCJP - tips that you need know http://blog.camilolopes.com.br/livrosrevistaspalestras/
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11161
    
  16

The compiler is stupid, and cannot figure out that the two lines go together... especially since they could theoretically be hundreds of lines apart.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Prakash Subramanian
Ranch Hand

Joined: Feb 03, 2005
Posts: 32
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.

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: switch question
 
Similar Threads
compile time constants in switch statements
what is compile time constant in switch case?
Switches
compile time constant
Compile Time constant??