You use either -jar or -cp, you can't combine the two. If you want to put additional JARs on the classpath then you should either put them in the main JAR's manifest and then use java -jar or you put the full classpath (including the main JAR and its dependencies) in -cp and name the main class explicitly on the command line

java -cp 'MyProgram.jar:libs/*' main.Main

(I'm using the dir/* syntax that tells the java command to add all .jar files from a particular directory to the classpath. Note that the * must be protected from expansion by the shell, which is why I've used single quotes.)

You mention that you're using Ant so for the alternative manifest approach, you can use ant's <manifestclasspath> task after copying the dependencies but before building the JAR.

<manifestclasspath property="myprogram.manifest.classpath" jarfile="MyProgram.jar">
  <classpath>
    <fileset dir="libs" includes="*.jar" />
  </classpath>
</manifestclasspath>

<jar destfile="MyProgram.jar" basedir="classes">
  <manifest>
    <attribute name="Main-Class" value="main.Main" />
    <attribute name="Class-Path" value="${myprogram.manifest.classpath}" />
  </manifest>
</jar>

With this in place, java -jar MyProgram.jar will work correctly, and will include all the libs JAR files on the classpath as well.

Answer from Ian Roberts on Stack Overflow
Top answer
1 of 4
178

You use either -jar or -cp, you can't combine the two. If you want to put additional JARs on the classpath then you should either put them in the main JAR's manifest and then use java -jar or you put the full classpath (including the main JAR and its dependencies) in -cp and name the main class explicitly on the command line

java -cp 'MyProgram.jar:libs/*' main.Main

(I'm using the dir/* syntax that tells the java command to add all .jar files from a particular directory to the classpath. Note that the * must be protected from expansion by the shell, which is why I've used single quotes.)

You mention that you're using Ant so for the alternative manifest approach, you can use ant's <manifestclasspath> task after copying the dependencies but before building the JAR.

<manifestclasspath property="myprogram.manifest.classpath" jarfile="MyProgram.jar">
  <classpath>
    <fileset dir="libs" includes="*.jar" />
  </classpath>
</manifestclasspath>

<jar destfile="MyProgram.jar" basedir="classes">
  <manifest>
    <attribute name="Main-Class" value="main.Main" />
    <attribute name="Class-Path" value="${myprogram.manifest.classpath}" />
  </manifest>
</jar>

With this in place, java -jar MyProgram.jar will work correctly, and will include all the libs JAR files on the classpath as well.

2 of 4
30

When the -jar option is used the -cp option is ignored. The only way to set the classpath is using manifest file in the jar.

It is easier to just use the -cp option, add your jar file to that, then explicitly call the main class.

Also, assuming the /home/user/java/MyProgram/jar/libs folder contains jar files (as opposed to class files) this won't work. You cannot specify a folder of jar file but must specify each jar file individually in the classpath (it is worth writing a simple shell script to do this for you if there are a significant number of jars).

🌐
Oracle
docs.oracle.com › javase › tutorial › deployment › jar › downman.html
Adding Classes to the JAR File's Classpath (The Java™ Tutorials > Deployment > Packaging Programs in JAR Files)
Manifest-Version: 1.0 Class-Path: MyUtils.jar MyLibs/Lib.jar MyResources/ Created-By: 1.8.0_422 (Oracle Corporation) Consequently, when the Java application is launched from within the MyApp directory, the classes in MyJar.jar, in addition to being able to access the classes and resources that are part of MyJar.jar, can also access classes and resources that are contained in the MyUtils.jar and MyLibs/Lib.jar JAR files and the MyResources/ directory.
Discussions

