Search code examples
javaclassloader

Preparation stage and initialization stage of java class loader


I am not able to understand the difference between following lines ( http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.2 )

A) Preparation involves initializing static fields to the default values.

B) Initialization of a class consists of executing initializers for static fields (class variables) declared in the class.

Does it mean that 'a' will get assign the default value in "preparation" stage and 'b' will get assign the value in "Initialization" stage:

static int a;  
static int b=2;

Solution

  • "Initializing to default values" means that the fields are set to the following values:

    • boolean: false
    • int, long, byte, short: 0
    • double, float: +0.0
    • char: '\u0000'
    • reference types: null

    "Initializing by executing initializers" means that now the expressions that are assigned to those static fields are evaluated and assigned to them.

    So, in the "preparation" stage, your a and b will be created and will receive the value 0. In the "initialization" stage, b will receive the value 2.


    This is easy to verify using a method that has a side-effect. Instead of assigning simple "2" to b, we are calling a static method that returns the value 2, but it also prints information about the variables before doing so:

    public class SimpleTest {
    
        private static int a;
        private static int b = printAAndBReturning2("initializer");
    
        static {
            printAAndBReturning2("static initializing block");
        }
    
        public static void main(String[] args) {
    
            printAAndBReturning2("main");
    
        }
    
        public static int printAAndBReturning2(String where) {
            System.out.printf("In %s a is %d and b is %d%n", where, SimpleTest.a, SimpleTest.b);
            return 2;
        }
    }
    

    The output is:

    In initializer a is 0 and b is 0
    In static initializing block a is 0 and b is 2
    In main a is 0 and b is 2

    This demonstration also serves to warn you about using methods that are ran during the initialization stage.