I am reading the Bathy and Berts book and have a doubt about the case construct. Yhe book says "The case argument has to be resolved at compile time, so that means you can use only a constant or final variable that is assigned a literal value." It also has an example:
Ok, my doubt is: why do we get a compiler error when using variable b? I mean, it's declared final, and is assigned a value before the case test. So, in my opinion, it can be considered a constant, but Kathy (and the compiler, by the way) tell me otherwise. Could someone please explain this to me? Thanks! Pedro Ivo Dantas
This gets into the question of what the compiler knows and when it knows it. "a" is essentially a synonym for 1 and is shown that way in the compiler's symbol table. You can use "a" pretty much any place you can use 1.
"b" is shown in the symbol table as a blank final variable. The rules are that it cannot be referenced until it is assigned a value (as usual) and that it can't be assigned a value after it has already been assigned a value. So "final int b;" and "b = 2;" are separate statements and "b" is not just a synonym for 2. Therefore, b can't be used after case.
Later in the compile process, the compiler will verify that b will always be assigned a value before it is used. Still later, an optimizing compiler may combine the "final int b;" and "b = 2;" statements for code generation purposes. However, for semantic analysis purposes, b has two possible values - unassigned and 2 - so it can't be used in place of 2 where only a constant will do; [ November 03, 2004: Message edited by: Mike Gershman ]