File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Switch case logic

 
Pritish Chakraborty
Ranch Hand
Posts: 91
C++ Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 91
C++ Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic