Difference between final variables and compile time constant

后端 未结 5 1526
孤城傲影
孤城傲影 2021-01-31 03:59

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         


        
5条回答
  •  执笔经年
    2021-01-31 04:23

    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.

提交回复
热议问题