Resolving 'Main Class Not Found' Error When Running Java in CMD
Resolving the "Main Class Not Found" Error in Java (CMD Execution)
When developing Java applications, running programs via the command prompt (CMD) is a common practice. However, you may encounter the "main class not found" error, which typically stems from incorrect main class specification or classpath issues. This guide outlines solutions and includes code examples for clarity.
Problem Analysis
To run a Java program, you use a command like:
java MainClass
The "main class not found" error arises due to:
- An incorrect or unspecified main class name.
- A misconfigured classpath, preventing Java from locating the class.
Solutions
Verify the Main Class Name
Ensure the main class name is correct and explicitly specified. To include the current directory in the classpath (so Java finds your class), use:
java -cp . MainClass
The -cp . flag sets the classpath to the current directory (.).
Configure the Classpath
If your main class depends on other classes (e.g., in a lib directory), add their location to the classpath:
java -cp .;lib/* MainClass
Here, lib/* includes all class files in the lib directory. This ensures Java locates both the main class and its dependencies.
Check Compilation
Ensure your Java source file is successfully compiled. If compilation fails, Java cannot find the corresponding .class file. Compile your code with:
javac MainClass.java
Only proceed to run the program after successful compilation.
Code Example
Below is a simple Java program to demonstrate correct main class usage:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Greetings! The program ran successfully.");
}
}
Save this code as HelloWorld.java. After compiling (using javac HelloWorld.java), run it with:
java HelloWorld
If everything works, you’ll see Greetings! The program ran successfully. in the console.
Troubleshooting Tips
- Classpath: If using external libraries, include their paths (e.g.,
java -cp .;path/to/libs/* MainClass). - Compilation: Ensure
javacoutputs a.classfile (e.g.,HelloWorld.classfor the example above).