Home What does "Could not find or load main class" mean?
Reply: 30

What does "Could not find or load main class" mean?

Stephen C
1#
Stephen C Published in 2013-08-07 03:02:46Z

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?

Stephen C
2#
Stephen C Reply to 2018-01-08 22:44:25Z

The java <class-name> command syntax

First of all, you need to understand the correct way to launch a program using the java (or javaw) command.

The normal syntax1 is this:

    java [ <option> ... ] <class-name> [<argument> ...]

where <option> is a command line option (starting with a "-" character), <class-name> is a fully qualified Java class name, and <argument> is an arbitrary command line argument that gets passed to your application.
1 - There is a second syntax for "executable" JAR files which I will describe at the bottom.

The fully qualified name (FQN) for the class is conventionally written as you would in Java source code; e.g.

    packagename.packagename2.packagename3.ClassName

However some versions of the java command allow you to use slashes instead of periods; e.g.

    packagename/packagename2/packagename3/ClassName

which (confusingly) looks like a file pathname, but isn't one. Note that the term fully qualified name is standard Java terminology ... not something I just made up to confuse you :-)

Here is an example of what a java command should look like:

    java -Xmx100m com.acme.example.ListUsers fred joe bert

The above is going to cause the java command to do the following:

  1. Search for the compiled version of the com.acme.example.ListUsers class.
  2. Load the class.
  3. Check that the class has a main method with signature, return type and modifiers given by public static void main(String[]). (Note, the method argument's name is NOT part of the signature.)
  4. Call that method passing it the command line arguments ("fred", "joe", "bert") as a String[].

Reasons why Java cannot find the class

When you get the message "Could not find or load main class ...", that means that the first step has failed. The java command was not able to find the class. And indeed, the "..." in the message will be the fully qualified class name that java is looking for.

So why might it be unable to find the class?

Reason #1 - you made a mistake with the classname argument

The first likely cause is that you may have provided the wrong class name. (Or ... the right class name, but in the wrong form.) Considering the example above, here a variety of wrong ways to specify the class name:

  • Example #1 - a simple class name:

    java ListUser
    

    When the class is declared in a package such as com.acme.example, then you must use the full classname including the package name in the java command; e.g.

    java com.acme.example.ListUser
    
  • Example #2 - a filename or pathname rather than a class name:

    java ListUser.class
    java com/acme/example/ListUser.class
    
  • Example #3 - a class name with the casing incorrect:

    java com.acme.example.listuser
    
  • Example #4 - a typo

    java com.acme.example.mistuser
    
  • Example #5 - a source filename

    java ListUser.java
    
  • Example #6 - you forgot the class name entirely

    java lots of arguments
    

Reason #2 - the application's classpath is incorrectly specified

The second likely cause is that the class name is correct, but that the java command cannot find the class. To understand this, you need to understand the concept of the "classpath". This is explained well by the Oracle documentation:

  • The java command documentation
  • Setting the Classpath.
  • The Java Tutorial - PATH and CLASSPATH

So ... if you have specified the class name correctly, the next thing to check is that you have specified the classpath correctly:

  1. Read the three documents linked above. (Yes ... READ them. It is important that a Java programmer understands at least the basics of how the Java classpath mechanisms works.)
  2. Look at command line and / or the CLASSPATH environment variable that is in effect when you run the java command. Check that the directory names and JAR file names are correct.
  3. If there are relative pathnames in the classpath, check that they resolve correctly ... from the current directory that is in effect when you run the java command.
  4. Check that the class (mentioned in the error message) can be located on the effective classpath.
  5. Note that the classpath syntax is different for Windows versus Linux and Mac OS.

Reason #2a - the wrong directory is on the classpath

When you put a directory on the classpath, it notionally corresponds to the root of the qualified name space. Classes are located in the directory structure beneath that root, by mapping the fully qualified name to a pathname. So for example, if "/usr/local/acme/classes" is on the class path, then when the JVM looks for a class called com.acme.example.Foon, it will look for a ".class" file with this pathname:

  /usr/local/acme/classes/com/acme/example/Foon.class

If you had put "/usr/local/acme/classes/com/acme/example" on the classpath, then the JVM wouldn't be able to find the class.

Reason #2b - the subdirectory path doesn't match the FQN

If your classes FQN is com.acme.example.Foon, then the JVM is going to look for "Foon.class" in the directory "com/acme/example":

  • If your directory structure doesn't match the package naming as per the pattern above, the JVM won't find your class.

  • If you attempt rename a class by moving it, that will fail as well ... but the exception stacktrace will be different.

To give a concrete example, supposing that:

  • you want to run com.acme.example.Foon class,
  • the full file path is /usr/local/acme/classes/com/acme/example/Foon.class,
  • your current working directory is /usr/local/acme/classes/com/acme/example/,

then:

# wrong, FQN is needed
java Foon

# wrong, there is no `com/acme/example` folder in the current working directory
java com.acme.example.Foon

# wrong, similar to above
java -classpath . com.acme.example.Foon

# fine; relative classpath set
java -classpath ../../.. com.acme.example.Foon

# fine; absolute classpath set
java -classpath /usr/local/acme/classes com.acme.example.Foon

Notes:

  • The -classpath option can be shortened to -cp in most Java releases. Check the respective manual entries for java, javac and so on.
  • Think carefully when choosing between absolute and relative pathnames in classpaths. Remember that a relative pathname may "break" if the current directory changes.

Reason #2c - dependencies missing from the classpath

The classpath needs to include all of the other (non-system) classes that your application depends on. (The system classes are located automatically, and you rarely need to concern yourself with this.) For the main class to load correctly, the JVM needs to find:

  • the class itself.
  • all classes and interfaces in the superclass hierarchy (e.g. see Java class is present in classpath but startup fails with Error: Could not find or load main class)
  • all classes and interfaces that are referred to by means of variable or variable declarations, or method call or field access expressions.

(Note: the JLS and JVM specifications allow some scope for a JVM to load classes "lazily", and this can affect when a classloader exception is thrown.)

Reason #3 - the class has been declared in the wrong package

It occasionally happens that someone puts a source code file into the the wrong folder in their source code tree, or they leave out the package declaration. If you do this in an IDE, the IDE's compiler will tell you about this immediately. Similarly if you use a decent Java build tool, the tool will run javac in a way that will detect the problem. However, if you build your Java code by hand, you can do it in such a way that the compiler doesn't notice the problem, and the resulting ".class" file is not in the place that you expect it to be.

The java -jar <jar file> syntax

The alternative syntax used for "executable" JAR files is as follows:

  java [ <option> ... ] -jar <jar-file-name> [<argument> ...]

e.g.

  java -Xmx100m -jar /usr/local/acme-example/listuser.jar fred

In this case the name of the entry-point class (i.e. com.acme.example.ListUser) and the classpath are specified in the MANIFEST of the JAR file.

IDEs

A typical Java IDE has support for running Java applications in the IDE JVM itself or in a child JVM. These are generally immune from this particular exception, because the IDE uses its own mechanisms to construct the runtime classpath, identify the main class and create the java command line.

However it is still possible for this exception to occur, if you do things behind the back of the IDE. For example, if you have previously set up an Application Launcher for your Java app in Eclipse, and you then moved the JAR file containing the "main" class to a different place in the file system without telling Eclipse, Eclipse would unwittingly launch the JVM with an incorrect classpath.

In short, if you get this problem in an IDE, check for things like stale IDE state, broken project references or broken launcher configurations.

It is also possible for an IDE to simply get confused. IDE's are hugely complicated pieces of software comprising many interacting parts. Many of these parts adopt various caching strategies in order to make the IDE as a whole responsive. These can sometimes go wrong, and one possible symptom is problems when launching applications. If you suspect this could be happening, it is worth restarting your IDE.

Other References

  • From the Oracle Java Tutorials - Common Problems (and Their Solutions)
Peter Mortensen
3#
Peter Mortensen Reply to 2017-01-14 16:49:21Z

Sometimes what might be causing the issue has nothing to do with the main class, and I had to find this out the hard way. It was a referenced library that I moved, and it gave me the:

Could not find or load main class xxx Linux

I just deleted that reference, added it again, and it worked fine again.

Louis van Tonder
4#
Louis van Tonder Reply to 2013-12-02 14:33:34Z

First set the path using this command;

set path="paste the set path address"

Then you need to load the program. Type "cd (folder name)" in the stored drive and compile it. For Example, if my program stored on the D drive, type "D:" press enter and type " cd (folder name)".

KawaiKx
5#
KawaiKx Reply to 2014-03-12 00:37:57Z

In my case, error appeared because I had supplied the source file name instead of the class name.

We need to supply the class name containing the main method to the interpreter.

Paolo Forgia
6#
Paolo Forgia Reply to 2017-09-04 14:06:24Z

If your source code name is HelloWorld.java, 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
Peter Mortensen
7#
Peter Mortensen Reply to 2017-01-14 16:51:55Z

What helped me was specifying the classpath on the command line, for example:

  1. Create a new folder, C:\temp

  2. Create file Temp.java in C:\temp, with the following class in it:

    public class Temp {
        public static void main(String args[]) {
            System.out.println(args[0]);
        }
    }
    
  3. Open a command line in folder C:\temp, and write the following command to compile the Temp class:

    javac Temp.java
    
  4. Run the compiled Java class, adding the -classpath option to let JRE know where to find the class:

    java -classpath C:\temp Temp Hello!
    
Kenster
8#
Kenster Reply to 2017-05-23 17:32:03Z

If your main method is in the class under a package, you should run it over the hierarchical directory.

Assume there is a source code file (Main.java):

package com.test;

public class Main {

    public static void main(String[] args) {
        System.out.println("salam 2nya\n");
    }
}

For running this code, you should place Main.Class in the package like directory ./com/test/Main.Java. And in the root directory use java com.test.Main.

Peter Mortensen
9#
Peter Mortensen Reply to 2017-01-14 16:54:38Z

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:

D:\project\com\cse\

The full name of my main class is:

com.cse.Main

So I cd back to the main directory:

D:\project

Then issue the java command:

java com.cse.Main
Peter Mortensen
10#
Peter Mortensen Reply to 2017-01-14 16:55:34Z

In this instance you have:

Could not find or load main class ?classpath

It's because you are using "-classpath", but the dash is not the same dash used by java on the command prompt. I had this issue copying and pasting from Notepad to cmd.

Peter Mortensen
11#
Peter Mortensen Reply to 2017-01-14 16:56:52Z

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:

javac HelloWorld.java
java -cp . HelloWorld
mathewbruens
12#
mathewbruens Reply to 2015-09-02 05:58:27Z

I spent a decent amount of time trying to solve this problem. I thought that I was somehow setting my classpath incorrectly but the problem was that I typed:

java -cp C:/java/MyClasses C:/java/MyClasses/utilities/myapp/Cool
instead of:
java -cp C:/java/MyClasses utilities/myapp/Cool
I thought the meaning of fully qualified meant to include the full path name instead of the full package name.

Xiao Peng - Builder of ZenUML
13#
Xiao Peng - Builder of ZenUML Reply to 2017-06-05 00:38:20Z

According to the error message ("Could not find or load main class"), there are two categories of problems:

  1. Main class could not be found
  2. Main class could not be loaded (this case is not fully discussed in the accepted answer)

Main class could not be found when there is typo or wrong syntax in the fully qualified class name or it does not exist in the provided classpath.

Main class could not be loaded when the class cannot be initiated, typically the main class extends another class and that class does not exist in the provided classpath.

For example:

public class YourMain extends org.apache.camel.spring.Main

If camel-spring is not included, this error will be reported.

Anandaraja Ravi
14#
Anandaraja Ravi Reply to 2015-09-18 03:01:01Z

In Java, when you sometimes run the JVM from the command line using the java executable and are trying to start a program from a class file with public static void main (PSVM), you might run into the below error even though the classpath parameter to the JVM is accurate and the class file is present on the classpath:

Error: main class not found or loaded

This happens if the class file with PSVM could not be loaded. One possible reason for that is that the class may be implementing an interface or extending another class that is not on the classpath. Normally if a class is not on the classpath, the error thrown indicates as such. But, if the class in use is extended or implemented, java is unable to load the class itself.

Reference: https://www.computingnotes.net/java/error-main-class-not-found-or-loaded/

Peter Mortensen
15#
Peter Mortensen Reply to 2017-01-20 19:12:33Z

On Windows put .; at the CLASSPATH value in the beginning.

The . (dot) means "look in the current directory". This is a permanent solution.

Also you can set it "one time" with set CLASSPATH=%CLASSPATH%;.. This will last as long as your cmd window is open.

Jaanus
16#
Jaanus Reply to 2015-12-14 14:14:27Z

I got this error after doing mvn eclipse:eclipse This messed up my .classpath file a little bit.

Had to change the lines in .classpath from

<classpathentry kind="src" path="src/main/java" including="**/*.java"/>
<classpathentry kind="src" path="src/main/resources" excluding="**/*.java"/>

to

<classpathentry kind="src" path="src/main/java" output="target/classes" />
<classpathentry kind="src" path="src/main/resources" excluding="**"  output="target/classes" />
GuiRitter
17#
GuiRitter Reply to 2015-12-27 00:26:16Z

This is a specific case, but since I came to this page looking for a solution and didn't find it, I'll add it here.

Windows (tested with 7) doesn't accept special characters (like รก) in class and package names. Linux does, though.

I found this out when I built a .jar in NetBeans and tried to run it in command line. It ran in NetBeans but not in command line.

syntagma
18#
syntagma Reply to 2016-01-16 10:26:31Z

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 the Advanced... button then add bin folder of your project.

Peter Mortensen
19#
Peter Mortensen Reply to 2017-01-20 19:16:09Z

I was unable to solve this problem with the solutions stated here (although the answer stated has, no doubt, cleared my concepts). I faced this problem two times and each time I have tried different solutions (in the Eclipse IDE).

  • Firstly, I have come across with multiple main methods in different classes of my project. So, I had deleted the main method from subsequent classes.
  • Secondly, I tried following solution:
    1. Right click on my main project directory.
    2. Head to source then clean up and stick with the default settings and on Finish. After some background tasks you will be directed to your main project directory.
    3. After that I close my project, reopen it, and boom, I finally solved my problem.
Peter Mortensen
20#
Peter Mortensen Reply to 2017-01-20 19:17:26Z

You really need to do this from the src folder. There you type the following command line:

[name of the package].[Class Name] [arguments]

Let's say your class is called CommandLine.class, and the code looks like this:

package com.tutorialspoint.java;

    /**
     * Created by mda21185 on 15-6-2016.
     */

    public class CommandLine {
        public static void main(String args[]){
            for(int i=0; i<args.length; i++){
                System.out.println("args[" + i + "]: " + args[i]);
            }
        }
    }

Then you should cd to the src folder and the command you need to run would look like this:

java com.tutorialspoint.java.CommandLine this is a command line 200 -100

And the output on the command line would be:

args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
Peter Mortensen
21#
Peter Mortensen Reply to 2017-01-20 19:19:26Z

Sometimes it's better to remove the added JAR files and add again with proper build helps. For me it has been a regular issue, and I followed the same approach:

  1. Put all the referred JAR files in a folder, jarAddOns, and copy it in a safe place
  2. Now from Eclipse (or from your IDE) remove the JAR files.
  3. Move the whole project folder from the workspace to a safe location
  4. Restart Eclipse (your IDE)
  5. Now import your project directory from the safe location.
  6. Add the JAR files into your project from the jarAddOns folder (previously saved in safe location)
  7. Project buildpath, add JAR files and apply
  8. Now run the project. It should not show the error.
Community
22#
Community Reply to 2017-05-23 12:18:29Z

Try -Xdiag.

Steve C's answer covers the possible cases nicely, but sometimes to determine whether the class could not be found or loaded might not be that easy. Use java -Xdiag (since jdk 7). This prints out nice stacktrace which provides a hint to what the message Could not find or load main class message means.

For instance, it can point you to other classes used by the main class that could not be found and prevented the main class to be loaded.

Peter Mortensen
23#
Peter Mortensen Reply to 2017-04-09 10:30:52Z

I had such an error in this case:

java -cp lib.jar com.mypackage.Main

It works with ; for Windows and : for Unix:

java -cp lib.jar; com.mypackage.Main
Peter Mortensen
24#
Peter Mortensen Reply to 2017-01-20 19:24:53Z

All answers here are directed towards Windows users it seems. For Mac, the classpath separator is :, not ;. As an error setting the classpath using ; is not thrown then this can be a difficult to discover if coming from Windows to Mac.

Here is corresponding Mac command:

java -classpath ".:./lib/*" com.test.MyClass

Where in this example the package is com.test and a lib folder is also to be included on classpath.

Peter Mortensen
25#
Peter Mortensen Reply to 2017-04-09 10:32:31Z

For a database connection I was getting this one. I just added the following in the class path:

export CLASSPATH=<path>/db2jcc4.jar:**./**

Here I appended ./ in last so that my class also get identified while loading.

Now just run:

java ConnectionExample <args>

It worked perfectly fine.

Addison
26#
Addison Reply to 2017-02-23 06:59:44Z

Seems like when I had this problem, it was unique.

Once I removed the package declaration at the top of the file, it worked perfectly.

Aside from doing that, there didn't seem to be any way to run a simple HelloWorld.java on my machine, regardless of the folder the compilation happened in, the CLASSPATH or PATH, parameters or folder called from.

shaILU
27#
shaILU Reply to 2017-02-23 07:56:52Z

Use this command

java -cp . [PACKAGE.]CLASSNAME

example if your classname is Hello.class created from Hello.java then use below command

java -cp . Hello

If your file Hello.java is inside package com.demo then use below command

java -cp . com.demo.Hello

with jdk 8 many time it happens that class file is present in same folder but java command expects classpath and for this reason we add -cp . to take current folder as reference for classpath.

developer747
28#
developer747 Reply to 2017-03-27 02:18:52Z

Class file location: C:\test\com\company

File Name: Main.class

Fully qualified class name: com.company.Main

Command line command:

java  -classpath "C:\test" com.company.Main

Note here that class path does NOT include \com\company

Robert Odoch
29#
Robert Odoch Reply to 2017-05-17 15:31:22Z

By default, Java uses ., the geek letter for "current working directory" (you now know one letter in the geek alphabet right?) as the default CLASSPATH. What this means is that when you type a command at the prompt e.g. java MyClass, the command is interpreted as if you had type java -cp . MyClass. Did you see that dot between -cp and MyClass? (cp is short for the longer classpath option)

This is sufficient for most cases and things seems to work just fine until at some time you try to add a directory to your CLASSPATH. In most cases when programmers need to do this, they just run a command like set CLASSPATH=path\to\some\dir. This command creates a new environment variable called CLASSPATH having the value path\to\some\dir or replaces its value with path\to\some\dir if CLASSPATH was already set before.

When this is done, you now have a CLASSPATH environment variable and Java no longer uses it's default classpath (.) but the one you've set. So the next day you open your editor, write some java program, cd to the directory where you saved it, compile it, and try to run it with the command java MyClass, and you are greeted with a nice output: Could not find or load main class ... (If your commands were working well before and you are now getting this output, then this might be the case for you).

What happens is that when you run the command java MyClass, Java searches for the class file named MyClass in the directory or directories that you have set in your CLASSPATH and not your current working directory so it doesn't find your class file there and hence complains.

What you need to do is add . to your class path again which can be done with the command set CLASSPATH=%CLASSPATH%;. (notice the dot after the semicolon). In plain english this command says "Pick what was initially the value of CLASSPATH (%CLASSPATH%), add . to it (;.) and assign the result back to CLASSPATH".

And viola, you are once again able to use your command java MyClass as usual.

Thanks.

Chezzwizz
30#
Chezzwizz Reply to 2017-05-21 08:14:38Z

When running the java with the -cp option as advertised in Windows PowerShell you may get an error that looks something like:

The term `ClassName` is not recognized as the name of a cmdlet, function, script ...

In order to for PowerShell to accept the command, the arguments of the -cp option must be contained in quotes as in:

java -cp 'someDependency.jar;.' ClassName

Forming the command this way should allow Java process the classpath arguments correctly.

Ramesh Pareek
31#
Ramesh Pareek Reply to 2017-06-01 10:36:01Z

This might help you if your case is specifically like mine: as a beginner I also ran into this problem when I tried to run a java program.

I compiled it like this: javac HelloWorld.java

and tried to run also with the same extension

java Helloworld.java

When I removed the .java and rewrote the command like this java HelloWorld, The Program ran perfectly. :)

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.417351 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO