質問

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?

役に立ちましたか?

解決

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;

他のヒント

What does this mean?

It means that 'b' isn't a compile time constant expression, and the JLS requires it to be.

When and how are final variables assigned a value?

Formally, when the assignment statement or initializer is executed.

But in practice, if the final declares a compile time constant the expression is evaluated at compile time and its value is hard-wired into the code.

What happens at run time and what happens at compile time?

See above.

Why should we give switch a compile time constant?

Because the JLS requires it.

It is necessary for the bytecode compiler to check that the switch statement is well formed; i.e. that the values of the switch constants don't collide. It also allows the JIT compiler to generate code that is optimized for the actual values of the switch constants.

What other structures of java demands a compile time constant?

None that I can think of, off the top of my head.

From compiler point of view you are trying to use a variable b that might not be initialized. The switch statement are compiled into JVM bytecode tableswitch or lookupswitch which requires that values used in case statement are both compile time constant and unique.

final int a = 4; // compiler is sure a is initialized
final int b;// variable b is not guranted to be assigned

e.g. Although this statement will ultimately initialize b , but compiler can't detect it.

if (a < 4) b= 10;
if (a >= 4) b = 8

final int b; can be assigned once and value is not sure, that will be decided on runtime depending on conditions. that is the reason, even if being a final variable, it is not COMPILE TIME constant although it will be a RUN TIME constant and case needs compile time constants.

The switch statement needs a constant. As final variables can be delayed initialized and the compiler cannot determine for b that it has a value in the case branch.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top