Home » Core Java » class » How the class loader works

About Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

How the class loader works

In this example we shall show you how the class loader works. To see how the class loader works we have performed the following steps:

  • We have created three classes, A, B and C, that each one uses a static block to print a message. The code in a static block is executed when the class is loaded by the class loader.
  • We create a new instance of A class, then we get an object of B class, using the forName(String className) API method of Class and then we create a new C object and see the printed messages from the static blocks,

as described in the code snippet below.  

package com.javacodegeeks.snippets.core;


class A {

    static {

  System.out.println("Loading A");
    }
}


class B {

    static {

  System.out.println("Loading B");
    }
}


class C {

    static {

  System.out.println("Loading C");
    }
}

public class ClassLoader {

    public static void main(String[] args) {

  

  System.out.println("inside main");

  new A();

  System.out.println("inside main : After creating A");

  try {


Class.forName("B");

  } catch (ClassNotFoundException e) {


System.out.println("inside main : Couldn't find B");

  }

  System.out.println("inside main : After Class.forName("B")");

  new C();

  System.out.println("inside main : After creating C");

    }
}

Output:

inside main
Loading A
inside main : After creating A
inside main : Couldn't find B
inside main : After Class.forName("B")
Loading C
inside main : After creating C

  
This was an example of how the class loader works in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments