sneppets-java8

Error: Could Not Find Or Load Main Class

The most common error that new Java developers would experience while running java program is “Could Not Find Or Load Main Class“.

Command Prompt “Error : Could Not Find Or Load Main Class”

If you are running the java program from command prompt or terminal, then follow this section to resolve this error. Let’s consider the following Hello Java program. Note, we don’t have any package declaration in this Java file.

public class Hello {

    public static void main(String[] args) {

        System.out.println("Hello");
		
    }
	
}

Try compiling the java source code and run.

E:\Sneppets>javac Hello.java

E:\Sneppets>java hello
Error: Could not find or load main class hello
Caused by: java.lang.NoClassDefFoundError: Hello (wrong name: hello)

Check whether you had typed class name wrongly (in this case it should be “java Hello” instead of “java hello“.

E:\Sneppets>java Hello
Hello

If the above solution did not solve the problem, then check whether you had any package declaration in your java code as shown below and class files are generated properly in that subfolder (example)

With Package Declaration

package example;

public class Hello {

    public static void main(String[] args) {

        System.out.println("Hello");
		
    }
	
}
E:\Sneppets>java Hello
Error: Could not find or load main class Hello
Caused by: java.lang.NoClassDefFoundError: example/Hello (wrong name: Hello)

To fix the above error use “-d” option which is used specify where to place generated class files.

E:\Sneppets>javac -d . Hello.java

The above command generate the class files under “E:/Sneppets/example” folder. And while running the java program you need to specify the correct package where the .class files are generated as shown below

E:\Sneppets>java example.Hello
Hello

Eclipse “Error : Could Not Find Or Load Main Class”

If you are running your project from Eclipse IDE and face this error, check your .classpath file of your java project and change the absolute paths to relative paths i.e., use relative paths.

If you face this error still, then clean your entire build path using Project -> Clean, which will discard all build results and states. Then try to rebuild from scratch. Once you re-build, try to run your main class now, the error should go away !

Further Reading

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments