Solution:
This error can occur for a couple of reasons. Let me walk through every possible solution step by step.
1. Calling .class file from java command:
public class HelloWorld {
public static void main(String args[]) {
System.out.println(" Hello World !");
}
}
Let's assume I have the basic program above. If I will compile it using the command, HelloWorld.class will be created.
javac HelloWorld.java
Now I want to run the .class file. I will get the error message if I run
java HelloWorld.class
Instead of
java HelloWorld
2. Incorrect Casing: We all know that Java is a case sensitive language. We need to keep in mind whenever we declare a variable, function or even class name.
So, we’ll get the error message if we run
java helloworld
instead of
java HelloWorld
3. Class in a package
Have a close look at the program below.
package com.naymulhasan;
/**
* Java program to demonstrate
* Error :Could not find or load main class
*
* @author Naymul Hasan
*/
public class HelloWorld {
public static void main(String args[]) {
System.out.println(" Hello World !");
}
}
Here I have HelloWorld class inside com.naymulhasan package. In this case, if I try to call
java HelloWorld
it will give the same error message. Because I had to call the class file with the package name. Let me try this one
java com.naymulhasan.HelloWorld
Oops! I am still getting the error message because the CLASSPATH environment variable is not set. Let’s try with the CLASSPATH command -cp
java -cp . com.naymulhasan.HelloWorld
BOOM. You are all set now.