Java static final values replaced in code when compiling?

后端 未结 10 1319
死守一世寂寞
死守一世寂寞 2020-11-28 10:27

In java, say I have the following

==fileA.java==
class A
{  
    public static final int SIZE = 100;
}  

Then in another file I use this valu

10条回答
  •  余生分开走
    2020-11-28 11:26

    There is an exception to this:-

    If static final field is null at the time of compiling then it doesn't get replaced with null (which is actually its value)

    A.java

    class A{
         public static final String constantString = null;
    }
    

    B.java

    class B{
         public static void main(String... aa){
             System.out.println(A.constantString);
         }
    }
    

    Compile both A.java and B.java and run java B

    Output will be null


    Now Update A.java with following code and compile only this class.

    class A{
         public static final String constantString = "Omg! picking updated value without re-compilation";
    }
    

    Now run java B

    Output will be Omg! picking updated value without re-compilation

提交回复
热议问题