Basics of ClassLoaders in Java

The Classloaders in Java dynamically load Java classes into the Java Virtual Machine. Usually classes are only loaded on demand.

By default, Java uses three class loaders, when JVM starts.

  1. Bootstrap classloader
  2. Extension classloader
  3. System classloader

Following figure shows the role of each ClassLoader:-


The ClassLoaders in Java works on 3 Principles:-

  1. Delegation – Forward request of class loading to the parent ClassLoader and only load the Class if the parent is not able to find or load the Class.
  2. Visibility – Allows child ClassLoaders to see all the Classes loaded by the parent ClassLoader. But parent ClassLoader cannot see the Classes loaded by the child ClassLoader.
  3. Uniqueness – Allows to load a Class exactly once, which is basically achieved by delegation and ensures that child ClassLoader does not reload the same Class already loaded by the parent ClassLoader.


Let us see a simple Java program to print the ClassLoader of the Class.

public class MyClass {
 public static void main(String[] args) {
 //Get the ClassLoader of the class MyClass
 ClassLoader classLoader = MyClass.class.getClassLoader();
 //Get the parent ClassLoader of classLoader
 ClassLoader parentClassLoader = classLoader.getParent();
 //Get the super ClassLoader, This will return null as we are trying
 //to get the Bootstrap ClassLoader 
 ClassLoader superClassLoader = parentClassLoader.getParent();

 //This will return null as we are trying to get the ClassLoader 
 // of the core Java Runtime Class, which is Bootstrap ClassLoader
 ClassLoader stringClassLoader = String.class.getClassLoader();


Running the above Class, produces the following output:-





Leave a Reply

Your email address will not be published. Required fields are marked *