30

So, I can do this very well:

java mypackage.MyClass

if ./mypackage/MyClass.class exists. I can also happily do this:

java -cp myjar.jar mypackage.MyClass

if the class file exists in the appropriate part of the jar. Easy stuff. But I can't for the life of me manage to do something like this:

java -cp utilities.jar mypackage.MyClass

where ./mypackage/MyClass.class exists, and where ./utilities.jar exists (not containing MyClass, of course).

Am I about to feel stupid?

4 Answers 4

61

Possibly :)

# On Unix
java -cp utilities.jar:. mypackage.MyClass

# On Windows
java -cp utilities.jar;. mypackage.MyClass

Basically that's just including . (the current directory) on the classpath as well as the jar file.

5
  • Is -cp a short form for -classpath? Dec 6, 2017 at 12:03
  • @overexchange: Yes. (Running java -? would have told you that.)
    – Jon Skeet
    Dec 6, 2017 at 12:03
  • this is not working for me.... java -cp argparse4j-0.9.0.jar:. Demo Error: Could not find or load main class Demo Caused by: java.lang.ClassNotFoundException: Demo
    – rica01
    Sep 30, 2021 at 21:55
  • @rica01: Well is Demo.class in the current directory? We can't really tell much just from that. (And what operating system are you using?)
    – Jon Skeet
    Oct 1, 2021 at 5:41
  • it was. I honestly gave up on this, it was taking tooooooo much time for something that should be extrasimple. thanks anyways jon!
    – rica01
    Oct 1, 2021 at 9:04
7

Try this if you're on Windows:

java -cp .;utilities.jar mypackage.MyClass

Or this if you're on Linux:

java -cp .:utilities.jar mypackage.MyClass

The current directory is not in the CLASSPATH by default when you specify a value for -cp.

2
  • No, the current directory is the classpath by default; it's only when you specify a different classpath that you get problems.
    – Jon Skeet
    Jun 20, 2011 at 10:06
  • @Vuntic: That would certainly be accurate. Maybe @duffymo would like to edit to that wording :)
    – Jon Skeet
    Jun 20, 2011 at 10:12
1

The question seems dated. But there is no answer mentioning the feature of running source file directly without using javac first, applicable for JDK 11+.

On linux:

java -cp some-library.jar:some-other-library.jar AClassName.java

On windows:

java -cp "some-library.jar;some-other-library.jar" AClassName.java
-1

You should include the mypackage.MyClass into the CLASSPATH or the -cp parameter. For example:

java -cp utilities.jar;myjar.jar mypackage.MyClass

The path separator is ; on windows and : on Unix/Linux

1
  • that I can do just fine; MyClass is in a standalone class file, not myjar.jar
    – amara
    Jun 20, 2011 at 10:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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