i

JAVA Complete Course

Static Initialize

Generally in java to initialize class fields we need to create an instance of object even if we have initialization blocks in our class.

We need the actual class object to be created. We have mentioned that static fields don’t belong to any instance, they are part of the class but in order to initialize them in normal initialization block, we still need the instance to be created. Is there any other solution?

Of course, it is. In java we can have static initializer block which runs during class loading and we will be able to initialize and access static fields of any class before creating actual object of it. Below is the example, how static initializer block looks like

As we mentioned, static initializers are running before constructors. Actually, to be more precise they run before we access any static field after class loading.