Search code examples
javaclassloader

When are imported classes loaded in java?


In the following scenario ,

import A;
public class B{
    static A a;
    static{
        a = new A();
    }
}

Is it possible that the static initialization block gets called before a is properly initialized? Note: A here is a logging framework.


Solution

  • In the case you mention above static block will be called before A is initialized as static block will be called when class loads (Class B in your case). So when you do

    B.someStaticMethod() 
    

    First class B will be loaded where static block is called with it(One time process in JVM) and then static method will be called.

    Also Note that Importing statement to load the class does not load the class. It happens when yo do some operation on that class.