It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Switch case logic 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 "Switch case logic" Watch "Switch case logic" New topic
Author

Switch case logic

Pritish Chakraborty
Ranch Hand

Joined: Jun 12, 2012
Posts: 91

Hello all

In Chapter 5 of K&B, in the switch case objective, it is said that the case value can only be some literal constant or a final variable, in addition to being a compile time constant.

That's very fine, but the code example that follows is what is confusing.



What's wrong with this section of code? b is a final variable and has been assigned only once. Both a and b are compile time constants, is it not? Or am I missing something?


OCJP 6
gurpeet singh
Ranch Hand

Joined: Apr 04, 2012
Posts: 924
    
    1

Pritish Chakraborty wrote:Hello all

In Chapter 5 of K&B, in the switch case objective, it is said that the case value can only be some literal constant or a final variable, in addition to being a compile time constant.

That's very fine, but the code example that follows is what is confusing.



What's wrong with this section of code? b is a final variable and has been assigned only once. Both a and b are compile time constants, is it not? Or am I missing something?


b is not a compile time constant. i recommend you reading Henry's post on compile time constants, which i must say is the excellent source regarding compile time constant. in short for a variable to be compile time constant variable it should be of type String or primitive, declared with final keyword and this is important, initialized on the same line as declaration.. in your case it is not initialized in the same line. had it been final int b = 2; then it would have been compile time constant variable.

please find henry's excellent post at http://www.coderanch.com/t/454384/java/compile-time-constant
Pritish Chakraborty
Ranch Hand

Joined: Jun 12, 2012
Posts: 91

I was thinking along those lines, but it really confused me as to why if not initialized on the same line, a final variable cannot be a compile time constant. Henry's reference cleared that; a more proper definition as per him is "declared and initialized at the same time".

Thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Switch case logic