How to Solve java.lang.ClassNotFoundException in Java?
ClassNotFoundException is a checked exception and occurs when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath.
In older days, there are no editors like Eclipse are available. Even in Notepad, people have done java coding and by using the “javac” command to compile the java files, and they will create a ‘.class’ file. Sometimes accidentally the generated class files might be lost or set in different locations and hence there are a lot of chances of “ClassNotFoundException” occurs. After the existence of editors like Eclipse, Netbeans, etc., IDE creates a “ClassPath” file kind of entries.
From the above image, we can see that many jar files are present. They are absolutely necessary if the java code wants to interact with MySQL, MongoDB, etc., kind of databases, and also few functionalities need these jar files to be present in the build path. If they are not added, first editors show the errors themselves and provide the option of corrections too.
Implementation: Sample program of connecting to MySQL database and get the contents
Case 1: In the above code, we are using com.mysql.cj.jdbc.Driver and in that case if we are not having mysql-connector-java-8.0.22.jar, then we will be getting ClassNotFoundException.
Case 2: So, keep the jar in the build path as shown below.
Note: Similarly for any database connectivity, we need to have the respective jars for connecting to that database. The list of database driver jars required by java to overcome ClassNotFoundException is given below in a tabular format
- When we are developing Web based applications, the jars must be present in ‘WEB-INF/lib directory’.
- In Maven projects, jar dependency should be present in pom.xml
- Sample snippet of pom.xml for spring boot
Example 1 With Spring boot
Example 2 Without spring boot
Example 3 Gradle based dependencies (MongoDB)
Similarly, other DB drivers can be specified in this way. It depends upon the project nature, the dependencies has to be fixed. For ordinary class level projects, all the classes i.e parent class, child class, etc should be available in the classpath. If there are errors, then also .class file will not be created which leads to ClassNotFoundException, and hence in order to get the whole code working, one should correct the errors first by fixing the dependencies. IDE is much helpful to overcome such sort scenarios such as when the program throws ClassNotFoundException, it will provide suggestions to users about the necessity of inclusion of jar files(which contains necessary functionalities like connecting to database.
Please Login to comment...