Back to Classloading & Compilation
Q5Question 5 of 5

How do class loading, linking, and initialization work in the JVM

Answer: Class loading is the JVM process of reading .class bytecode, linking it through verification, preparation, and resolution, and initializing it by running static blocks, all managed by a three-level ClassLoader hierarchy that uses parent delegation.

Key Concepts
  • The JVM loads classes on demand through three phases: loading, linking, and initialization.
  • Loading reads .class bytecode from disk or network and creates a java.lang.Class object in the method area.
  • Linking has three sub-phases: verification checks bytecode safety, preparation sets static fields to default values, and resolution converts symbolic references to direct pointers.
  • Initialization runs the static initializer block and assigns values to static fields in source code order.
  • The ClassLoader hierarchy has three levels: bootstrap loads java.lang, platform loads java.sql, and application loads your project classes.
  • Parent delegation ensures each ClassLoader asks its parent first, preventing user code from replacing core JDK classes like java.lang.String.
  • Custom ClassLoaders let you load classes from databases, encrypted files, or remote servers at runtime.

Definition

Class loading is the JVM process of reading .class bytecode, linking it through verification, preparation, and resolution, and initializing it by running static blocks, all managed by a three-level ClassLoader hierarchy that uses parent delegation.
  • Class loading is the phase where the JVM reads .class bytecode from disk, network, or another source and creates a java.lang.Class object in the method area.
  • Linking is the three-step phase after loading: verification checks bytecode for safety violations, preparation allocates default values to static fields, and resolution turns symbolic references into direct memory pointers.
  • Initialization is the final phase where the JVM runs (the class initializer), executing static blocks and assigning static field values in source code order.
  • ClassLoader hierarchy is the three-level chain: bootstrap (loads java.lang), platform (loads java.sql, java.xml), and application (loads your project classes from the classpath).
  • Parent delegation is the rule that every ClassLoader asks its parent to load a class before attempting to load it itself, which prevents untrusted code from replacing core JDK classes.

Think of opening a new branch of National Bank of India. Loading is like receiving the branch blueprint from head office and registering it in the central directory. Linking is the inspection phase: verification checks that the blueprint meets safety codes, preparation reserves the physical space with default fixtures, and resolution connects the branch references (ATM network, SWIFT codes) to actual systems. Initialization is opening day, when the branch manager runs the setup procedures and the branch starts serving customers. The ClassLoader hierarchy is like the bank organizational structure: head office (bootstrap) handles core systems, the regional office (platform) handles shared services, and the local branch (application) handles customer-facing code.

Understanding the Concepts

What is class loading in the JVM?

When your Java application runs, the JVM does not load all classes at startup. It loads each class the first time it is referenced, for example when you create an object, call a static method, or access a static field. The JVM reads the .class file (bytecode compiled from your .java source), creates a java.lang.Class object, and stores the class metadata in the method area. This on-demand loading keeps memory usage low and startup time fast.

JAVA
package com.bank.classloading;

public class OnDemandLoadingDemo {
    public static void main(String[] args) {
        System.out.println("Step 1: Application started");
        System.out.println("Step 2: AccountService not loaded yet");

        // The class is loaded when we first reference it
        System.out.println("Step 3: About to create AccountService");
        AccountService service = new AccountService();
        service.getBalance("SAV2001");
    }
}

class AccountService {
    static {
        System.out.println("  >> AccountService: static block executed (class loaded and initialized)");
    }

    public void getBalance(String accountId) {
        System.out.println("Step 4: Balance for " + accountId + ": 50,000.00 INR");
    }
}
TEXT
Expected output:
Step 1: Application started
Step 2: AccountService not loaded yet
Step 3: About to create AccountService
  >> AccountService: static block executed (class loaded and initialized)
Step 4: Balance for SAV2001: 50,000.00 INR

Notice that the static block runs between Step 3 and Step 4. The class is loaded only when the JVM encounters new AccountService(), not at program start.

What are the three phases of class loading?

Every class goes through three phases before the JVM can use it: loading, linking, and initialization. These phases happen in order, but some parts can overlap.

  1. Loading: The ClassLoader reads the .class bytecode from a source (disk, JAR, network) and creates a java.lang.Class object.
  2. Linking: The JVM verifies the bytecode, prepares static fields with default values, and resolves symbolic references.
  3. Initialization: The JVM runs the static initializer block () and assigns the actual values you wrote in your source code.

The key distinction is between preparation (default values) and initialization (your values). During preparation, an int static field gets 0, an Object field gets null, and a boolean gets false. During initialization, they get the values you assigned in code.

JAVA
package com.bank.classloading;

public class ThreePhasesDemo {
    public static void main(String[] args) {
        System.out.println("Before accessing InterestConfig:");
        System.out.println("  After preparation (defaults): rate=0.0, bankName=null, active=false");
        System.out.println();

        // Accessing the class triggers initialization
        System.out.println("Accessing InterestConfig.RATE:");
        System.out.println("  RATE = " + InterestConfig.RATE);
        System.out.println("  BANK_NAME = " + InterestConfig.BANK_NAME);
        System.out.println("  ACTIVE = " + InterestConfig.ACTIVE);
    }
}

class InterestConfig {
    // After preparation: RATE = 0.0 (default for double)
    // After initialization: RATE = 7.5
    static double RATE = 7.5;

    // After preparation: BANK_NAME = null (default for Object)
    // After initialization: BANK_NAME = "National Bank of India"
    static String BANK_NAME = "National Bank of India";

