A common problem that new Java developers experience is that their programs fail to run with the error message: Could not find or load main class ...
What does this mean, what causes it, and how should you fix it?
A common problem that new Java developers experience is that their programs fail to run with the error message: Could not find or load main class ...
What does this mean, what causes it, and how should you fix it?
When the same code works on one PC, but it shows the error in another, the best solution I have ever found is compiling like the following:
If your classes are in packages then you have to
cd
to the main directory and run using the full name of the class (packageName.MainClassName).Example:
My classes are in here:
The full name of my main class is:
So I
cd
back to the main directory:Then issue the
java
command:What fixed the problem in my case was:
Right click on the project/class you want to run, then
Run As
->Run Configurations
. Then you should either fix your existing configuration or add new in the following way:open the
Classpath
tab, click on theAdvanced...
button then addbin
folder of your project.You really need to do this from the
src
folder. There you type the following command line:Let's say your class is called
CommandLine.class
, and the code looks like this:Then you should
cd
to the src folder and the command you need to run would look like this:And the output on the command line would be:
I also faced similar errors while testing a Java MongoDB JDBC connection. I think it's good to summarize my final solution in short so that in the future anybody can directly look into the two commands and are good to proceed further.
Assume you are in the directory where your Java file and external dependencies (JAR files) exist.
Compile:
Run:
Use this command:
Example: If your classname is Hello.class created from Hello.java then use the below command:
If your file Hello.java is inside package com.demo then use the below command
With JDK 8 many times it happens that the class file is present in the same folder, but the
java
command expects classpath and for this reason we add-cp .
to take the current folder as reference for classpath.