Error: Could not find or load main class
Programs written in Java programming language need a main() method to be run/executed because it is where the program execution begins. Occasionally when you run a Java program, you might see the error "Could not find or load main class" . You get this error because you are incorrectly trying to run the main() inside the class using java command.
Reasons to Occur Error :
- File Extension
- Wrong package
- Invalid Classpath
- Wrong Class Name
JAVA source code files (.java extension) are compiled into .CLASS file s using a Java compiler (javac command). A CLASS file contains bytecode that can be executed by the Java Virtual Machine (JVM). If your Java source code file name is MyClass.java, so your compiled code will be MyClass.class.
You will get that error if you call it using:
Instead, use this:
A package in Java is used to group related classes . Java packages are use to avoid name conflicts, and to write a better maintainable code. To run a Java class which is in a package, we must provide its fully qualified name . When the Main class is inside a package then you need to run it as follows :
You will get "Error: Could not find or load main class MainClassName" . This is because it must be called with its fully qualified class name:
Here you can see, the name of this class is not MainClassName, It's packageName.MainClassName . Attempting to execute MainClassName does not work, because no class having that name exists. Not on the current classpath anyway.
The classpath is the path where the Java Virtual Machine look for user-defined classes, packages and resources in Java programs . If you have declared the classname correctly but are still shown the same error, chances are that Java command could not find the specified classname at the path. So, first you must ensure that you add the location of your .class file to your classpath. So, if its in the current folder, add . (dot) to your classpath.
For example, if your class file "MyClass" is saved in the following directory d:\temp
In this example, . (dot) meaning the current directory, is the entirety of classpath.
If you're running it from command prompt , you need to make sure your classpath is correct. If you set it already, you need to restart your terminal to reload your system variables.
Wrong Class Name
Sometimes this error happens because your Java file name (.java) and the main class name are different.
If you save the above program in a "sample.java" file and compile it, the compiler generate "MyClass.class" file and not "sample.class".
When you run
It failed with the error "Could not find or load main class sample ".
So, you have to call