Error: Could not find or load main class

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.

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.

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

and that’s that. 🙂

原文链接:Error: Could not find or load main class

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容