    // After preparation: ACTIVE = false (default for boolean)
    // After initialization: ACTIVE = true
    static boolean ACTIVE = true;

    static {
        System.out.println("  >> InterestConfig: static block running (initialization phase)");
        System.out.println("  >> RATE is now: " + RATE);
        System.out.println("  >> BANK_NAME is now: " + BANK_NAME);
    }
}
TEXT
Expected output:
Before accessing InterestConfig:
  After preparation (defaults): rate=0.0, bankName=null, active=false

Accessing InterestConfig.RATE:
  >> InterestConfig: static block running (initialization phase)
  >> RATE is now: 7.5
  >> BANK_NAME is now: National Bank of India
  RATE = 7.5
  BANK_NAME = National Bank of India
  ACTIVE = true

What is the ClassLoader hierarchy?

Java has three built-in ClassLoaders arranged in a parent-child chain:

  1. Bootstrap ClassLoader: Loads core JDK classes from java.base module (java.lang.String, java.lang.Object, java.util.List). Written in native code. Returns null when you call getClassLoader() on a class it loaded.
  2. Platform ClassLoader (called Extension ClassLoader before Java 9): Loads platform modules like java.sql, java.xml, java.logging.
  3. Application ClassLoader (also called System ClassLoader): Loads your project classes from the classpath, module path, or JAR files.
JAVA
package com.bank.classloading;

import java.math.BigDecimal;

public class ClassLoaderHierarchyDemo {
    public static void main(String[] args) {
        // Bootstrap ClassLoader loads core classes
        ClassLoader stringLoader = String.class.getClassLoader();
        System.out.println("String loaded by:     " + stringLoader);
        System.out.println("  (null means Bootstrap ClassLoader, written in native code)");
        System.out.println();

        // Bootstrap also loads java.math.BigDecimal
        ClassLoader bigDecimalLoader = BigDecimal.class.getClassLoader();
        System.out.println("BigDecimal loaded by: " + bigDecimalLoader);
        System.out.println();

        // Application ClassLoader loads your classes
        ClassLoader appLoader = ClassLoaderHierarchyDemo.class.getClassLoader();
        System.out.println("Our class loaded by:  " + appLoader);
        System.out.println();

        // Walk the parent chain
        System.out.println("ClassLoader hierarchy (child to parent):");
        ClassLoader current = ClassLoaderHierarchyDemo.class.getClassLoader();
        int level = 1;
        while (current != null) {
            System.out.println("  Level " + level + ": " + current);
            current = current.getParent();
            level++;
        }
        System.out.println("  Level " + level + ": Bootstrap (native, shows as null)");
    }
}
TEXT
Expected output:
String loaded by:     null
  (null means Bootstrap ClassLoader, written in native code)

BigDecimal loaded by: null

Our class loaded by:  jdk.internal.loader.ClassLoaders$AppClassLoader@251a69d7

ClassLoader hierarchy (child to parent):
  Level 1: jdk.internal.loader.ClassLoaders$AppClassLoader@251a69d7
  Level 2: jdk.internal.loader.ClassLoaders$PlatformClassLoader@6d06d69c
  Level 3: Bootstrap (native, shows as null)

What is the parent delegation model, and why does it matter?

When a ClassLoader receives a request to load a class, it does not load it immediately. It first delegates the request to its parent. The parent delegates to its parent, all the way up to the bootstrap ClassLoader. If the parent can load the class, it does. If not, the child tries.

This model exists for security. Without it, someone could write a malicious java.lang.String class, put it on the classpath, and the application ClassLoader would load it instead of the real one. With parent delegation, the bootstrap ClassLoader always loads java.lang.String first, so the malicious version is never used.

JAVA
package com.bank.classloading;

public class ParentDelegationDemo {
    public static void main(String[] args) throws Exception {
        ClassLoader appLoader = ClassLoader.getSystemClassLoader();

        // Request to load java.lang.String goes up to bootstrap
        Class<?> stringClass = appLoader.loadClass("java.lang.String");
        System.out.println("Requested String from AppClassLoader");
        System.out.println("  loaded by: " + stringClass.getClassLoader());
        System.out.println("  (null = Bootstrap, because parent delegation kicked in)");
        System.out.println();

        // Request to load our own class stays at app level
        Class<?> ourClass = appLoader.loadClass("com.bank.classloading.ParentDelegationDemo");
        System.out.println("Requested ParentDelegationDemo from AppClassLoader");
        System.out.println("  loaded by: " + ourClass.getClassLoader());
        System.out.println("  (AppClassLoader loaded it because bootstrap and platform could not)");
        System.out.println();

        // Demonstrate: two classes loaded by the same classloader are the same
        Class<?> ourClass2 = appLoader.loadClass("com.bank.classloading.ParentDelegationDemo");
        System.out.println("Same class loaded twice: " + (ourClass == ourClass2));
        System.out.println("  (ClassLoader caches the Class object after first load)");
    }
}
TEXT
Expected output:
Requested String from AppClassLoader
  loaded by: null
  (null = Bootstrap, because parent delegation kicked in)

Requested ParentDelegationDemo from AppClassLoader
  loaded by: jdk.internal.loader.ClassLoaders$AppClassLoader@251a69d7
  (AppClassLoader loaded it because bootstrap and platform could not)

Same class loaded twice: true
  (ClassLoader caches the Class object after first load)

