Error: Could not find or load main class in Java [Solved]

Error: Could not find or load main class HelloWorld comes when you are trying to run your Java program using java command with the main class as HelloWorld but Java is not able to find the class. In order to solve this error, you must know how Java find and loads the classes, that's a little bit complex topic for beginners, but we will touch the same base here. For the curious reader, I would suggest reading my post How Classpath works in Java, a must read for a beginner. For now, you just remember that there is an environment variable called CLASSPATH which includes directories where Java looks for all class files and if it doesn't find your main class there then it throws "Error: Could not find or load main class XXX", where XXX is the name of your main class.

Since many Java programmer is now started programming using Eclipse they face this issue when they first try to run their Java program from command line. In Eclipse, it's easy to compile and run the program because Eclipse takes care of all Classpath setup, but when you run your Java program from command line, CLASSPATH environment variable comes in picture.

Personally, I don't like this environment variable and doesn't define in my environment variable, because its confusing and source of so many classpath related issue. Instead, I use -cp or -classpath option with java command to run my program. This way you always know which JARs are included in your classpath.


For beginners, another important thing to understand is the difference between PATH and CLASSPATH, you must know that PATH is used locate system executable, commands or .exe, .dll files (in Windows) and .so files (in Linux). It is also used to locate native libraries used by your Java program. While, CLASSPATH is used to locate the class file or JAR files. It's Java class loader who looked into CLASSPATH for loading classes.


Coming back to the problem in hand, if you are a beginner in Java, who are able to run the program from Eclipse but getting "Error: Could not find or load main class HelloWorld" when trying to run the same program from the command line then follow the steps given here to solve it.



Solving Error: Could not find or load main class HelloWorld 

Unfortunately beginner's book like Head First Java, which many developers used to learn Java, doesn't teach you how to deal with this kind of errors. You need to build this skill by doing active development.  In order to understand the problem little better, let's reproduce it. This is one of the most important troubleshooting skill which will help you a long way in your career. Half of the problem is solved when you are able to reproduce it. For our purpose we will use following HelloWorld program for our testing, interestingly I have named it HelloHP and it resides in a package called "dto". I have purposefully chosen a class with a package instead of HelloWorld in the default package because many programmers get "Could not find or load main class" error when they try to run a class which is inside a package.

package dto;
/**
 * Simple Java program to demonstrate following error
 * Error :Could not find or load main class
 * 
 * @author Javin Paul
 */
public class HelloHP {

    public static void main(String args[]) {
        System.out.println("My first program in Java, HelloWorld !!");
       
    }

}

When you run this from Eclipse, by Right click on the source file and Choosing "Run as Java Program", it will run fine and print following line:

My first program in Java, HelloWorld !!

Everything as expected, Now we will try to run same Java program from command line. Since I am using Maven with Eclipse, its build process creates class files in project_directory\target\classes directory. If you are not using Maven with Eclipse, then you can see the class file created by Eclipse's Java compiler in project_directory\bin. It doesn't matter how those class files are created, but, what is important is the location of the class file.

If your class is inside a non-default package e.g. "dto" in our case then compiler the will put the HelloHP.class file, which contains Java bytecode in a directory named "dto". In our case the full name of class dto.HelloHP and it is present in C:\Users\WINDOWS 8\workspace\Demo\target\classes\dto. So in the first try, I go there and execute java command to launch my program, as seen below:

C:\Users\WINDOWS 8\workspace\Demo\target\classes\dto>java HelloHP
Error: Could not find or load main class HelloHP

Do you see the error? It's coming because the full name of the class should be dto.HelloHP and not HelloHP. So let's correct this error and try to run the same command from the same location but this time with fully qualified name:

C:\Users\WINDOWS 8\workspace\Demo\target\classes\dto>java dto.HelloHP
Error: Could not find or load main class dto.HelloHP

Still same error, right. Why? because I don't have any CLASSPATH environment variable, neither I am using -classpath or -cp option to suggest the path, So by default Java is only searching in the current directory. It is looking for dto/HelloHP.class but since we are already inside dto, it is  not able to find the class. So, what should we do now? let's go to the parent directory "C:\Users\WINDOWS 8\workspace\Demo\target\classes" and execute the same command, this time, it should work:

