[ACCEPTED]-Explanation of how classloader loads static variables-classloader

Accepted answer
Score: 11

Yes, in short, it is linear.

"What the 13 compiler actually does is to internally 12 produce a single class initialization 11 routine that combines all the static variable 10 initializers and all of the static initializer blocks 9 of code, in the order that they appear 8 in the class declaration. This single 7 initialization procedure is run automatically, one 6 time only, when the class is first loaded."

Taken 5 from Java in a nutshell.

http://www.developer.com/java/other/article.php/2238491

You should define 4 the variables and then initialize them in 3 a static intitializer block in the correct 2 order, or you could swap the order of the 1 statements as follows:

private static final int [][] LIST_INTEGER = new int [][] { {947,947}, {110,103}, 
        {947,958}, {110,120}, 
        {947,954}, {103,107}, 
        {947,967}, {110,99,104}};

private static final String [] LIST_CODE = gerarListCode(); 
Score: 4

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

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

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

More Related questions