Difference between final variables and compile time constant

后端 未结 5 1525
孤城傲影
孤城傲影 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:22

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-31 04:35

    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;
    
    0 讨论(0)
  • 2021-01-31 04:38

    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.

    0 讨论(0)
  • 2021-01-31 04:41

    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.

    0 讨论(0)
提交回复
热议问题