ClassLoader Java
Well, first let’s consider what is a ClassLoader. Basically, when we are compiling the java source code, it is being converted into a byte code. This .class file is loaded into the memory when we are trying to use the class in our program. This also involves 3 phases, loading, linking, and initialization. Let’s have a look at these three phases.
ClassLoader in Java
Loading →
Well, usually, the first class to be loaded into the memory is the class that contains the main() method. The class loader reads the byte code, and stores some information like –
- name of the class
- information about variables, methods
- whether the byte code is related to an interface, or Class, or enum, etc.
This information is stored in the method area by the JVM. There are three class loaders available, which are the Bootstrap classloader, Extension classloader, and application class loader.
Let’s have a very brief look at what these class loaders do –
Bootstrap Class loader: The bootstrap class loader is the root class loader, which helps in loading the standard java packages, like java.io, java.lang, and so on(these are present in the rt.jar file). This loader has got the highest priority.
Extension Class loader: The extension class loader helps load the extensions of the standard java libraries.
Application Classloader: The application class loader is used to load the files present on the classpath.
Now, let’s get to the next part, which is linking. Once the class is loaded into the memory, the linking process is done. In this, the different elements and other dependencies are combined together. In the linking process, different things are done, like verification, preparation, and resolution.
In the verification phase, the byte code is verified to check whether or not it is proper in accordance with certain rules and constraints. If it is not found to be proper, it is a verification error.
In the preparation phase, memory is allocated for all the static fields for the class or interface, and they are initialized with their default values. Like if you are having a static field of type int, then it is going to have a default value of 0.
In the resolution phase, the symbolic references are replaced with direct references. It is easy to understand. The class contains some different components, like variables, methods, class, etc, which are converted to symbols. When JVM is executing the program, it uses symbolic references to locate the components.
So, resolving is converting these symbolic references to actual/direct references.
Next comes the initialization, in which, some different things are done, like executing the static block, assigning values to the static fields, etc. Like if we have a static variable created of type int, it is initially going to hold 0, as the default value. But if we have set it to 10, the value is now going to be assigned to the variable in the initialization phase.