I've compiled a HelloWorld program, and I'm using the command prompt to run it. The .class file is named HelloWorld2.class
The file is located in C:\Users\Matt\workspace\HelloWorld2\bin Here's what I'm getting when I go to command prompt, and type "Java HelloWorld2" :
C:\Users\Matt>Java HelloWorld2
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld2
Caused by: java.lang.ClassNotFoundException: HelloWorld2
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: HelloWorld2. Program will exit.
I was expecting to see a HelloWorld printed out. What am I doing wrong? I have the JDK installed.
You need to set the classpath to find your compiled class:
java -cp C:\Users\Matt\workspace\HelloWorld2\bin HelloWorld2
To run Java class file from the command line, the syntax is:
where packageName (usually starts with either
com
ororg
) is the folder name where your class file is present.For example if your main class name is App and Java package name of your app is
com.foo.app
, then your class file needs to be incom/foo/app
folder (separate folder for each dot), so you run your app as:Note:
$
is indicating shell prompt, ignore it when typingIf your class doesn't have any
package
name defined, simply run as:java App
.If you've any other jar dependencies, make sure you specified your classpath parameter either with
-cp
/-classpath
or usingCLASSPATH
variable which points to the folder with your jar/war/ear/zip/class files. So on Linux you can prefix the command with:CLASSPATH=/path/to/jars
, on Windows you need to add the folder into system variable. If not set, the user class path consists of the current directory (.
).Practical example
Given we've created sample project using Maven as:
and we've compiled our project by
mvn compile
in ourmy-app/
dir, it'll generate our class file is intarget/classes/com/foo/app/App.class
.To run it, we can either specify class path via
-cp
or going to it directly, check examples below:To double check your class and package name, you can use Java class file disassembler tool, e.g.:
Note:
javap
won't work if the compiled file has been obfuscated.This can mean a lot of things, but the most common one is that the class contained in the file doesn't have the same name as the file itself. So, check if your class is also called HelloWorld2.