R.A.M. said:
java Main produces:
Exception in thread "main" java.lang.NoClassDefFoundError: Main
(wrong name: helloworld/Main)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown
Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
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)
See the second line where it says "wrong name helloworld/Main"?
That's because you've got a package name and you're not using it to
invoke the class. You need to include the package name as part of
the class name with a dot separator (after copying the file to the
correct location.)
Example:
1. Source and compiled class are currently in
c:\JavaProjects\MainSample
2. Create a directory under MainSample named helloworld. Package
names require the compiled class to be in a named subdirectory.
3. Copy Main.class to helloworld.
4. From the source directory type:
java -classpath c:\JavaProjects\MainSample helloworld.Main
Note that helloworld.Main is not just Main. It can be considered
like a "virtual class name". It includes the package. That's how
the JVM knows which class you want to run (you could have Main
classes in other packages.)
The -classpath argument tells the compiler the ROOT to the top
level directory of the package. So *after* the classpath arg you
must provide the the class name, but since you have a package in
the name it has to include that too. The oddity is that you don't
give the JVM helloworld/Main, you give it helloworld.Main. The JVM
figures out that the dot separator indicates a backslash or slash.
There is a lot more to know about classpaths too. You can get into
a lot of trouble by ignoring classpath issues. Once you start
using jar files it changes things, so don't rush past learning
about packages and classpath now.