Could Not Find or Load Main Class in Java
It is very common to face errors and exceptions in the Java programming language. But some of the most popular and common errors are often faced by programmers who are new in programming. Among these errors, could not find or load main class in Java, is one of them that occurs usually. The error indicates that the java command failed to find or load the main class. It occurs when we try to run a program. When the error occurs, the JVM shows the following error message on the console:
The error is mostly generated when we incorrectly specify the class name at run time of the program.
Reasons to Occur Error
The error generates because the JVM fails to load the main class or package name. There are some other reasons that generate the same error, as follows:
Solution to the Error
To avoid or resolve the error, we need to specify the absolute package name or class name.
The main class is a class in which the main() method is defined. Let's create a program that generates and displays an error on the console.
We see that the above program compiles and runs, successfully. Let's generate the error that could not find or load main class in the above program. To generate and display the error, we have misspelled the class name while typing the java command java DemoClas.
It also occurs when we specify the .class extension at the end of the class name.
To avoid the error, do not write .class extension at the end of the class name while using the java command.
The error also occurs when we don't place the class in the correct folder. In the following image, we are not inside the demo folder where the class is located. It means the DemoClass.class file must be inside the directory C:\demo.
In the above program, let's create a package named com.javatpoint. It means, on compiling the following Java program the .class file will be generated inside the C:\demo\com\javatpoint\DemoClass.class.
Remember that if the class is inside a package, we must use the full class name, including the package name, in the java command.