Receiving “wrong name” NoClassDefFoundError when executing a Java program from the command-line

Because I found these answers unclear, here is what you need to do.
First, if you package your code (IE your classes have the package keyword at the top) the compiled classes have to be in a directory with the same name as your package declaration in code. After you have compiled your classes, you need to move up a directory when you exectute the java command, and you include the name of the package. For example, if your code exists in /myFolder/myPackage/ , and your class starts with package myPackage (note that the directory and the package are the same name), then you would do the following (linux / osx):

cd /myFolder/myPackage

javac MyClass.java 

cd ..

java myPackage.MyClass

Edit – A late edit to clarify something I see people get confused on. In the example above, the package is only one deep, meaning its just myPackage. If you code has a larger package, like

package com.somedomain.someproject;

you will need to execute the java command from the directory which contains the root directory for that package. For example if your compiled code is in myCode/com/somedomain/someproject/MyMainClass.class, then you will execute the java command from the myCode folder, like this (Again, take special note that the directory structure is the same as the package declaration):

cd /myCode
java com.somedomain.someproject.MyMainClass

Leave a Comment