Video in progress

Exactly when is a class loaded and initialized by the JVM?

A class is loaded lazily, the first time it is needed. Initialization happens on the first active use: creating an object, calling a static method, reading a non-constant static field, or when a subclass is initialized.

📖 Answer

When the JVM starts, it loads only the classes it needs. Your ReportGenerator class may not be loaded until the code reaches it.

What triggers initialization:

  • new ReportGenerator();
  • ReportGenerator.create(), a static method;
  • ReportGenerator.counter, reading or writing a static field;
  • Class.forName("...ReportGenerator");
  • when a subclass is being initialized, the parent class too.

What does not:

  • ReportGenerator[] arr = new ReportGenerator[10];, creating an array;
  • the ReportGenerator.class literal;
  • reading a compile-time constant like static final int LIMIT = 100;: javac copies the value straight into the calling code.

This property is used in the well-known "lazy holder" singleton: the inner static class is initialized only when getInstance() is called, and the JVM does it thread-safely.