DEV Community


Posted on

Error: Could not find or load main class

alt text

While trying to execute java code via command-line you may have encountered the above error quite commonly (if you declare your class as a part of some package)

What is package?

Packages are containers for classes that are used to keep the class name space compartmentalized. For example, a package allows you to create a class named List, which you can store in your own package without concern that it will collide with some other class named List stored elsewhere.

Finding packages

How does the Java run-time system know where to look for packages that you create?
The answer has three parts. First, by default, the Java run-time system uses the current working directory as its starting point. Thus, if your package is in a subdirectory of the current directory, it will be found. Second, you can specify a directory path or paths by setting the CLASSPATH environmental variable. Third, you can use the -classpath option with java and javac to specify the path to your classes.
In this read I will focus on the most easiest way, i.e. first one

The Demonstration :-

1> Checkin into your development directory in my case this is
2> The easiest way is to simply create your package directory below your development folder.

alt text

3> Now put your .java file into the package directory complie the code .
CAUTION: make sure that all the .class files are placed in the right folder/directory.

alt text

4> Then execute the class using the command:
java .

alt text

and that's that. :)

Top comments (2)

linehammer profile image

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. For example, If your source code name is, your compiled code will be HelloWorld.class. You will get that error if you call it using:

java HelloWorld.class

Instead, use this:

java HelloWorld

Other reasons to occur this error is :

File Extension
Wrong package
Invalid Classpath
Wrong Class Name

phagunjain profile image

thanks for the nice explanation!