Could Not Find or Load Main Class Error | Java

Java Could Not Find or Load Main Class

When starting your Java application, you may encounter this error:

Error: Could not find or load main class MyClass
Caused by: java.lang.ClassNotFoundException: MyClass
Caused by: java.lang.ClassNotFoundException: MyClass

This error is very common when creating new Java based projects. Whether you're using Gradle or Maven, Spring Boot or Kafka, chances are you've encountered this error before.

Sometimes the error will occur unexpectedly. Sometimes the error is specific to your IDE.

Regardless, fixing the error is easy and it starts with understanding the cause:

What Causes the "Could Not Find or Load Main Class" Error?

This error is thrown whenever Java can't find or load the main class of your application.

Let's say you define a class like this:

public class MyClass {
  public static void main(String[] args) {
    System.out.println("My class is working!");
  }
}
  public static void main(String[] args) {
    System.out.println("My class is working!");
  }
}

When running this simple class, you could get the "could not find or load main class" error for several reasons...

1. IDE Configuration Issue

Most IDEs let you configure the starting point for your application. For example, in IntelliJ you can edit configuration to select a main class for running the project.

If you're running your application through an IDE, make sure that it is configured properly to look for the main class in the right place.

2. Wrong Class Name

Remember that class names must be unique in Java. Furthermore, they are case sensitive...

Let's say you are running your program from the CLI using the java tool..

java myclass

This will result in the "Could not find or load main class" error because class names are case sensitive.

3. Wrong Extension

When running from the command line, many developers accidentally append an extension like:

java MyClass.java

or

java MyClass.class

The correct way is to run without any extension:

java MyClass

4. Wrong Location

Let's say your class is part of a package like this:

package com.myproject;
public class  MyClass {
  public static void main(String[] args) {
    System.out.println("My class is working!");
  }
}
public class  MyClass {
  public static void main(String[] args) {
    System.out.println("My class is working!");
  }
}

If you don't run your class with the fully qualified name AND from the right directory, you will get the "Could not find or load main class" error...

5. Wrong Class Path

The class path is where the JVM looks for classes to load into your program. Sometimes developers provide a specified path like this:

java MyClass -cp /usr/local/path

While the optional -cp argument allows you to specify your own class path, you can easily get the "Could not find or load main class" error if this is incorrect...

How to fix the "Could Not Find or Load Main Class" Error

1. Make sure your IDE is configured properly

Make sure that your IDE has the correct configuration for finding the main class/entry point of your application.

2. Make sure your class name is correct

If you are running your program from the CLI, make sure that you are specifying the right class name without extensions...

java MyClass

3. Make sure you are running your application from the right directory

Make sure you are running your application from the right folder. If your class is part of a package then you must run it from the parent directory....

java com.myproject.MyClass

4. Make sure your class path is correct

Make sure your class path is correct. By default, the class path is the current working directory ".". If you override this with the -cp argument then make sure it's accurate!

Understanding the Java Error "Could Not Find or Load Main Class"

While this error is self explanatory and easy to fix, it's worth understanding how Class Loaders work behind the scenes. This gives you a better understanding of why the "Could Not Find or Load Main Class" error happens...

When are Classes Loaded in Java?

Classes are loaded dynamically. This means classes are loaded into memory only when they are needed.

Unlike C++, Java is a dynamically compiled language. This means the language is compiled to machine code while the program is running.

Of course, some classes must be loaded initially when your program starts. The JRE utilizes a native class loader to load the main entry point of your application. From here, class loaders are used to dynamically load (lazy load) classes as they are needed by the application.

The Class Loading Mechanism in Java

Java utilizes a delegation mechanism for loading classes at runtime. There are 3 built-in class loaders used by the JRE at runtime:

1. Bootstrap class loader: This loads the standard runtime classes found in rt.jar

2. Extensions: This loads any extension classes used by the JRE

3. System: This loads classes defined by the application and found on the class path

Each class loader first checks a cache to see if the requested class has already been loaded into memory. If nothing is found in the cache, it delegates the finding of the class to the parent class loader.

This process happens recursively...

If the system class loader can't find the class, it delegates to the extension class loader.

If the extension class loader can't find the class, it delegates to the bootstrap class loader.

If the bootstrap class loader can't find the class, it tells the extension class loader to find it

If the extension class loader can't find the class, it tells the system class loader to find it

If the system class loader can't find it, it throws an ClassNotFound exception

This mechanism works to ensure uniqueness, visibility and delegation are applied to the class loading mechanism in Java.

Uniqueness explains the reason why no two classes can have the same name. By keeping class names unique, class loaders can easily find the single representation of a defined class.

Visibility explains the child-parent relationship between class loaders. While children can view parent classes, parents can't view child classes. This ensures an isolation level needed to create the hierarchy between class loaders.

Delegation explains how the class loaders work together to recursively retrieve a unique class. By delegating to parent classes, class loaders ensure only one representation of a defined class exists.

Java Class Loading Order

1) Class loader searches cache for loaded classes

2) If cache has the class, it is returned. Otherwise, the class loader delegates to parent class to retrieve the class

3) Parent class loaders ultimately delegate to the bootstrap class loader. If the class isn't found, the bootstrap loader returns responsibility to child loader.

4) Either the system loader finds and loads the class, or a ClassNotFound exception is thrown.

Custom Class Loaders

You can create your own class loaders by extending the ClassLoader class:

public class CustomClassLoader extends ClassLoader { ...

Most developers don't need to worry about creating custom class loaders. There are times where it makes sense however. Sometimes custom class loaders are used to implementing class versioning. Other custom class loaders allow you to create classes dynamically or switch implementations etc.

Conclusion

The "Could not find or load main class" error is common and easy to fix. Its cause usually has to do with specifying the wrong class name, extension, or class path.

This error can be easily fixed by checking IDE configurations, class path variables, class names, and making sure you're running the application from the right directory.

The JRE utilizes a class loading mechanism to dynamically load classes into memory. This mechanism relies on a recursive process where class loaders delegate retrieval to parent loaders if they can't find the class already loaded in memory.

You can create your own custom class loaders for dynamic class creation and versioning.

Your thoughts?