How to Fix java.lang.ClassNotFoundException in Java?
To Resolve ClassNotFoundException in Java, following JAR files are required for respective databases.
Database | Command Line |
---|---|
MySQL | mysql-connector-java-8.0.22.jar |
MongoDB | mongo-java-driver-3.12.7.jar |
SQL Server | sqljdbc4.jar |
MYSQL | sqljdbc.jar |
Oracle | oracle.jdbc.driver.oracledriver |
Note:
- 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.xmlSample snippet of pom.xml for spring boot
Sample snippet of pom.xml for Spring boot
Example – 1: With Spring boot
XML
<!-- Spring boot mongodb dependency --> < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-data-mongodb</ artifactId > </ dependency > |
Example – 2: Without spring boot
XML
<!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver --> < dependency > < groupId >org.mongodb</ groupId > < artifactId >mongodb-driver</ artifactId > < version >3.6.3</ version > </ dependency > |
Example – 3: Gradle based dependencies (MongoDB)
XML
dependencies { compile 'org.mongodb:mongodb-driver:3.2.2' } |
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.
How to Solve java.lang.ClassNotFoundException in Java?
In Java, java.lang.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. ClassNotFoundException should be handled with a try-catch block or using the throw keyword.
In older days, there are no editors like Eclipse are available. Even in Notepad, people have done Java coding 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 occurring. After the existence of editors like Eclipse, Netbeans, etc., IDE creates a ClassPath file kind of entry.