6

I have a simple Java file Q.java that depends on an external library file X.jar. Both Q.java and X.jar are in the same directory. I can compile Q.java from the command line by doing: "javac -cp X.jar Q.java". This generates a Q.class file. How do I run this now? I tried all these:

1) java Q 2) java -cp X.jar Q

I keep getting a Exception in thread "main" java.lang.NoClassDefFoundError: Q Caused by: java.lang.ClassNotFoundException: Q

So how do I run this from the command line now that I have the class file?

2

2 Answers 2

11
java -cp X.jar:. Q

You have to specify in the classpath that you want to use the JAR dependency AND the current local directory to resolve classes.


Edit suggested in the comments:

On Windows, replace : by ;:

java -cp X.jar;. Q
1
  • 4
    In Windows, you have to use ";", not ":", so there it would be "java -cp X.jar;. Q"
    – Ed Staub
    Commented Aug 14, 2011 at 1:41
0

Set the current directory in your classpath, it should solve the problem. Most of the time, we need current directory in the classpath, so generally I advice to set "." (without quotes) in your system CLASSPATH environment variable instead of setting for each run.

Not the answer you're looking for? Browse other questions tagged or ask your own question.