NoClassDefFoundError Could not find the main class

A common question that programmers new to Java have is what is the relationship between packages, javac, java, and the NoClassDefFoundError.

It is important to understand that there is a relationship between the package and physical directory structure.  For example, if you have a class "MyClass" and it is in a package com.myapp, you would want the following file structure

MyProject
   |--source
      |--com
          |--myapp
              |--MyClass.java
   |--classes

MyClass.java would have package com.myapp; at the top of the file.  Then from the source directory, you could issue the following to compile and place the class file in MyProject/classes/com/myapp/MyClass.class

javac -d ../classes com.myapp.MyClass.java

The result would be that the compiler would create the directories under /classes (note classes needs to exist).  Now, to run MyClass, issue the following from the classes directory:

java com.myapp.MyClass

It is important to realize that when compiling and running that the package name, fully qualified class name, and location you issue javac and java from are all important.

 

 

Add comment