Understanding Java classpath.
A .jar file is really just a zipfile with a bunch of classes inside, these classes are generally inside packages (namespaces) that match a directory structure. So a jar is really just a directory tree with classes. The classpath is just a complete directory tree of classes that gets formed from the standard library (java.util.List, etc.), the librarary jar files (CoolFramework.jar for example), and your own source code. This 'classpath' is really just an in-memory directory tree. So if you use org.javaguy.coolframework.SomeClass in your code, the JVM knows to look in ./org/javaguy/coolframework for a SomeClass.class file and load that. More on reddit.com
🌐 r/learnprogramming
4
2
January 13, 2021
command line - Including all the jars in a directory within the Java classpath - Stack Overflow
Is there a way to include all the jar files within a directory in the classpath? I'm trying java -classpath lib/*.jar:. my.package.Program and it is not able to find class files that are certainly... More on stackoverflow.com
🌐 stackoverflow.com
Executable jar with an external class path reference
Hmm, not sure you can use wildcards in a manifest Class-Path, but you should be able to list the dependencies individually e.g. Class-Path: conf/dependency_one.jar conf/next_dependency.jar Kind of annoying, but should work.. More on reddit.com
🌐 r/java
17
7
November 11, 2012
Java default ClassPath environment variable - Stack Overflow
I accidentally changed my Classpath environment variable in Windows system properties and am now getting a heap of errors on execution, what is the default? What should I be pointing it towards? M... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Chilkat
chilkatsoft.com › java-classpath-Windows.asp
Java JAR Archives and classpath on Windows
javac -classpath ".;C:/chilkatJava/chilkat.jar" Test.java java -classpath ".;C:/chilkatJava/chilkat.jar" Test
🌐
Medium
medium.com › javarevisited › back-to-the-basics-of-java-part-1-classpath-47cf3f834ff
Tutorial on how Java classpath works | Javarevisited
May 15, 2022 - The classpath is simply a list of directories, JAR files, and ZIP archives to search for class files [1]. The runtime needs to know where to find your compiled classes so that’s what you’re providing here.
🌐
Reddit
reddit.com › r/learnprogramming › understanding java classpath.
r/learnprogramming on Reddit: Understanding Java classpath.
January 13, 2021 -

I was surfing stackoverflow, trying to better understand what the classpath is all about and came upon this question/answer. It mostly makes sense, but there are two slightly confusing paragraphs in the accepted answer that go:

First, let's suppose that MyClass is something you built as part of your project, and it is in a directory in your project called output. The .class file would be at output/org/javaguy/coolframework/MyClass.class (along with every other file in that package). In order to get to that file, your path would simply need to contain the folder 'output', not the whole package structure, since your import statement provides all that information to the VM.

Now let's suppose that you bundle CoolFramework up into a .jar file, and put that CoolFramework.jar into a lib directory in your project. You would now need to put lib/CoolFramework.jar into your classpath. The VM will look inside the jar file for the org/javaguy/coolframework part, and find your class.

I don't understand the two sentences that say:

You would now need to put lib/CoolFramework.jar into your classpath. The VM will look inside the jar file for the org/javaguy/coolframework part, and find your class.

Why would the VM "look inside the jar file for the org/javaguy/coolframework part"? Why does that structure exist within the jar file? The answer mentions that you bundle "CoolFramework up into a .jar file", so why would that include the org/javaguy/coolframework hierarchy? Isn't CoolFrameWork just a single directory?

🌐
UCSB
sites.cs.ucsb.edu › ~cappello › 50-2005-Winter › lectures › classpath.html
Setting the class path
For example, to use a class library that is in a .jar file, the command would look something like this: % java -classpath /java/MyClasses/myclasses.jar utility.myapp.Cool
Find elsewhere
🌐
Michigan State University
web.pa.msu.edu › reference › jdk-1.2.2-docs › tooldocs › solaris › classpath.html
Setting the class path
For example, to use a class library that is in a .jar file, the command would look something like this: % java -classpath /java/MyClasses/myclasses.jar utility.myapp.Cool
Top answer
1 of 16
1340

