Monday, 20 July 2015

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 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 little bit complex topic for beginners, but we will touch same base here. For curious reader, I would suggest to read my post How Classpath works in Java, a must read for 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 are now started programming using Eclipse they face this issue when they first try to run their Java program from command line. In Eclipse its easy to compile and run 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 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 class file or JAR files. Its Java class loader who looked into CLASSPATH for loading classes. Coming back to 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 command line then follow the steps given here to solve it.



Solving Error: Could not find or load main class HelloWorld 

In order to understand the problem little better, let's 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 default package, because many programmer 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 will put the HelloHP.class file, which contains Java bytecode in a directory named "dto". In our case full name of class dto.HelloHP and it is present in C:\Users\WINDOWS 8\workspace\Demo\target\classes\dto. So in 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? Its coming because full name of class should be dto.HelloHP and not HelloHP. So let's correct this error and try to run the same command from 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 path, So by default Java is only searching in 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 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 its 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 same error, Why? because Java is still looking into current directory and there is no .\target\dto\HelloHP.class there, as its 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 manifest.mf file and that's why I suggest to read about How Classpath works in Java (see the link in 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 its ;(semi colon) while in Linux it is (colon), also note we have included current directory in existing classpath. If you still face the issue on setting classpath, see this step by step guide to set 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 in package or not. If its in 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 run following command from parent directory of "com"

java com.abc.HelloWorld

without any classpath hints, Java will look into 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 non empty 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. Its only from JDK 1.7 onward we are started receiving this new error. 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 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 solution is working and CLASSPATH basics is very important for a Java developer. I have seen many programmer 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.

No comments:

Post a Comment