Difference between final variables and compile time constant

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

提交回复
热议问题