Junior — Middle
Can you explain how Java classes are loaded during program execution?
sobes.tech AI
Answer from AI
Loading Java classes is performed using a special JVM component — the class loader (ClassLoader). When a program accesses a class for the first time, the ClassLoader searches for the corresponding bytecode file (.class) in specific locations (for example, in the classpath), loads it into memory, and converts it into a data structure understandable by the JVM.
The loading process includes three main stages:
- Loading — reading the class bytecode and creating a Class object.
- Linking — verifying correctness, preparing (allocating memory for static fields), and resolving symbols.
- Initialization — executing static blocks and initializing static variables.
Example: when calling Class.forName("com.example.MyClass"), the class MyClass is loaded and initialized.
There are also different types of loaders: Bootstrap ClassLoader (loads core Java classes), Extension ClassLoader, and System/Application ClassLoader, which operate hierarchically.