Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

The use of CLASSPATH and the package statement

Starting out with Java

The use of CLASSPATH and the package statement

by  jfryer  Posted    (Edited  )
The use of and (relationship between) the
Code:
package
statement and the CLASSPATH seems to trip up many new Java developers, so I figured I post this as a FAQ to make it more accessable for all to read.

Code:
Exception in thread "main" java.lang.NoClassDefFoundError
means that the java virtual machine cannot find the class you are attempting to call.

The most likely cause is because you are using packages, these seems to trip most people up who have this problem.

For Example:
package com.mine;

class MyClass
{;}

the class you are calling here is NOT MyClass, it is com.mine.MyClass which needs to reside in a directory structure of com\mine\MyClass.java.
Now, to compile the above code you would use "javac com.mine.MyClass" and you would need to be in the directory that com resides in.
Example:
MyClass.java lives in c:\Java_Apps\com\mine\MyClass.java
javac needs to be run from c:\Java_Apps, because it is from there that javac can "see" the package com.mine
The use of packages tells the JVM the name AND location of a class file

The second catch is the use of CLASSPATH. This is the list of directories that java uses to look in to search for the packages you are calling. A stock standard CLASSPATH usually contains the . directory (ie the current directory) and the location of the Java libraries
Example:
CLASSPATH=.;c:\j2sdk140_1\lib

When javac or java is executed it looks in the current directory (the .) and in the java library directory (the c:\j2sdk140_1\lib) for the packages needed. If you have other packages in other locations that are needed then you can add them to your classpath.

Be careful, you cannot have CLASSPATH=c:\j2sdk140_1\lib;c:\Java_Apps\com\mine as a classpath and expect the above example to work. This is because java will look in
c:\j2sdk140_1\lib for a com\mine\ directory and then it will look in c:\Java_Apps\com\mine for a com\mine\ and obviously not find them.

There may be other reasons as well, for example the class file the JVM is unable to find may be missing totally (it's happened)

I hope this makes it somewhat clearer for those with questions.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top