Explanation of how classloader loads static variables

前端 未结 2 1836
再見小時候
再見小時候 2020-12-17 23:05

Ok so this is a newbie question on java, but i can\'t seem to get my head around it.

I have the following code inside my class

private static final          


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 23:55

    The JVM will, indeed, initialize the static fields in the order it encounters them.

    A class's static fields are initialized when the class is first encountered by the JVM. According to Java Puzzlers, puzzle 49 (which goes on to reference JLS 4.12.5), static fields are first set to their default values. Object variables are set to null, ints are set to 0, etc. After that, their initializers are executed in order of appearance.

    So, in your example, LIST_CODE and LIST_INTEGER are first set to null. Then, LIST_CODE is initialized by calling gerarListCode(). LIST_INTEGER is still null when that method is executed. Only after that, LIST_INTEGER is initialized with the literal value you give in your example.

提交回复
热议问题