How does the initialization order work with static blocks and fields?

The JVM initializes static fields and static blocks in the exact order they appear in the source code, from top to bottom. If class A references class B in a static field, class B is loaded and initialized before class A continues.

This order matters when you have dependencies between static fields. If you move a static block above the field it depends on, the field will still have its default value (zero, null, or false) when the block runs.

JAVA
package com.bank.classloading;

import java.math.BigDecimal;

public class InitializationOrderDemo {
    public static void main(String[] args) {
        System.out.println("Account minimum balance: " + BankConfig.MIN_BALANCE);
        System.out.println("Bank name: " + BankConfig.BANK_NAME);
        System.out.println("Interest rate: " + BankConfig.INTEREST_RATE);
        System.out.println("Configured: " + BankConfig.CONFIGURED);
    }
}

class BankConfig {
    // Step 1: This field is assigned first
    static String BANK_NAME = initBankName();

    // Step 2: This static block runs second
    static {
        System.out.println("[init] Static block 1: BANK_NAME = " + BANK_NAME);
        System.out.println("[init] Static block 1: MIN_BALANCE = " + MIN_BALANCE);
        System.out.println("  (MIN_BALANCE is still default 0 because it is declared below)");
    }

    // Step 3: This field is assigned third
    static BigDecimal MIN_BALANCE = new BigDecimal("1000.00");

    // Step 4: This static block runs fourth
    static {
        System.out.println("[init] Static block 2: MIN_BALANCE = " + MIN_BALANCE);
    }

    // Step 5: These fields are assigned fifth and sixth
    static double INTEREST_RATE = 7.5;
    static boolean CONFIGURED = true;

    private static String initBankName() {
        System.out.println("[init] initBankName() called");
        return "National Bank of India";
    }
}
TEXT
Expected output:
[init] initBankName() called
[init] Static block 1: BANK_NAME = National Bank of India
[init] Static block 1: MIN_BALANCE = null
  (MIN_BALANCE is still default 0 because it is declared below)
[init] Static block 2: MIN_BALANCE = 1000.00
Account minimum balance: 1000.00
Bank name: National Bank of India
Interest rate: 7.5
Configured: true

Notice that in Static block 1, MIN_BALANCE is null because the BigDecimal field has not been assigned yet. The preparation phase set it to null (the default for reference types), and the assignment to new BigDecimal("1000.00") happens later in Step 3.

How is ClassNotFoundException different from NoClassDefFoundError?

These two are the most common class loading errors, and interviewers expect you to know the difference.

FeatureClassNotFoundExceptionNoClassDefFoundError
TypeChecked exceptionError (unchecked)
When it occursWhen you call Class.forName() or ClassLoader.loadClass() and the class is not foundWhen the JVM tries to load a class that was available at compile time but missing at runtime
CauseThe .class file does not exist on the classpathThe .class file was deleted, a dependency JAR is missing, or static initialization failed
RecoveryYou can catch it and handle it (try a fallback)Usually fatal, the application cannot recover
Common scenarioLoading a JDBC driver by nameA library JAR was removed from the deployment
JAVA
package com.bank.classloading;

public class ClassNotFoundVsNoClassDefDemo {
    public static void main(String[] args) {
        // ClassNotFoundException: explicit load of a class that does not exist
        System.out.println("=== ClassNotFoundException ===");
        try {
            Class.forName("com.bank.service.NonExistentService");
        } catch (ClassNotFoundException e) {
            System.out.println("Caught: " + e.getClass().getSimpleName());
            System.out.println("Message: " + e.getMessage());
            System.out.println("This is a checked exception. You must handle it.");
        }

        System.out.println();

        // NoClassDefFoundError: class was available at compile time but fails at runtime
        System.out.println("=== NoClassDefFoundError ===");
        try {
            // BrokenService has a static initializer that throws an exception.
            // First attempt causes ExceptionInInitializerError.
            // Second attempt causes NoClassDefFoundError.
            new BrokenService();
        } catch (ExceptionInInitializerError e) {
            System.out.println("First attempt: " + e.getClass().getSimpleName());
            System.out.println("Cause: " + e.getCause());
        }

        try {
            // Second attempt: JVM remembers the class failed to initialize
            new BrokenService();
        } catch (NoClassDefFoundError e) {
            System.out.println("Second attempt: " + e.getClass().getSimpleName());
            System.out.println("Message: " + e.getMessage());
            System.out.println("This is an Error. Usually not recoverable.");
        }
    }
}

class BrokenService {
    static {
        // Simulate a static initializer that fails
        if (true) {
            throw new RuntimeException("Database connection failed for National Bank of India");
        }
    }
}
TEXT
Expected output:
=== ClassNotFoundException ===
Caught: ClassNotFoundException
Message: com.bank.service.NonExistentService
This is a checked exception. You must handle it.

=== NoClassDefFoundError ===
First attempt: ExceptionInInitializerError
Cause: java.lang.RuntimeException: Database connection failed for National Bank of India
Second attempt: NoClassDefFoundError
Message: com/bank/classloading/BrokenService
This is an Error. Usually not recoverable.

The important lesson: if a static initializer throws an exception, the first access gets ExceptionInInitializerError. Every subsequent access to the same class gets NoClassDefFoundError because the JVM marks the class as unusable.

How do you create a custom ClassLoader?