Using Java 6 or later, the classpath option supports wildcards. Note the following:

  • Use straight quotes (")
  • Use *, not *.jar

Windows

java -cp "Test.jar;lib/*" my.package.MainClass

Unix

java -cp "Test.jar:lib/*" my.package.MainClass

This is similar to Windows, but uses : instead of ;. If you cannot use wildcards, bash allows the following syntax (where lib is the directory containing all the Java archive files):

java -cp "$(printf %s: lib/*.jar)"

(Note that using a classpath is incompatible with the -jar option. See also: Execute jar file with multiple classpath libraries from command prompt)

Understanding Wildcards

From the Classpath document:

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

A class path entry that contains * will not match class files. To match both classes and JAR files in a single directory foo, use either foo;foo/* or foo/*;foo. The order chosen determines whether the classes and resources in foo are loaded before JAR files in foo, or vice versa.

Subdirectories are not searched recursively. For example, foo/* looks for JAR files only in foo, not in foo/bar, foo/baz, etc.

The order in which the JAR files in a directory are enumerated in the expanded class path is not specified and may vary from platform to platform and even from moment to moment on the same machine. A well-constructed application should not depend upon any particular order. If a specific order is required then the JAR files can be enumerated explicitly in the class path.

Expansion of wildcards is done early, prior to the invocation of a program's main method, rather than late, during the class-loading process itself. Each element of the input class path containing a wildcard is replaced by the (possibly empty) sequence of elements generated by enumerating the JAR files in the named directory. For example, if the directory foo contains a.jar, b.jar, and c.jar, then the class path foo/* is expanded into foo/a.jar;foo/b.jar;foo/c.jar, and that string would be the value of the system property java.class.path.

The CLASSPATH environment variable is not treated any differently from the -classpath (or -cp) command-line option. That is, wildcards are honored in all these cases. However, class path wildcards are not honored in the Class-Path jar-manifest header.

Note: due to a known bug in java 8, the windows examples must use a backslash preceding entries with a trailing asterisk: https://bugs.openjdk.java.net/browse/JDK-8131329

2 of 16
287

Under Windows this works:

java -cp "Test.jar;lib/*" my.package.MainClass

and this does not work:

java -cp "Test.jar;lib/*.jar" my.package.MainClass

Notice the *.jar, so the * wildcard should be used alone.


On Linux, the following works:

java -cp "Test.jar:lib/*" my.package.MainClass

The separators are colons instead of semicolons.

🌐
Baeldung
baeldung.com › home › java › jvm › ways to add jars to classpath in java
Ways to Add JARs to Classpath in Java | Baeldung
August 19, 2025 - It’s important to note that the ... of the Java installation is a legacy mechanism, where JAR files placed in it are automatically added to the classpath....
🌐
Coderanch
coderanch.com › t › 405278 › java › classpath-works-executable-Jars
How classpath works for executable Jars (Beginning Java forum at Coderanch)
Yes. CLASSPATH environment variables and the -classpath switch are both ignored when Java is running an executable jar.
🌐
Reddit
reddit.com › r/java › executable jar with an external class path reference
r/java on Reddit: Executable jar with an external class path reference
November 11, 2012 -

I have packaged my application as an executable jar, but I need to be able to include a directory outside of the jar on the classpath.

The folder structure is as follows and I am trying to include the conf directory

/project/test-SNAPSHOT.jar
/project/conf
/project/suites
/project/run.sh

I tried adding the class path argument to the java command in the run.sh, but learned that when -jar is used the classpath argument is ignored

java -classpath .:conf/ -jar test-SNAPSHOT.jar suites/audit.xml

I also tried adding the the Class-Path attribute to the manifest

Manifest-Version: 1.0
Build-Jdk: 1.6.0_35
Built-By: Luvmysubi
Created-By: Apache Maven
Main-Class: org.testng.TestNG
Archiver-Version: Plexus Archiver
Class-Path: conf/*

But when this is done java complains that it cannot find the Main-Class attribute.

Failed to load Main-Class manifest attribute from
test-SNAPSHOT.jar

Any ideas? The only thing I can think of is bundling all of the dependencies into a lib folder instead of using a single jar.

*formatting

🌐
JustAnswer
justanswer.com › computer-programming › 4seza-java-adding-jar-classpath-just-running.html
Java: Adding a .jar to the classpath. Just running through ...
Bring your computer programming questions to programming Experts on JustAnswer. Ask a programmer online and get answers ASAP.
🌐
Coderanch
coderanch.com › t › 552278 › java › Set-library-classpath-runnable-JAR
Set library classpath inside runnable JAR file (Java in General forum at Coderanch)
September 11, 2011 - You cannot put JAR files inside JAR files - Java does not support that, it will not be able to load classes from the embedded JAR file.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-set-classpath-when-class-files-are-in-jar-file-in-java
How to Set Classpath When Class Files are in .jar file in Java? - GeeksforGeeks
July 23, 2025 - Each classpath should end with a filename or directory depending on what you are setting the classpath. For a .jar or .zip file that contains .class files, the class path ends with the name of the .zip or .jar file.
Top answer
1 of 2
2

The ClassPath environment variable is only used when you want your computer to look at a specific location for your .class files; generally speaking, it doesn't exist unless you make it exist, whether on purpose or a side effect of some installer.

Most of the time, the applications you are running (primarily JRE), know exactly where to look for .class files. Most of the time.

However, if you were refering to the PATH environmental variable, that can be more of an issue.

Oracle has a throughout step-by-step on setting your enviromental variables (I can vouch, I just had to reset my PATH this morning): http://docs.oracle.com/javase/tutorial/essential/environment/paths.html

However, here are the steps as I remember them:

  1. Start Menu, right click Computer, Choose Properties
  2. Advanced System on the far left, and there is an Enviromental Variables button near the bottom, click it
  3. In the bottom context menu, find the PATH variable and choose edit
  4. Put a semicolon after the last one, and then add "C:\Program Files\Java\jre7\lib;" and "C:\Program Files\Java\jre7\bin;" or wherever your java "lib" and "bin" folders are

And then you should be all swell and dandy, no harm no fowl.

2 of 2
2

The difault of CLASSPATH environment variable is nothing, i.e. by default this variable does not exist. If you had something defined you should know what did you define. If you do not know, try to analyze your stack trace and understand what is needed to your application to work.

If you have problems, send your stack trace here and we will try to help you.

🌐
Assertnotmagic
assertnotmagic.com › 2020 › 03 › 03 › java-classpath-mystery
assert_not magic? | Java Programs, Packages, and Class Paths Explained… Plus a Bonus Mystery
March 3, 2020 - Java defaults to searching your current directory for any classes it needs. But if you want to point it somewhere else, you have a couple of options: Use the -cp|--classpath option when running the java and javac commands from the command line.
🌐
Reddit
reddit.com › r/javahelp › how to define classpath variable when compiling? absolute path or relative?
r/javahelp on Reddit: How To Define ClassPath Variable When Compiling? Absolute Path Or Relative?
June 3, 2023 -

Yes I know if I use an IDE, it will handle all this automatically. But just for the sake of learning, I'm curious.

I've been figuring out how to compile a package and a regular class file on the command line (Bash).

My project is organized into folders like this.

 /classes

 /src
   /mainDir
      -main.java
   /sortersDir
      -bubbleSorter.java

bubbleSorter . java has this package statement in the beginning:

 package sorterClasses;

When I open bash at the project root directory, and type in:

 " javac -d classes src/sorters/bubbleSorter.java "

I am able to see that there is now a folder within the classes folder called " sorterClasses " and my bubbleSorter . class file is in there.

I then try to compile the main . java file by typing in:

 " javac -d classes -cp classes src/main.main.java " 

and the statement executes with no errors.

But then when I try to run the main class file on the terminal with

" java classes/main " 

it gives me an error saying " could not find or load main classes classes.main Caused by: java.lang.NoClassDefFoundError: main (wrong name: classes/main).

I then also tried typing in

" java -cp ./classes classes/main "

and it said " error: could not find or load main class classes.main "

Which makes me wonder....am I specifying the classpath correctly? Should I put down the entire absolute path? Like: ' C:/JavaPractice/Project1 ' ? Or just the relative path based on where the bash terminal currently is? That's what I did before. I added in the dot ( . ) to specify the current directory and then wrote classes to designate the classes folder.

Also correct me if I'm wrong, but you only need to specify the -cp option when you're compiling a file that uses other classes right? The -cp option is meant to figure out where to import classes from, and the -d option is meant to figure out where to export the compiled files?

Top answer
1 of 3
2
Why don’t you put two files in the same package?
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Medium
medium.com › @benizizamohamed › classpath-in-java-8e3cc6d049b
ClassPath in Java 😊
August 12, 2023 - Yeah, that is correct; a classpath is a path for the compiler to identify which class, or which package we use in our defined class. It provides the compiler a way to find classes or packages that are used in our class.
🌐
Coderanch
coderanch.com › t › 643884 › java › classpath-java-Head-Java-Edition
What exactly is a classpath in java? Head First Java 2nd Edition (Beginning Java forum at Coderanch)
EXAMPLE I've got a package: pl\corso\simple Inside path: C:\Java Projects\Lib\pl\corso\simple Inside directory simple I've got public class called List.java which belongs to pl.corso.simple package and I've got a public class outside the package which uses pl.corso.simple package (exacly uses ...