Class Loader
TL;DR
- The Class Loader Subsystem is responsible for loading
.classfiles into the JVM’s memory (specifically the Method Area) at runtime. - It performs three main phases: Loading, Linking, and Initialization.
- Java uses a Delegation Hierarchy to load classes securely.
Concept
When you write new Student(), the JVM needs the blueprint for Student. If it hasn’t loaded it yet, the Class Loader takes over.
1. Loading
The Class Loader searches the file system, network, or JAR files for Student.class. Once found, it creates a java.lang.Class object in the Heap representing this class.
2. Linking
- Verification: The Bytecode Verifier checks if the
.classfile is valid and hasn’t been maliciously altered. - Preparation: Allocates memory for
staticvariables and assigns them default values (e.g.,static int countbecomes 0). - Resolution: Replaces symbolic references in the bytecode with direct, physical memory references.
3. Initialization
This is where static variables are assigned their actual values (e.g., static int count = 5), and static {} initialization blocks are executed.
Examples
public class ClassLoaderExample {
// Preparation Phase: This is allocated as '0'
// Initialization Phase: This is assigned '100'
static int configValue = 100;
static {
// Initialization Phase: This block runs ONCE when the class is loaded
System.out.println("ClassLoader is initializing this class!");
}
public static void main(String[] args) {
System.out.println("Main method executing.");
// Output:
// ClassLoader is initializing this class!
// Main method executing.
}
}
Interview Questions
Q: When exactly does a Class Loader load a class?
A: Classes are loaded dynamically on demand (Lazy Loading), not all at once when the application starts. A class is loaded the very first time it is referenced in the code—either by instantiating it (new Object()), invoking a static method (Math.max()), or accessing a static field.
Q: Can you create your own Custom Class Loader?
A: Yes. You can extend java.lang.ClassLoader and override the findClass() method. This is extremely useful if you need to load classes from non-standard locations, such as downloading .class files securely over an encrypted network connection, extracting them from a proprietary encrypted archive, or generating bytecode entirely on-the-fly at runtime.