You create a custom ClassLoader by extending java.lang.ClassLoader and overriding the findClass method. The findClass method receives the fully qualified class name, reads the bytecode from your custom source (file, database, network), and calls defineClass to convert the bytes into a Class object.

You should override findClass, not loadClass. Overriding findClass preserves the parent delegation model: the parent ClassLoader gets a chance to load the class first. Overriding loadClass bypasses parent delegation and can cause security issues.

JAVA
package com.bank.classloading;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class BankingPluginClassLoader extends ClassLoader {
    private final Path pluginDirectory;

    public BankingPluginClassLoader(Path pluginDirectory, ClassLoader parent) {
        super(parent);
        this.pluginDirectory = pluginDirectory;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // Convert com.bank.plugin.InterestCalculator to
        // com/bank/plugin/InterestCalculator.class
        String fileName = name.replace('.', '/') + ".class";
        Path classFile = pluginDirectory.resolve(fileName);

        System.out.println("  [PluginClassLoader] Loading: " + name);
        System.out.println("  [PluginClassLoader] From:    " + classFile);

        if (!Files.exists(classFile)) {
            throw new ClassNotFoundException("Plugin class not found: " + name);
        }

        try {
            byte[] bytecode = Files.readAllBytes(classFile);
            System.out.println("  [PluginClassLoader] Bytecode size: " + bytecode.length + " bytes");
            return defineClass(name, bytecode, 0, bytecode.length);
        } catch (IOException e) {
            throw new ClassNotFoundException("Failed to read plugin: " + name, e);
        }
    }

    public static void main(String[] args) {
        // Demonstrate the custom ClassLoader concept
        System.out.println("BankingPluginClassLoader created");
        System.out.println("  Plugin directory: /opt/bank/plugins");
        System.out.println("  Parent: " + ClassLoader.getSystemClassLoader());
        System.out.println();
        System.out.println("How it works:");
        System.out.println("  1. loadClass() is called with the plugin class name");
        System.out.println("  2. Parent delegation: parent ClassLoader tries first");
        System.out.println("  3. Parent cannot find the plugin class (not on classpath)");
        System.out.println("  4. findClass() is called on our custom ClassLoader");
        System.out.println("  5. We read the .class file from the plugin directory");
        System.out.println("  6. defineClass() converts bytes into a Class object");
        System.out.println("  7. The plugin class is now loaded and ready to use");
    }
}
TEXT
Expected output:
BankingPluginClassLoader created
  Plugin directory: /opt/bank/plugins
  Parent: jdk.internal.loader.ClassLoaders$AppClassLoader@251a69d7

How it works:
  1. loadClass() is called with the plugin class name
  2. Parent delegation: parent ClassLoader tries first
  3. Parent cannot find the plugin class (not on classpath)
  4. findClass() is called on our custom ClassLoader
  5. We read the .class file from the plugin directory
  6. defineClass() converts bytes into a Class object
  7. The plugin class is now loaded and ready to use

What are common mistakes with class loading?

The most common mistake is breaking the parent delegation model by overriding loadClass instead of findClass.

Wrong: overriding loadClass and breaking parent delegation

JAVA
package com.bank.classloading;

public class WrongClassLoaderDemo {
    public static void main(String[] args) {
        System.out.println("WRONG: Overriding loadClass()");
        System.out.println();
        System.out.println("  // This BREAKS parent delegation");
        System.out.println("  @Override");
        System.out.println("  public Class<?> loadClass(String name) {");
        System.out.println("      // Tries to load EVERYTHING itself, including java.lang.Object");
        System.out.println("      byte[] bytes = readBytecode(name);");
        System.out.println("      return defineClass(name, bytes, 0, bytes.length);");
        System.out.println("  }");
        System.out.println();
        System.out.println("Problems:");
        System.out.println("  1. Tries to load java.lang.Object itself (SecurityException)");
        System.out.println("  2. Core JDK classes could be replaced by malicious code");
        System.out.println("  3. Same class loaded by two ClassLoaders becomes two different types");
        System.out.println("  4. ClassCastException even though the class name looks the same");
    }
}
TEXT
Expected output:
WRONG: Overriding loadClass()

  // This BREAKS parent delegation
  @Override
  public Class<?> loadClass(String name) {
      // Tries to load EVERYTHING itself, including java.lang.Object
      byte[] bytes = readBytecode(name);
      return defineClass(name, bytes, 0, bytes.length);
  }

Problems:
  1. Tries to load java.lang.Object itself (SecurityException)
  2. Core JDK classes could be replaced by malicious code
  3. Same class loaded by two ClassLoaders becomes two different types
  4. ClassCastException even though the class name looks the same

Correct: overriding findClass to preserve parent delegation

JAVA
package com.bank.classloading;

public class CorrectClassLoaderDemo {
    public static void main(String[] args) {
        System.out.println("CORRECT: Overriding findClass()");
        System.out.println();
        System.out.println("  // This PRESERVES parent delegation");
        System.out.println("  @Override");
        System.out.println("  protected Class<?> findClass(String name) throws ClassNotFoundException {");
        System.out.println("      // Only called if the parent could not load the class");
        System.out.println("      byte[] bytes = readPluginBytecode(name);");
        System.out.println("      return defineClass(name, bytes, 0, bytes.length);");
        System.out.println("  }");
        System.out.println();
        System.out.println("Benefits:");
        System.out.println("  1. Parent loads core JDK classes as expected");
        System.out.println("  2. Our ClassLoader only loads classes the parent cannot find");
        System.out.println("  3. No security risk of replacing java.lang.String");
        System.out.println("  4. No duplicate class issues across ClassLoaders");
    }
}
TEXT
Expected output:
CORRECT: Overriding findClass()

  // This PRESERVES parent delegation
  @Override
  protected Class<?> findClass(String name) throws ClassNotFoundException {
      // Only called if the parent could not load the class
      byte[] bytes = readPluginBytecode(name);
      return defineClass(name, bytes, 0, bytes.length);
  }

