Lỗi "Error: Could not find or load main class" xảy ra khi JVM không tìm thấy class chứa main() để chạy.
Các nguyên nhân & Cách fix
1. Sai tên class (Typo)
D:\> javac Example.java D:\> java Exmple # Thiếu 'a' Error: Could not find or load main class Exmple
Fix: Gõ đúng tên class: java Example.
2. Sai chữ hoa/thường (Case-sensitive)
D:\> java EXAMPLE # Class tên Example Error: Could not find or load main class EXAMPLE Caused by: java.lang.NoClassDefFoundError: Example (wrong name: EXAMPLE)
Fix: Giống hệt khai báo: java Example.
3. Sai package / Thiếu package
// File: sample/Example.java
package sample;
class Example { public static void main(String[] args) {...} }
D:\> javac -d . Example.java D:\> java samp.Example # Sai package Error: Could not find or load main class samp.Example
Fix: Dùng đúng package: java sample.Example (chạy từ thư mục root chứa package).
4. Thêm đuôi .class khi chạy
D:\> java Example.class Error: Could not find or load main class Example.class
Fix: Không thêm .class: java Example.
5. Classpath không chứa thư mục class
D:\> java -cp /other/path Example Error: Could not find or load main class Example
Fix: java -cp . Example (chạy từ thư mục chứa class) hoặc java -cp D:\path\to\classes Example.
Checklist nhanh
- Biên dịch thành công:
javac Example.javacó fileExample.class? - Chạy từ đúng thư mục chứa
.class(hoặc package root)? - Tên class chính xác (case-sensitive)?
- Không thêm
.class? - Có package? → Dùng fully qualified name:
java pkg.Main. - Có dependency JAR? →
java -cp ".;lib/*" pkg.Main.