Java Could not find or load main class
By:Roy.LiuLast updated:2019-08-11
A popular error message for new Java users.
Error: Could not find or load main class ClassName.class Caused by: java.lang.ClassNotFoundException: ClassName.class
1. No Package
1.1 Reviews a simple Java Hello World, no package.
C:\projects\HelloWorld.java
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World");
Terminal
# Compile Java source code C:\projects> javac HelloWorld.java C:\projects> dir 15/04/2019 01:20 PM 425 HelloWorld.class 15/04/2019 01:42 PM 138 HelloWorld.java # Run Java C:\projects>java HelloWorld.class Error: Could not find or load main class HelloWorld.class Caused by: java.lang.ClassNotFoundException: HelloWorld.class
To fix it, run java ClassName, without .class extension.
Terminal
C:\projects>java HelloWorld Hello World
2. With Package
2.1 A simple Hello World and package it as com.mkyong
C:\projects\HelloWorld.java
package com.mkyong; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World");
Terminal
# Compile Java source code C:\projects> javac HelloWorld.java C:\projects> dir 15/04/2019 01:20 PM 425 HelloWorld.class 15/04/2019 01:42 PM 138 HelloWorld.java C:\projects>java HelloWorld Error: Could not find or load main class HelloWorld Caused by: java.lang.NoClassDefFoundError: com/mkyong/HelloWorld (wrong name: HelloWorld)
2.2 If package is defined, the Java classes .class must place in the correct folder location.
For example :
C:\projects\HelloWorld.java
package com.mkyong;
The above generated class file must place in C:\projects\com\mkyong\HelloWorld.class
2.3 To fix it, we can use -d to specify where to place generated class files.
Terminal
# Compile Java source code C:\projects> javac -d . HelloWorld.java C:\projects> dir 15/04/2019 02:01 PM <DIR> com 15/04/2019 01:51 PM 161 HelloWorld.java C:\projects\com\mkyong\HelloWorld.class C:\projects\HelloWorld.java
2.4 Now, we can run like this java {package}.HelloWorld
Terminal
C:\projects>java HelloWorld Error: Could not find or load main class HelloWorld Caused by: java.lang.ClassNotFoundException: HelloWorld C:\projects>java com.mkyong.HelloWorld Hello World
From:一号门
COMMENTS