How to execute a java .class from the command line

Viewed 436982

I have a compiled java class:

Echo.class

public class Echo {
    public static void main (String arg) {

            System.out.println(arg);
    }
}

I cd to the directory and enter: java Echo "hello"

I get this error:

C:\Documents and Settings\joe\My Documents\projects\Misc\bin>java Echo "hello"
Exception in thread "main" java.lang.NoClassDefFoundError: Echo
Caused by: java.lang.ClassNotFoundException: Echo
        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)
        at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Could not find the main class: Echo.  Program will exit.

What is the simplest way to get my java code in a form that I can run from the command line as apposed to having to use Eclipse IDE?

7 Answers

With Java 11 you won't have to go through this rigmarole anymore!

Instead, you can do this:

> java MyApp.java

You don't have to compile beforehand, as it's all done in one step.

You can get the Java 11 JDK here: JDK 11 GA Release

Related