Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Troubleshoot NoClassDefFoundError in Java

I have a Java program called Main.java, it is located in the following directory:

/home/user/program/Main.java

When I try to run Main.java from the 'program' directory, everything goes ok, I use this line:

/home/user/program$ java Main

But when I try to run Main.java from the home directory :

/home$ java /home/user/program/Main

I get :

Exception in thread "main" java.lang.NoClassDefFoundError: /home/user/program/Main
Caused by: java.lang.ClassNotFoundException: .home.user.program.Main

What is the cause of this error?

like image 399
shaw Avatar asked Mar 21 '11 10:03

shaw


2 Answers

This is due to your classpath, which will default to the current directory. When you run java Main from /home/user/program it finds the class in the current directory (since the package seems to be unset, meaning it is the default). Hence, it finds the class in /home/user/program/Main.class.

Running java /home/user/program/Main from /home tries to find the class in the classpath (the current directory) which will look in /home/home/user/program expecting to find the file Main.class containing a definition of the Main class with package .home.user.program.

Extra detail: I think the java launcher is trying to be nice by converting /-notation for a classname to the .-notation; and when you run java /home/user/program/Main it is actually running java .home.user.program.Main for you. This is because you shouldn't be specifying a file, but a fully specified classname (ie including package specifier). And when a class has a package java expects to find that class within a directory structure that matches the package name, inside a directory (or jar) in the classpath; hence, it will try to look in /home/home/user/program for the class file

You can fix it by specifying your classpath with -cp or -classpath:

java -cp /home/user/program Main
like image 143
Mike Tunnicliffe Avatar answered Sep 22 '22 05:09

Mike Tunnicliffe


Because its looking for the class using the fullname you give (/home/user/program/Main). You should only look for the Main class but using the good classpath : java Main -cp /home/user/program

Which means it'll search the Main class in the given set of paths

like image 34
Michael Laffargue Avatar answered Sep 26 '22 05:09

Michael Laffargue