By Pankaj Kumar
java.lang.ClassNotFoundException
are using Class.forName
or ClassLoader.loadClass
to load a class by passing String name of a class and it’s not found on the classpath.Class.forName
but forget to add it’s jar file in the classpath.Let’s look at a simple example where we will get ClassNotFoundException
.
package com.journaldev.exceptions;
public class DataTest {
public static void main(String[] args) {
try {
Class.forName("com.journaldev.MyInvisibleClass");
ClassLoader.getSystemClassLoader().loadClass("com.journaldev.MyInvisibleClass");
ClassLoader.getPlatformClassLoader().loadClass("com.journaldev.MyInvisibleClass");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Note that com.journaldev.MyInvisibleClass
doesn’t exist, so When we execute above program, we get following exception stack trace.
java.lang.ClassNotFoundException: com.journaldev.MyInvisibleClass
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:292)
at com.journaldev.exceptions.DataTest.main(DataTest.java:7)
In above example, all the three statements will throw java.lang.ClassNotFoundException
.
It’s very easy to fix ClassNotFoundException because the exception stack trace clearly specifies the class not found. Just check for classpath settings and make sure class it’s present at runtime.
NoClassDefFoundError
is a runtime error thrown when a class is not found at runtime. It’s very similar to ClassNotFoundException
. Read more at Java NoClassDefFoundError. Reference: API Doc
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.