When does static class initialization happen?

Tony R picture Tony R · Aug 17, 2010 · Viewed 73.4k times · Source

When are static fields initialized? If I never instantiate a class, but I access a static field, are ALL the static blocks and private static methods used to instantiate private static fields called (in order) at that instant?

What if I call a static method? Does it also run all the static blocks? Before the method?

Answer

Stephen C picture Stephen C · Aug 17, 2010

A class's static initialization normally happens immediately before the first time one of the following events occur:

  • an instance of the class is created,
  • a static method of the class is invoked,
  • a static field of the class is assigned,
  • a non-constant static field is used, or
  • for a top-level class, an assert statement lexically nested within the class is executed1.

See JLS 12.4.1.

It is also possible to force a class to initialize (if it hasn't already initialized) by using Class.forName(fqn, true, classLoader) or the short form Class.forName(fqn)


1 - The final bullet point was present in the JLS for Java 6 through Java 8, but it was apparently a mistake in the specification. It was finally corrected in the Java 9 JLS: see source.