Benefits:
  1. Parent loads core JDK classes as expected
  2. Our ClassLoader only loads classes the parent cannot find
  3. No security risk of replacing java.lang.String
  4. No duplicate class issues across ClassLoaders

Another common mistake is depending on static initialization order across classes without understanding when initialization happens.

Wrong: assuming a static field in another class is initialized

JAVA
package com.bank.classloading;

import java.math.BigDecimal;

public class WrongInitOrderDemo {
    // WRONG: This field depends on LoanConfig.MAX_AMOUNT,
    // but if LoanConfig fails to initialize, this class also fails.
    static BigDecimal SAFE_LIMIT;

    static {
        try {
            SAFE_LIMIT = LoanConfig.MAX_AMOUNT.multiply(new BigDecimal("0.8"));
            System.out.println("SAFE_LIMIT = " + SAFE_LIMIT);
        } catch (Throwable t) {
            System.out.println("WRONG: Static init failed because LoanConfig failed");
            System.out.println("  Error: " + t.getClass().getSimpleName() + ": " + t.getMessage());
            SAFE_LIMIT = BigDecimal.ZERO;
        }
    }

    public static void main(String[] args) {
        System.out.println("SAFE_LIMIT = " + SAFE_LIMIT);
    }
}

class LoanConfig {
    static BigDecimal MAX_AMOUNT = new BigDecimal("5000000.00");

    static {
        System.out.println("LoanConfig initialized: MAX_AMOUNT = " + MAX_AMOUNT);
    }
}
TEXT
Expected output:
LoanConfig initialized: MAX_AMOUNT = 5000000.00
SAFE_LIMIT = 4000000.00
SAFE_LIMIT = 4000000.00

Correct: use lazy initialization for cross-class dependencies

JAVA
package com.bank.classloading;

import java.math.BigDecimal;

public class CorrectInitOrderDemo {
    // CORRECT: Compute the value lazily, not in a static block
    static BigDecimal getSafeLimit() {
        return LoanConfig2.MAX_AMOUNT.multiply(new BigDecimal("0.8"));
    }

    public static void main(String[] args) {
        System.out.println("CORRECT: Lazy computation avoids static init dependency");
        System.out.println("SAFE_LIMIT = " + getSafeLimit());
    }
}

class LoanConfig2 {
    static BigDecimal MAX_AMOUNT = new BigDecimal("5000000.00");

    static {
        System.out.println("LoanConfig2 initialized: MAX_AMOUNT = " + MAX_AMOUNT);
    }
}
TEXT
Expected output:
CORRECT: Lazy computation avoids static init dependency
LoanConfig2 initialized: MAX_AMOUNT = 5000000.00
SAFE_LIMIT = 4000000.00

What is a complete banking project using a custom ClassLoader?

This project builds a plugin system for National Bank of India. The bank loads interest-calculation plugins at runtime from a separate directory, so different branches can have different interest rates without redeploying the core application.

Project structure

DIAGRAM
banking-plugin-system/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── com/
                └── bank/
                    ├── plugin/
                    │   ├── BankingPlugin.java           (interface)
                    │   └── PluginClassLoader.java        (custom classloader)
                    ├── plugins/
                    │   ├── SavingsInterestPlugin.java    (plugin implementation)
                    │   └── FixedDepositPlugin.java       (plugin implementation)
                    └── PluginManagerApp.java              (main class)

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
    syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>

    syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
    syn-kw"><artifactIdsyn-kw">>banking-plugin-systemsyn-kw"></artifactIdsyn-kw">>
    syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>
    syn-kw"><packagingsyn-kw">>jarsyn-kw"></packagingsyn-kw">>

    syn-kw"><propertiessyn-kw">>
        syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
        syn-kw"><maven.compiler.sourcesyn-kw">>25syn-kw"></maven.compiler.sourcesyn-kw">>
        syn-kw"><maven.compiler.targetsyn-kw">>25syn-kw"></maven.compiler.targetsyn-kw">>
    syn-kw"></propertiessyn-kw">>
syn-kw"></projectsyn-kw">>

BankingPlugin.java

JAVA
package com.bank.plugin;

import java.math.BigDecimal;

public interface BankingPlugin {
    String getPluginName();
    BigDecimal calculate(String accountId, BigDecimal principal, int tenureMonths);
}

PluginClassLoader.java

JAVA
package com.bank.plugin;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class PluginClassLoader extends ClassLoader {
    private final Path pluginDir;

    public PluginClassLoader(Path pluginDir) {
        super(ClassLoader.getSystemClassLoader());
        this.pluginDir = pluginDir;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String path = name.replace('.', '/') + ".class";
        Path classFile = pluginDir.resolve(path);

        if (!Files.exists(classFile)) {
            throw new ClassNotFoundException("Plugin not found: " + name + " at " + classFile);
        }

        try {
            byte[] bytecode = Files.readAllBytes(classFile);
            System.out.println("  [PluginClassLoader] Loaded " + name + " (" + bytecode.length + " bytes)");
            return defineClass(name, bytecode, 0, bytecode.length);
        } catch (IOException e) {
            throw new ClassNotFoundException("Failed to read: " + name, e);
        }
    }
}

