/errors/java/could-not-find-or-load-main-class
Error: Could not find or load main class
- tool
- Java
- exit code
- 1
- versions
- Java 11+, Java 17, Java 21, Java 25
- os
- any
Error: Could not find or load main class X means the JVM searched the class path for a class named X and found no matching .class file. Almost always the name or the class path is wrong: the class sits in a package and must be run by its fully qualified name (java com.example.Hello) from the root of the package tree, or with -cp pointing at that root. The Caused by: line says why: ClassNotFoundException when no file matches, NoClassDefFoundError ... (wrong name: ...) when a file was found but declares another fully qualified name.
Reproduce it
mkdir -p src/com/example
cat > src/com/example/Hello.java <<'EOF'
package com.example;
public class Hello {
public static void main(String[] args) { System.out.println("hello"); }
}
EOF
javac -d out src/com/example/Hello.java
java -cp out HelloOutput · exit 1
Error: Could not find or load main class Hello Caused by: java.lang.ClassNotFoundException: Hello
The class was compiled to out/com/example/Hello.class. Its name is com.example.Hello, so Hello alone matches nothing on the class path out.
Fix: fully qualified name and the right class path
mkdir -p src/com/example
cat > src/com/example/Hello.java <<'EOF'
package com.example;
public class Hello {
public static void main(String[] args) { System.out.println("hello"); }
}
EOF
javac -d out src/com/example/Hello.java
java -cp out com.example.HelloOutput
hello
Wrong-name variant
Running from inside the package folder finds the file but not the right class:
mkdir -p src/com/example
cat > src/com/example/Hello.java <<'EOF'
package com.example;
public class Hello {
public static void main(String[] args) { System.out.println("hello"); }
}
EOF
javac -d out src/com/example/Hello.java
cd out/com/example
java HelloOutput · exit 1
Error: Could not find or load main class Hello Caused by: java.lang.NoClassDefFoundError: Hello (wrong name: com/example/Hello)
Checklist
| Command | Problem |
|---|---|
| java Hello.class | Pass the class name, not the file name |
| java out/com/example/Hello | Use dots and the class path: java -cp out com.example.Hello |
| java -cp lib/a.jar:lib/b.jar Main (Windows) | Use ; as separator on Windows: lib\a.jar;lib\b.jar |
| java -jar app.jar | The JAR manifest needs a Main-Class entry |