Java › Class Loading & Bytecode Verification
What are the phases of class loading (loading, linking, initialization), and what specifically happens during each?
IntermediateAnswer
Loading finds the class's bytecode and creates its Class object in memory; Linking has three sub-phases -- verification (bytecode verifier checks the class file is structurally valid and doesn't violate JVM safety constraints), preparation (static fields are allocated and set to their default zero-equivalent values, not yet their actual initializer values), and resolution (symbolic references to other classes are optionally resolved, can be deferred until first actual use); Initialization executes the class's static initializers and static field assignments in the order they appear in source, happening lazily on first active use (like the first instantiation or static method call) rather than eagerly at class loading time.
public class Config {
static { System.out.println("Static initializer running"); }
static int value = computeValue();
static int computeValue() {
System.out.println("Computing static value");
return 42;
}
}
// Config class is LOADED and LINKED when referenced, but INITIALIZATION
// (running the static block and computeValue()) happens lazily on first active use:
System.out.println("Before first use");
int v = Config.value; // triggers initialization HERE, prints both messages firstReal-world example A developer debugging why a static initializer's side effect (like registering a driver via Class.forName()) doesn't happen until much later than expected in program execution learns this is expected behavior, since Java defers class initialization lazily until the class is genuinely actively used, not merely referenced or loaded.