SavingsInterestPlugin.java

JAVA
package com.bank.plugins;

import com.bank.plugin.BankingPlugin;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class SavingsInterestPlugin implements BankingPlugin {
    private static final BigDecimal ANNUAL_RATE = new BigDecimal("0.04"); // 4% per annum

    @Override
    public String getPluginName() {
        return "Savings Account Interest Calculator";
    }

    @Override
    public BigDecimal calculate(String accountId, BigDecimal principal, int tenureMonths) {
        // Simple interest: P * R * T / 12
        BigDecimal interest = principal
            .multiply(ANNUAL_RATE)
            .multiply(new BigDecimal(tenureMonths))
            .divide(new BigDecimal("12"), 2, RoundingMode.HALF_UP);
        System.out.println("  [SavingsInterestPlugin] Account " + accountId
            + ": principal=" + principal + ", months=" + tenureMonths
            + ", interest=" + interest);
        return interest;
    }
}

FixedDepositPlugin.java

JAVA
package com.bank.plugins;

import com.bank.plugin.BankingPlugin;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class FixedDepositPlugin implements BankingPlugin {
    private static final BigDecimal ANNUAL_RATE = new BigDecimal("0.075"); // 7.5% per annum

    @Override
    public String getPluginName() {
        return "Fixed Deposit Interest Calculator";
    }

    @Override
    public BigDecimal calculate(String accountId, BigDecimal principal, int tenureMonths) {
        // Compound interest: P * (1 + R/12)^T - P
        BigDecimal monthlyRate = ANNUAL_RATE.divide(new BigDecimal("12"), 10, RoundingMode.HALF_UP);
        BigDecimal base = BigDecimal.ONE.add(monthlyRate);
        BigDecimal compounded = principal.multiply(base.pow(tenureMonths));
        BigDecimal interest = compounded.subtract(principal).setScale(2, RoundingMode.HALF_UP);
        System.out.println("  [FixedDepositPlugin] Account " + accountId
            + ": principal=" + principal + ", months=" + tenureMonths
            + ", interest=" + interest);
        return interest;
    }
}

PluginManagerApp.java

JAVA
package com.bank;

import com.bank.plugin.BankingPlugin;
import com.bank.plugin.PluginClassLoader;

import java.math.BigDecimal;
import java.nio.file.Path;

public class PluginManagerApp {
    public static void main(String[] args) throws Exception {
        System.out.println("National Bank of India - Plugin Manager");
        System.out.println("========================================");
        System.out.println();

        // In production, this path comes from configuration
        Path pluginDir = Path.of("/opt/bank/plugins");
        PluginClassLoader loader = new PluginClassLoader(pluginDir);

        // Simulating runtime plugin loading
        // In this demo, we load classes that are on the classpath
        // In production, they would be in the plugin directory
        String[] pluginNames = {
            "com.bank.plugins.SavingsInterestPlugin",
            "com.bank.plugins.FixedDepositPlugin"
        };

        for (String pluginName : pluginNames) {
            System.out.println("Loading plugin: " + pluginName);
            try {
                Class<?> pluginClass = loader.loadClass(pluginName);
                BankingPlugin plugin = (BankingPlugin) pluginClass
                    .getDeclaredConstructor()
                    .newInstance();

                System.out.println("  Plugin name: " + plugin.getPluginName());
                System.out.println("  Loaded by:   " + pluginClass.getClassLoader());

                // Calculate interest for Rajesh's account
                BigDecimal interest = plugin.calculate(
                    "SAV2001", new BigDecimal("500000.00"), 12);
                System.out.println("  Result: " + interest + " INR");
                System.out.println();
            } catch (ClassNotFoundException e) {
                System.out.println("  Plugin not found: " + e.getMessage());
                System.out.println();
            }
        }

        System.out.println("All plugins processed.");
    }
}
TEXT
Expected output:
National Bank of India - Plugin Manager
========================================

Loading plugin: com.bank.plugins.SavingsInterestPlugin
  Plugin name: Savings Account Interest Calculator
  Loaded by:   jdk.internal.loader.ClassLoaders$AppClassLoader@251a69d7
  [SavingsInterestPlugin] Account SAV2001: principal=500000.00, months=12, interest=20000.00
  Result: 20000.00 INR

Loading plugin: com.bank.plugins.FixedDepositPlugin
  Plugin name: Fixed Deposit Interest Calculator
  Loaded by:   jdk.internal.loader.ClassLoaders$AppClassLoader@251a69d7
  [FixedDepositPlugin] Account SAV2001: principal=500000.00, months=12, interest=38803.43
  Result: 38803.43 INR

All plugins processed.

How to run the project

BASH
# Step 1: Build the project
cd banking-plugin-system
mvn clean package

# Step 2: Run the plugin manager
java -cp target/classes com.bank.PluginManagerApp

# Step 3: To test with external plugins:
# Compile a plugin separately and place .class files in /opt/bank/plugins/
mkdir -p /opt/bank/plugins/com/bank/plugins
javac -d /opt/bank/plugins src/main/java/com/bank/plugins/SavingsInterestPlugin.java
java -cp target/classes com.bank.PluginManagerApp

What should a senior or principal engineer know?

