C:\Discounts> Use code System.OutOfMemoryException and get FREE SHIPPING_

Java - "Could not find or load main class" Error

Java - "Could not find or load main class" Error

CLASSPATH, Java

One of the most frequently encountered errors when learning Java programming is the "Could not find or load main class" error. Before we dive into understanding the cause of the error, it's first important to understand how to launch a program using the java command. The "Could not find or load main class" error can be caused by many things, let's start with the basics and then go over some other possible causes of this error.

Launching a program using the java command

This is fairly simple but also often the cause of this error, first ensure your syntax for launching the java app is correct. If you need more info on the java command check out the oracle doc.

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

The class name argument is incorrect

When specifying the class name argument it is important to remember that this is case sensitive and may require the full package name. Here's an example given that we are trying to execute the class my.app.MyJavaClass

java my.app.MyJavaClass

Ensure your CLASSPATH is correct

The next step to troubleshoot is to make sure that you have your class path set correctly. These are just the environment variables that are typically setup to point to your JDK. For this solution we recommend reading this CLASSPATH tutorial, this should get you squared away.

Remember CLASSPATH syntax is OS-dependent

So if you've confirmed your CLASSPATH is set correctly in your environment variable and you're still getting the error.. Let's make sure you are using the correct syntax for your OS.

On Windows each file path must be separated by a semicolon ;

    java -cp file.jar;dir/* my.app.MyJavaClass

    On Unix each file path must be separated by a colon :

      java -cp file.jar:dir/* my.app.MyJavaClass

      You are executing the command including .class

      While this fix will only work with Java classes declared in the default package with no JAR file, it is still worth mentioning. Check out the code examples below to better understand the resolution. 

      Here is the problem syntax which is causing the error

        java my.app.MyJavaClass.class

        Resolution #1: Remove .class 

          java my.app.MyJavaClass

          Resolution #2: Specify the classpath parameter explicitly

            java -classpath . my.app.MyJavaClass