C:\Users\WINDOWS 8\workspace\Demo\target\classes\dto>cd ..

C:\Users\WINDOWS 8\workspace\Demo\target\classes>java dto.HelloHP
My first program in Java, HelloWorld !!

Bingo!!, our program ran successfully because, without any hint about where to find class files, Java is by default looking into the current directory, denoted by . (dot) and able to locate ./dto/HelloHP.class.

Now, what if you want to run this program from any other directory? Well, for that purpose whether we need to define CLASSPATH or just use -classpath or -cp option. I like the second option because it's easier to control and change. Also, remember, it overrides any CLASSPATH environment variable. If you like to set CLASSPATH environment variable in Windows, see that tutorial.

Now let's run the program target directory first without using -classpath option:

C:\Users\WINDOWS 8\workspace\Demo\target\classes>cd ..

C:\Users\WINDOWS 8\workspace\Demo\target>java dto.HelloHP
Error: Could not find or load main class dto.HelloHP

You can see we are again started getting the same error, Why? because Java is still looking into the current directory and there is no .\target\dto\HelloHP.class there, as it's one level down e.g. .\target\classes\dto\HelloHP.class

Now let's run the same command using -classpath option from target directory itself:

C:\Users\WINDOWS 8\workspace\Demo\target>java -cp ./classes;. dto.HelloHP
My first program in Java, HelloWorld !!

Bingo!!, our program ran successfully again because now Java is also looking at ./classes directory and there it is able to find dto\HelloHP.class file.

There are many ways Error: Could not find or load main class HelloWorld manifests itself, but if you know the basics of Java Classpath, you can easily sort out the problem. Most of the time you just need to either correct your CLASSPATH environment variable or run your program with java -cp or -classpath option. By the way, there are more to it e.g. Main class defined in the manifest.mf file and that's why I suggest reading about How Classpath works in Java (see the link in the first paragraph).

Summary

If you are getting "Error: Could not find or load main class XXX", where XXX is the name of your main class while running Java program then do this to solve that error:

1) If you are running Java program right from the directory where .class file is and you have CLASSPATH environment variable defined then make sure it include current directory. (dot). You can include it as set CLASSPATH=%CLASSPATH%;. in Windows and export CLASSPATH = ${CLASSPATH}:. (see the separator, in Windows it's;(semicolon) while in Linux it is (colon), also note we have included current directory in existing classpath. If you still face the issue of setting classpath, see this step by step guide to set the classpath. Same thing applies if you are running your program using -cp or -classpath option.


2) If you are running Java program from the directory, your .class file is and you don't have any CLASSPATH or -cp option then check whether your class is the in the package or not. If it's the in the package then go outside of the package directory and run java command with fully qualified name e.g. if your program is com.abc package then runs following command from the parent directory of "com"

java com.abc.HelloWorld

without any classpath hints, Java will look into the current directory and search for com\abc\HelloWorld.class in Windows, so if com directory exists in your current directory, your program will run otherwise you will get "Error: Could not find or load main class dto.HelloHP".


3) You can run your Java program from anywhere with the help of proper CLASSPATH or java -cp option as shown below:

java -cp C:\test\;. com.abc.HelloWorld


If you still facing any issue just check whether you have accidentally using CLASSPATH environment variable, you can check this in Windows by running echo %CLASSPATH% command and in Linux by running echo $CLASSPATH. If CLASSPATH is nonempty then it will print its value otherwise just echo the same command.

4) If you are running in Java version 1.6 or 1.5, then instead of receiving "Error: Could not find or load main class", you will get Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld. It's only from JDK 1.7 onward we are started receiving this new error. The solution is exactly same, every bit of discussion applies to that case as well. So if you are not able to solve that problem by following steps here, do let me know and I will try to work with you to troubleshoot the problem.

Here is the screenshot of how I tried to reproduce and solve the error as discussed in the previous paragraph:

Solution of Error: Could not find or load main class HelloWorld



That's all about how to solve "Error: Could not find or load main class HelloWorld" in Java. Classpath is little confusing topic to master, but you will understand it once you started writing and running some Java program. If you are still not able to fix your problem then post a comment there with what you have tried and we will try to troubleshoot together. My goal is not just to give you solution but also make you able to explain why the solution is working and CLASSPATH basics are very important for a Java developer. I have seen many programmers getting frustrated, losing interest in Java due to various PATH and CLASSPATH issues e.g. NoClassDefFoundError and ClassNotFoundException and this is my humble effort to bring them back and empower with practical knowledge. Hope you understand.


Further Reading
Building debugging and troubleshooting skill is not easy and it takes lots of practice and experience to understand, reproduce and solve the error. If you are new Java developer then you first pick a book to learn Java from start to end, but if you are intermediate Java developer then you should look at the following the book to develop your debugging skill.
  • Head First Java (for beginners) (see here)
  • Java Puzzlers by Joshua Bloch (see here)
  • Java Performance by Binu John and Charlie Hunt (see here)

31 comments :

Anonymous said...

Another common cause of this error is invoking java command with .class file. Java just need name of your main class without any extension. If you call this

java HelloWorld.class

you will see
Could not find or load main class HelloWorld.class

Anonymous said...

Thank you so, so much for the thorough explanation. I was trying to figure out as to why it keep prompting that error message.

I had multiple folders/packages to compile. The compilation wasn't the issue but the running of the main file in a child directory, is. Apparently, I ran it as:

>java dto\Hello

instead of

>java dto.Hello

Javier Sánchez said...

Hello: Have you ever faced permissions issues on windows server 2012? Our program runs perfectly if you just double click on it, but it doesn't as a scheduled task. User is set to run wheter logged in or not. It also has full permissions on the program path and it has execution permissions on the java.exe path as well. Do you happen to have any clues on this situation? We are getting the "Error: Could not find or load main class" with the sched task user. Thanks!

Javin Paul said...

Hello Javier, by scheduled task do you mean running your Java program as windows service?

jaison said...

Hi, I am trying to call one c function from java via JNI. I added dll of the c program in java build path. but after doing this , i am getting the error "Could not find or load main class".
I am using Cygwin & eclipse.

c program
---------------
#include < stdint.h >
#include "JniCSidePgm.hpp"
#include < stdio.h >
#include < jni.h >

int sum(int v1,int v2){
return v1+v2;
}


java program
------------------
package com.jni;

public class JniJavaSidePgm {

static {
System.loadLibrary("JniCSide"); // Load native library at runtime
// hello.dll (Windows) or libhello.so (Unixes)
}

// Declare a native method sayHello() that receives nothing and returns void
private native void sum(int v1,int v2);

// Test Driver
public static void main(String[] args) {
new JniJavaSidePgm().sum(1,2); // invoke the native method
}
}

Javin Paul said...

Hello Jaison, from where did you running your program? since your main class is inside com.jni package, you must run outside that directory and provide a fully qualified name e.g.
java -cp . com.jni.JniJavaSidePgm

Anonymous said...

Running from outside the package did the job for me, thanks! No one any where else was able to get that across

Anonymous said...

