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.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.