At the senior level, you should understand class loading deeply enough to diagnose classloader leaks, resolve duplicate class conflicts, and configure module boundaries.

  • Metaspace: Since Java 8, class metadata is stored in native memory (metaspace), not the permanent generation. Monitor metaspace usage with -XX:MaxMetaspaceSize and JMX metrics. Classloader leaks fill metaspace and crash the JVM with OutOfMemoryError: Metaspace.
  • Classloader leaks: A class cannot be garbage collected until its ClassLoader is garbage collected. If you hold a reference to a Class or an instance, the entire ClassLoader and all its classes stay in memory. This is common in application servers that redeploy WARs.
  • Thread context ClassLoader: Each thread has a context ClassLoader set by Thread.setContextClassLoader(). Frameworks like JDBC, JNDI, and Spring use it to load classes. If you create threads in a pool, they inherit the parent thread's context ClassLoader.
  • Module system (Java 9+): The module system adds a layer on top of ClassLoaders. Each module belongs to a module layer, and each layer has its own ClassLoader. The bootstrap ClassLoader loads java.base, and other modules are loaded by the platform or application ClassLoader depending on their layer.
  • ServiceLoader and SPI: The ServiceLoader API uses the thread context ClassLoader to discover service implementations. This is how JDBC drivers are loaded automatically since Java 6.
  • Class data sharing (CDS): Java 10+ can share class metadata across JVM instances to reduce startup time. Application CDS (AppCDS) in Java 13+ can include application classes.
JAVA
package com.bank.classloading;

import java.lang.management.ManagementFactory;
import java.lang.management.ClassLoadingMXBean;

public class SeniorClassLoadingDemo {
    public static void main(String[] args) {
        ClassLoadingMXBean classLoadingBean = ManagementFactory.getClassLoadingMXBean();

        System.out.println("=== Class Loading Metrics ===");
        System.out.println("Currently loaded classes: " + classLoadingBean.getLoadedClassCount());
        System.out.println("Total loaded since start: " + classLoadingBean.getTotalLoadedClassCount());
        System.out.println("Total unloaded:           " + classLoadingBean.getUnloadedClassCount());
        System.out.println();

        // Thread context ClassLoader
        System.out.println("=== Thread Context ClassLoader ===");
        ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
        System.out.println("Main thread context CL: " + contextCL);
        System.out.println();

        // Module information (Java 9+)
        System.out.println("=== Module Information ===");
        Module stringModule = String.class.getModule();
        System.out.println("String module: " + stringModule.getName());
        System.out.println("String module layer: " + stringModule.getLayer());

        Module ourModule = SeniorClassLoadingDemo.class.getModule();
        System.out.println("Our module: " + ourModule.getName());
        System.out.println("  (null name means unnamed module, the default for classpath code)");
        System.out.println();

        // Senior checklist
        System.out.println("=== Senior/Principal Checklist ===");
        System.out.println("1. Monitor metaspace: -XX:MaxMetaspaceSize, ClassLoadingMXBean");
        System.out.println("2. Classloader leaks: holding Class or instance references prevents GC");
        System.out.println("3. Thread context CL: used by JDBC, JNDI, Spring for SPI loading");
        System.out.println("4. Module system: modules add encapsulation on top of classloaders");
        System.out.println("5. AppCDS: share class metadata across JVM instances for fast startup");
        System.out.println("6. OSGi/JPMS: use module layers for hot-swappable plugin architectures");
    }
}
TEXT
Expected output:
=== Class Loading Metrics ===
Currently loaded classes: 487
Total loaded since start: 487
Total unloaded:           0

=== Thread Context ClassLoader ===
Main thread context CL: jdk.internal.loader.ClassLoaders$AppClassLoader@251a69d7

=== Module Information ===
String module: java.base
String module layer: boot
Our module: null
  (null name means unnamed module, the default for classpath code)

=== Senior/Principal Checklist ===
1. Monitor metaspace: -XX:MaxMetaspaceSize, ClassLoadingMXBean
2. Classloader leaks: holding Class or instance references prevents GC
3. Thread context CL: used by JDBC, JNDI, Spring for SPI loading
4. Module system: modules add encapsulation on top of classloaders
5. AppCDS: share class metadata across JVM instances for fast startup
6. OSGi/JPMS: use module layers for hot-swappable plugin architectures

What are common interview follow-up questions?

  • Can two classes with the same fully qualified name coexist in the JVM? (Yes, if they are loaded by different ClassLoaders. Each ClassLoader defines its own namespace.)
  • What happens if a class is loaded by two different ClassLoaders? (The JVM treats them as two different types. Casting one to the other throws ClassCastException.)
  • What is the difference between Class.forName() and ClassLoader.loadClass()? (Class.forName() loads and initializes the class. ClassLoader.loadClass() loads but does not initialize it.)
  • Can you unload a class in Java? (Not directly. A class is garbage collected only when its ClassLoader is garbage collected and no references to the Class or its instances exist.)
  • What is the difference between the Platform ClassLoader and the Extension ClassLoader? (Same concept, different names. Extension ClassLoader was used before Java 9. Platform ClassLoader is the Java 9+ name.)
  • Why does JDBC use Class.forName() to load drivers? (Before Java 6, JDBC drivers needed explicit loading with Class.forName("com.mysql.cj.jdbc.Driver") because the static block registered the driver. Since Java 6, the ServiceLoader mechanism loads drivers automatically.)
  • How does Spring Boot load classes from embedded JARs? (Spring Boot uses a custom ClassLoader called LaunchedURLClassLoader that can read nested JARs inside the fat JAR.)

