I know that "if(compile time constant)" is considered different than "while(compile time constant)" and I know that "if" is used to provide conditional compilation.
But why is the compiler very nervous about final variables?
Here compiler is confident enough that value of i will be initialized, so He is happy with it. But in other example Since it will not initialize compiler has no idea what to print on console. Same problem comes, If you try to use it for other purposes without initialization. I remember in C/C++, If we don't initialize a variable, we would get a garbage value after printing. I guess Java compiler don't want to take that chance.
This is not really an issue with compile time constant -- it is an issue with how the if statement is evaluated.
As you already mentioned, the "reachable code" check for "if" statements is turned off to allowed for conditional statements. Hence, since the check is turned off, it doesn't really know that the "if" block is not executed. And if it is executed, you should get an error as the final variable is assigned twice.
Lukas Smith wrote:
The same in the first case, but despite the fact the compiler allows it.
So the flow control executes after final are assigned?
The Java compiler makes a distinction between whether code is reachable and whether it can complete normally. A monkey wrench is thrown in with the "if" stsatement. I remember looking at it last year, and coming to the conclusion... "getting a headache -- not really worth my time" ...
Anyway, if you are interested, see section 14.21 of the JLS.