Search code examples
javaclassloader

Difference between loading a class and instantiating it


Could someone explain what is the difference between Class loading and instantiating a Class. When we load a class with Static variable does it also get instantiated the same time the Class get loaded? After all static code is part of the class rather than it's individual instances. It would be helpful if someone provided an example to help me understand this better.


Solution

  • Here is some nice explanation(with an example and observation)

    When a class is loaded and initialized in JVM - Java

    When Class is loaded in Java

    Class loading is done by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need of class initialization occurs. If Class is loaded before its actually being used it can sit inside before being initialized. I believe this may vary from JVM to JVM. While its guaranteed by JLS that a class will be loaded when there is a need of static initialization.

    When a Class is initialized in Java

    When a Class is initialized in Java After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when :

    1) an Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.

    2) an static method of Class is invoked.

    3) an static field of Class is assigned.

    4) an static field of class is used which is not a constant variable.

    5) if Class is a top level class and an assert statement lexically nested within class is executed.

    Hope that helps.