Difference between final variables and compile time constant

Tarun Mohandas picture Tarun Mohandas · Mar 9, 2013 · Viewed 8.4k times · Source

What is the difference between final variables and compile time constants?

Consider the following code

final int a = 5;
final int b;
b=6;
int x=0;
switch(x)
{
     case a: //no error
     case b: //compiler error
}

What does this mean? When and how are final variables assigned a value? What happens at run time and what happens at compile time? Why should we give switch a compile time constant? What other structures of java demands a compile time constant?

Answer

poitroae picture poitroae · Mar 9, 2013

The problem is, that all case: statements must be ultimate at compile time. Your first statement is ultimate. a will for 100% be no other value than 5.

final int a = 5;

However, this is not guaranteed for b. What if there would be an if-statement around b?

final int b;
if(something())
   b=6;
else
   b=5;