Visual Overview

DIAGRAM
 Class Loading Phases
 ======================

 ┌──────────────────────────────────────────────────────────────┐
 │                     Phase 1: LOADING                         │
 │  Read .class bytecode from source (disk, JAR, network)      │
 │  Create java.lang.Class object in method area               │
 └──────────────────────────┬───────────────────────────────────┘
                            │
                            ▼
 ┌──────────────────────────────────────────────────────────────┐
 │                     Phase 2: LINKING                         │
 │                                                              │
 │  ┌──────────────────┐                                        │
 │  │ 2a. Verification │ Check bytecode format and safety       │
 │  └────────┬─────────┘                                        │
 │           ▼                                                  │
 │  ┌──────────────────┐                                        │
 │  │ 2b. Preparation  │ Allocate static fields, set defaults   │
 │  │                  │ int=0, Object=null, boolean=false      │
 │  └────────┬─────────┘                                        │
 │           ▼                                                  │
 │  ┌──────────────────┐                                        │
 │  │ 2c. Resolution   │ Symbolic refs to direct pointers       │
 │  └──────────────────┘                                        │
 └──────────────────────────┬───────────────────────────────────┘
                            │
                            ▼
 ┌──────────────────────────────────────────────────────────────┐
 │                  Phase 3: INITIALIZATION                     │
 │  Run <clinit>: static blocks + static field assignments     │
 │  Execute in source code order, top to bottom                │
 └──────────────────────────────────────────────────────────────┘


 ClassLoader Hierarchy (Parent Delegation)
 ==========================================

 ┌──────────────────────────────────┐
 │     Bootstrap ClassLoader        │  Loads: java.lang, java.util
 │     (native code, shows null)    │  Source: java.base module
 └───────────────┬──────────────────┘
                 │ parent
                 ▼
 ┌──────────────────────────────────┐
 │     Platform ClassLoader         │  Loads: java.sql, java.xml
 │     (Java 9+ name)               │  Source: platform modules
 └───────────────┬──────────────────┘
                 │ parent
                 ▼
 ┌──────────────────────────────────┐
 │     Application ClassLoader      │  Loads: your classes
 │     (System ClassLoader)         │  Source: classpath, module path
 └───────────────┬──────────────────┘
                 │ parent
                 ▼
 ┌──────────────────────────────────┐
 │     Custom ClassLoader           │  Loads: plugins, hot-loaded code
 │     (your subclass)              │  Source: database, network, files
 └──────────────────────────────────┘


 Parent Delegation Flow
 =======================

  loadClass("com.bank.plugins.InterestPlugin")
        │
        ▼
  Custom CL: "Can my parent load this?"
        │
        ▼
  App CL: "Can my parent load this?"
        │
        ▼
  Platform CL: "Can my parent load this?"
        │
        ▼
  Bootstrap CL: "Not in java.base." (fail)
        │
        ▼
  Platform CL: "Not in platform modules." (fail)
        │
        ▼
  App CL: "Not on classpath." (fail)
        │
        ▼
  Custom CL: "Found it in /opt/bank/plugins!" (success)
        │
        ▼
  defineClass() creates the Class object

Key Takeaway

Class loading is the JVM mechanism that reads compiled .class bytecode and makes it available for your application to use. It happens on demand: the first time your code references a class, the JVM triggers the three-phase process of loading, linking, and initialization. Loading reads the bytecode and creates a Class object. Linking verifies the bytecode for safety, sets static fields to their default values (zero, null, false), and resolves symbolic references to direct memory pointers. Initialization runs the static blocks and assigns the actual values you wrote in your source code.

The ClassLoader hierarchy is a three-level chain: the bootstrap ClassLoader loads core JDK classes like java.lang.String from the java.base module, the platform ClassLoader loads shared modules like java.sql, and the application ClassLoader loads your project classes from the classpath. Each ClassLoader delegates to its parent first, so your code can never accidentally replace a core JDK class. This parent delegation model is a security feature built into the JVM since Java 1.2.

In our National Bank of India banking plugin project, we built a custom ClassLoader that loads interest-calculation plugins from a separate directory. The SavingsInterestPlugin calculates simple interest at 4% per annum, and the FixedDepositPlugin calculates compound interest at 7.5%. The PluginClassLoader extends ClassLoader, overrides findClass (not loadClass, to preserve parent delegation), reads the .class bytes from disk, and calls defineClass to create the Class object. This pattern lets different bank branches deploy different plugins without redeploying the core application.

At the senior level, monitor metaspace usage with ClassLoadingMXBean and set -XX:MaxMetaspaceSize to prevent runaway class loading from crashing the JVM. Watch for ClassLoader leaks: if you hold a reference to a Class or its instance, the entire ClassLoader and all its classes stay in memory. Understand the thread context ClassLoader, because JDBC, JNDI, and Spring use it for service provider loading. At the principal level, design module layers for hot-swappable plugins, use AppCDS for faster startup, and plan ClassLoader hierarchies that isolate tenant code in multi-tenant systems.

Remember one sentence: the JVM loads classes on demand through a three-level ClassLoader hierarchy that delegates to its parent first, then links through verification, preparation, and resolution, and finally initializes by running static blocks in source code order.

---

Share
Use ← → arrow keys to navigate