Class.forName() vs ClassLoader.loadClass() in Java

In this post, we will learn the difference between "Class.forName()" and "ClassLoader.loadClass()"
in Java. This is a frequently asked question in Java interviews for beginners. Let's dive into it.

Difference between "Class.forName()" and "ClassLoader.loadClass()" in Java

Feature Class.forName() ClassLoader.loadClass()
Method Invocation Static method invoked on the Class class. Method invoked on an instance of the ClassLoader class.
Class Initialization Class is initialized during method invocation. Class is not initialized during method invocation.
Exception Handling Throws checked exception (ClassNotFoundException). Requires explicit exception handling (ClassNotFoundException).
Class Loading Mechanism Uses the default system class loader. Allows you to specify a custom class loader.
Recommended Usage Used when you have the fully qualified class name as a string and want to load and initialize the class dynamically at runtime. Used when you want more control over the class loading process or when using a custom class loader.


Comments