Difference Between Static and Dynamic Class Loading in Java

The major difference between static and dynamic class loading is that in static loading retrieval of class definition and instantiation of the object is done at compile time, while in dynamic loading classes are loaded at run time using Class.forName() method.

Static Class Loading: Creating objects and instance using new keyword is known as static class loading. Following is an example.

class TestClass {
  public static void main(String args[]) {
      TestClass tc = new TestClass();
  }
}

Dynamic Class Loading: Load classes using Class.forName() method. Dynamic class loading is done when class name is not known at compile time.

Syntax: Class.forName (String className);

Class.forName() static method returns the Class object associated with the class name. The string className can be supplied dynamically at run time. Once the class is dynamically loaded then class.newInstance() method returns an instance of the loaded class. Following is an example that demonstrates

// Example code to illustrate forName() method 
 
public class ForNameTest { 
    public static void main(String[] args) throws ClassNotFoundException { 
 
        // get the Class instance using forName method 
        Class obj = Class.forName("java.lang.String"); 
 
        System.out.print("obj is an object of class: " + obj.toString()); 
    } 
}
 
OUTPUT
======
obj is an object of class: class java.lang.String

Hope we have enjoyed reading this post. Please do write us if we have any suggestion/comment or come across any error on this page. Thank we for reading!


Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.