Package Troubleshooting

I had trouble with my early Java programs when I would use packages. If I left my files in the default package, it worked fine. But when I added them to a package, I could build them fine—just not run them. I found it to be a common problem among other students and I spent far too much time trying to search for an answer.

ExampleWithPackage.java source:

package com.moronicbajebus; 

public class ExampleWithPackage {
	public static void main(String[] args) {
		//…
	}
}

The error output from running it in the command line from the directory ‘working-directory’:

.../working-directory>java ExampleWithPackage
Exception in thread "main" java.lang.NoClassDefFoundError: ExampleWithPackage (wrong name: com/moronicbajebus/ExampleWithPackage)
        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)

The java files must be in directory tree that matches the package name from the working directory (the one you are in if you are using a command line). I need to create a directory named ‘com’ in ‘working-directory’; and then, I need to create a directory named ‘moronicbajebus’ in the newly created ‘com’ directory. Then I place ‘ExampleWithPackage.java’ in the ‘moronicbajebus’ directory.

Now the program will run with one more minor change, Now the program will run with one more minor change, I have to also give the package with the class:
.../working-directory>java com.moronicbajebus.ExampleWithPackage

Remember don’t choke your computer, choke your dog.