Thank you! You just saved me from banging my head against the wall! I kept trying to go to Run | Run in Eclipse and in past exercises (I'm working out of the Head First Java book) I didn't have to do that. I completely forgot about the "right click" and "Run As" Java Application!

Javin Paul said...

@Anonymous, glad to hear that solution worked for you.

raghu said...

I am unable to compile main class and in my directory byte code is not created for the main class..

Javin Paul said...

@raghu, what error are you getting, can you post your error here?

Anonymous said...

thank you! you're awesome my friend! you saved me... I spent hours to find a solution for this error.

Anonymous said...

Hello, I am getting "Error: Could not find or load main class Server" on Eclipse. Server is the main class, contains main() method but somehow Eclipse is not able to find it. It's on default package, and I have tried everything from cleaning the project, building the project and build automatically. Not sure what is wrong, can you please help?

mourina said...

Hey Javin,

Thanks a lot.

Helped my solve my first Java issue.



Mahek Shah said...

hey. I am trying to run a java program via notepad and i am using window 7 32 bit. The program is unable to run saying "Could not find or load main class". I have tried every possible thing from setting the path and classpath to using dto but the result is the same. pls help. i am using jre and jdk1.8.0_73

mithilesh said...

Hi, Is anyone available now.
I get an error while running a java program from command prompt

Javin Paul said...

Hello @mithilesh, what did you try? does solution given here helped you?

mithilesh said...

@Javin: Thank you for replying. I was able to execute the program but after removing the package name from the program file. How to run the program with the package name in the file?

Javin Paul said...

@mithilesh, you need to run the program outside of the directory e.g. if package is com then run the command outside of the com directory with full classname i.e. com.ClassName, I think I have discussed this in the article as well.

See this example

C:\Users\WINDOWS 8\workspace\Demo\target\classes>java dto.HelloHP
My first program in Java, HelloWorld !!

Robert Stanley said...

Not working :( HELP!

Getting error: Could not find or load main class

Javin Paul said...

Hello @Robert, what did you try and what is not working? Can you please describe your problem in little more detail?

Valerie said...

I have a folder on my desktop called ’opennlp’ where my .class file is in.
So, I followed the instructions and in my command line returned to the desktop to run the following command:
java opennlp.OpenNlpTest

However, I still get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: opennlp/tools/util/ObjectStream
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2625)
at java.lang.Class.getMethod0(Class.java:2866)
at java.lang.Class.getMethod(Class.java:1676)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
Caused by: java.lang.ClassNotFoundException: opennlp.tools.util.ObjectStream
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 6 more

I hope you can help me

Anonymous said...

Hello Mahek,try changing the name of your program to the name of the project class .It worked for me.

Anonymous said...

Thanks for this article, it was really usefull :-)

Ganesh Harugeri said...

You don't know how much your steps helped me to solve my problem. A big thank you Javin Paul :)

Javin Paul said...

your welcome @Ganesh, glad you find this tutorial useful.

Anonymous said...

This doesn't work for me. I am running Fedora (Linux). I copied your source for HelloHP and saved it as HelloHP.java. I then opened a terminal window, went to where I saved the file and compiled it from the command line. When I went to run it I got the class not found error as expected. I then went to the parent directory and tried again. Still failed. What am I doing wrong?
Here is the output from my attempt

vince@Vince2 sample]$ javac HelloHP.java
[vince@Vince2 sample]$ java HelloHP
Error: Could not find or load main class HelloHP
[vince@Vince2 sample]$ cd ..
[vince@Vince2 hsqldb]$ java dto.HelloHP
Error: Could not find or load main class dto.HelloHP

Thank you in advance

Anonymous said...

Update - I made a few changes and got it to work. I commented out the package statement in the source and added "-cp ." to the java command. This worked. What was wrong with the original code?
Here is some output:

vince@Vince2 sample]$ cat HelloHP.java

package HelloHP;
/**
* Simple Java program to demonstrate following error
* Error :Could not find or load main class
*
* @author Javin Paul
*/
public class HelloHP {

public static void main(String args[]) {
System.out.println("My first program in Java, HelloWorld !!");

}

}
[vince@Vince2 sample]$ java -cp . HelloHP
Error: Could not find or load main class HelloHP
[vince@Vince2 sample]$ javac HelloHP.java
[vince@Vince2 sample]$ java -cp . HelloHP
My first program in Java, HelloWorld !!

dArch said...

Very helpful explanation ... solved my issue w/o a fuss, thanks:-)

Javin Paul said...

@dArch, thanks!!glad to know that it help you to solve your issue.

Anonymous said...

Eclipse - main class not found error
I was also getting same problem in Eclipse i.e. whenever I run my program either by Run configurations or right click and run as Java program, I get the popup complaining about could not find or load main class. I debug it by debug as Java program and found that it was one of the dependent JAR which was available in classpath but Eclipse was not seeing it. My error was resolved after deleting existing run configuration where User entry was not pointing to default classpath. Just deleting the run configuration and re-creating it by running the class as right click, Run as Java program will fix the error.

Post a Comment