It is said that static blocks in java run only once when that class is loaded. But what does it actually mean? At which point is a class loaded by JVM (Java Virtual Machine)?
Is it when the main method in that class is called? And is it that all the super-classes of the same class are also loaded when the main method starts execution?
Consider that A extends B and B extends C. All have static blocks. If A has the main method, then what will be the sequence of execution of static blocks?
From the Java Language Specification:
The process is described in more detail in the Java Virtual Machine Specification.
This is described in the Execution section of the JLS. Namely:
So in your example, the static block of the "topmost" class (
C
) runs first, then that ofB
, then the most-derived one.See that documentation for a detailed description of all the steps that go into loading a class.
(Classes get loaded when they are first actively used.)
I think the following example will solve all of your problems:
Before a class is initialized, its superclasses are initialized, if they have not previously been initialized.
Thus, the test program:
prints:
The class One is never initialized, because it not used actively and therefore is never linked to. The class Two is initialized only after its superclass Super has been initialized.
For more details visit this link
Edit details: Removed confusing lines.