JVM
jvm1ClassLoadingDemo
- Path
- pkg6jvm/jvm1ClassLoadingDemo.java
- Package
- pkg6jvm
- Study order
- 1
- Run
- Single-file source launch
- Command
- java pkg6jvm/jvm1ClassLoadingDemo.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg6jvm;2 3/*4 * jvm1ClassLoadingDemo.java5 * ---------------------6 * Shows the class loader hierarchy and the order of static initialization.7 *8 * CLASS LOADING PHASES:9 * Loading -> Linking (Verify -> Prepare -> Resolve) -> Initialization10 * LOADER DELEGATION (parent-first):11 * Bootstrap (core JDK) -> Platform -> Application (your classpath)12 *13 * INITIALIZATION ORDER (on first active use of a class):14 * static fields & static blocks run top-to-bottom, exactly once.15 */16public class jvm1ClassLoadingDemo {17 18 static class Config {19 static final String NAME;20 static int counter;21 static { // static initializer block22 System.out.println(" [Config static block] runs once on first use");23 NAME = "JavaMastery";24 counter = 100;25 }26 Config() { System.out.println(" [Config constructor] runs per instance"); }27 }28 29 public static void main(String[] args) {30 // 1) Class loader hierarchy31 ClassLoader app = jvm1ClassLoadingDemo.class.getClassLoader();32 System.out.println("Application loader : " + app);33 System.out.println("Platform loader : " + app.getParent());34 System.out.println("Bootstrap loader : " + null + " (represented as null; loads java.* core)");35 36 // Core classes are loaded by the bootstrap loader (null)37 System.out.println("String's loader : " + String.class.getClassLoader() + " (bootstrap)");38 39 // 2) Static initialization happens on first ACTIVE use40 System.out.println("\nBefore touching Config (not initialized yet)...");41 System.out.println("Touching Config.NAME now:");42 System.out.println(" Config.NAME = " + Config.NAME); // triggers static block43 System.out.println("Creating two instances:");44 new Config(); new Config(); // static block does NOT rerun45 System.out.println("Config.counter = " + Config.counter);46 }47}