DEV Community

loading...

Error: Could not find or load main class

phagunjain profile image PHAGUN JAIN ・2 min read

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
C:\Users\omgill\Desktop\Java
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. :)

Discussion (0)

pic
Editor guide