Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Legal expressions for switch and case statements

 
sweety singh
Ranch Hand
Posts: 49
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code:

final int a = 1;
final int b;
b = 2;
int x = 0;
switch (x) {
case a: // ok
case b: // compiler error

why is there a compilation error at case b.... do i need to declare it as...
"final int b = 2;"
 
Kaydell Leavitt
Ranch Hand
Posts: 689
Eclipse IDE Firefox Browser Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Java Ranch:

What is going on in this example is a mistake that we all easily make. To understand what always happens is that the compiler, compiles one-line-at-a-time and that the evaluation is done on a second pass after compilation is complete.

As humans, we naturally try to compile and run the code in our minds at the same time.

In this specific case, in line 1, a variable named "a" is declared as an "int" and the "final" qualifier means that once a value is assigned, it cannot be changed, AND the value of "1" is assigned all on the same line of code, so the compiler knows that the value of the variable "a" is a constant.

Also, a "case" value in a "switch" statement must be a constant, and so the variable "a" is known by the compiler to be a constant.

In line 2, a variable "b" is declared, also as an int, and the "final" qualifier, but no value is assigned to b on that line. The point I want to make is that the compiler compiles only one line at-a-time and so when the variable "b" is later given a value, the compiler doesn't make a note that the value of the variable "b" is now known and is a constant because of the "final" qualifier.

I believe that many of my errors in trying to predict the outcome of running code is that I have a tendency to compile and run it in my mind in one pass and the computer uses two passes. In fact, the command-line tools are separate. "javac" compiles the code from source code into byte code and the command "java" takes the byte-code and executes it.
[ December 29, 2007: Message edited by: Kaydell Leavitt ]
 
sweety singh
Ranch Hand
Posts: 49
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot... thank you..
 
sitaram
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
case expressions must be constants expressions.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic