I know that the class is loaded exactly with the following record A a = new A(); .
And when accessing static class content,
for example, if we write А.SomeStatic .

Will the class be loaded only when declaring the variable A a; ?

    1 answer 1

    It is necessary to distinguish between class / interface loading and initialization (there is also an intermediate large stage - linking, but we will not consider it). Loading (loading) is the process of searching for a binary representation of a class / interface by the corresponding name and the creation of this class / interface from this representation. Initialization consists in the execution of all blocks / methods of class / interface initialization.

    The specification does not give exact instructions for loading the class / interface - this process can be performed in advance (lazy loading), or immediately before linking and initialization.

    Concerning initialization, the conditions for its implementation are clearly stated in the specification:

    • when executing the following JVM instructions: new , getstatic , putstatic or invokestatic ,
    • when executing reflection methods from the Java API ( Class class methods and using classes from the java.lang.reflect ),
    • initialization of derived classes
    • when starting the JVM, if the class contains a main() method.

    The declaration of a reference to class A does not lead to the fulfillment of at least one of the above conditions, therefore, the class will not be initialized.

    To view the class loading order, you can use the -verbose:class option.

    More information on this subject can be found in the specifications of Chapter 5. Loading, Linking, and Initializing