What is the difference between Class.forName() and ClassLoader.loadClass()?

Class.forName() and ClassLoader.loadClass() are both used to load classes dynamically at runtime, but they differ in how they handle class initialization. Class.forName() loads the class and immediately initializes it, whereas ClassLoader.loadClass() only loads the class into memory and postpones initialization until the class is actively used.

Key Points: • Class.forName() loads and initializes the class, executing static blocks and initializing static variables. • ClassLoader.loadClass() loads the class definition but delays initialization until the class is first accessed. • ClassLoader.loadClass() can improve startup performance when classes are loaded but may not be used immediately.

Example: Suppose a JDBC driver contains a static initialization block that registers itself with DriverManager. Using Class.forName() triggers the registration immediately, while loadClass() only loads the driver class without executing the registration logic until the class is initialized later.

Code Example:

public class Demo {

    static {
        System.out.println("Class Initialized");
    }
}

public class Main {

    public static void main(String[] args) throws Exception {

        // Loads and initializes the class
        Class.forName("Demo");

        // Loads only, initialization may occur later
        ClassLoader.getSystemClassLoader()
                   .loadClass("Demo");
    }
}

Interview Tip: A concise interview answer is: Class.forName() loads and initializes a class immediately, triggering static blocks and static variable initialization. ClassLoader.loadClass() only loads the class metadata and defers initialization until the class is actively used, making it useful when initialization can be delayed for performance reasons.