Saturday, June 28, 2008

Running Java classes with packages in Command Prompt*

Saturday, June 28, 2008 7:31:54 PM (GMT Standard Time, UTC+00:00)

For a few hours today I've been fighting with a java problem so in the interest of goodwill I've documented it and the solution below. I think for someone new to java (or someone who hasn't used it in ages aka me) this will be rather useful.

The problem: I wanted to run a Java file 'he.java', which is in a Java package (and Windows directory) called 'her'. Below you can see that when I compiled everything went fine, however when I tried to run the file that became somewhat of a problem! ..

R:\tech\her>javac he.java
R:\tech\her>java he
Exception in thread "main" java.lang.NoClassDefFoundError: he (wrong name: her/he)
        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$000(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)

The solution:
1. Because of the package the command will actually be "java her.he"
2. With that command alone, Java will look for "her.he.class" in "her" directory. However, because you are already in the "her" directory, you'll likely get the same error again, so you need to go up a directory i.e. "cd .."
3. Now try "java her.he"
R:\tech\>java he
Hello Jason!

I thank this article for enlightening me on this exception. It also has more detail, therefore I recommend it if you're interested.

Related posts:
Learning LaTeX and Eclipse
Including jar files in your projects in Eclipse
How to set CLASSPATH (and PATH) for Java in Linux
How to set PATH and CLASSPATH for Java in Vista

Comments are closed.