Java Error: Could not find or load main class

When you are creating apps using an IDE like Eclipse or IntelliJ IDEA, compiling and running your code is pretty easy since the IDE will take care of many of the things behind the scenes. But you may encounter this error when you try to compile and run your code by windows command line (yes, although I am a Mac user, this post is for windows but you can use the same principles to make your code on X-based systems too).

I will approach this assuming a scenario in which you will get this error and show you how to fix the scenario.

What might be wrong?

In this scenario you have a mycode folder under “C:\Users\myuser\mycode” and you have your .java source files here. Let’s say you have a test1.java file whose source looks like below:

Pay attention to the package statement.

Before using javac and java command on the command line to compile and run your source files, you need to first add “C:\Users\myuser\mycode” to your classpath. Below screenshot displays how you can do that.

Setting CLASSPATH on windows
Setting CLASSPATH on windows

To make sure you have set the CLASSPATH, restart the CMD and run “echo %CLASSPATH%”. Assuming you are done setting the CLASSPATH, now you should cd to “C:\Users\myuser\mycode” and run “javac test1.java”. This will create 2 separate classes inside “mycode” folder.

Now… If you run “java TestPhone” it will say Error: Could not find or load main class TestPhone. Try running “java com.mobile.TestPhone” and you will get the same error message. You know why? Because you have set your CLASSPATH as “C:\Users\myuser\mycode” and therefore java is trying to find your .class files under “C:\Users\myuser\mycode\com\mobile” (remember the package statement?).

Create “com” folder under “mycode” and then create “mobile” folder under it. Now, cut&paste Phone.class and TestPhone.class into “mobile” folder. Re-run “java com.mobile.TestPhone”, it should work this time.

Hope this helps.
Good Luck,
Serdar