This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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 ]