Difference between final variables and compile time constant

此生再无相见时 提交于 2019-12-31 08:49:46

问题


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?


回答1:


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;



回答2:


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.




回答3:


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



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/15309692/difference-between-final-variables-and-compile-time-constant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!