Core Java

Include Jars In Java Classpath Example

In Java, the classpath is a crucial parameter that tells the Java Virtual Machine (JVM) where to find compiled class files, including user-defined classes and external libraries packaged as JAR files. By default, the JVM searches for classes in the current working directory (.) and the JDK’s standard libraries. However, real-world Java applications often rely on third-party libraries such as Spring, Hibernate, Apache Commons, etc., which are distributed as JAR files. To use these libraries, developers must correctly configure the classpath to include Jars, so that the JVM can locate and load them at runtime. If the classpath is not set correctly, you might encounter errors such as:

1
Exception in thread "main" java.lang.NoClassDefFoundError: com/example/HelloWorld

or:

1
Exception in thread "main" java.lang.ClassNotFoundException: com.example.HelloWorld

Let us delve into understanding how the Java classpath can be setup to include JARs and the various ways to configure it effectively.

1. Using -cp or -classpath on the Command Line

You can specify JAR files on the command line using the -cp (or -classpath) option when executing a Java program. This method is useful when running Java programs manually without using an Integrated Development Environment (IDE) or build tools. For example, suppose we have a JAR file named example.jar containing a class com.example.HelloWorld. We can run the program as follows:

1
java -cp example.jar com.example.HelloWorld

1.1 Using Multiple JAR Files

In many cases, an application may require multiple JAR files. You can specify multiple JARs in the classpath using a colon (:) on Linux/Mac or a semicolon (;) on Windows:

1
java -cp "example.jar:lib/helper.jar" com.example.HelloWorld

Here:

  • example.jar is the main JAR containing the application entry point.
  • lib/helper.jar is an additional JAR that the application depends on.

If the JAR files are located in different directories, make sure to provide the correct relative or absolute paths.

1.2 Using Wildcards for Multiple JARs

Instead of listing each JAR file explicitly, you can use a wildcard (*) to include all JARs in a directory.

1
java -cp "lib/*" com.example.HelloWorld

This will include all JAR files inside the lib directory in the classpath. Make note that the wildcard approach works natively in Java 6 and later but does not support recursive directory scanning.

2. Using CLASSPATH on the Command Line

Another way to specify the location of JAR files is by setting the CLASSPATH environment variable. This method is useful when you want to define the classpath once and avoid specifying it every time you run the Java program. By default, the JVM searches for classes in the current directory (.). However, when working with external JARs, you need to explicitly include them in the CLASSPATH variable.

2.1 Setting CLASSPATH Temporarily

You can set the CLASSPATH variable temporarily in a terminal session. The value remains valid only for the duration of that session.

1
2
export CLASSPATH=example.jar
java com.example.HelloWorld

To include multiple JARs, separate them using a colon (:) on Linux/Mac or a semicolon (;) on Windows.

3. Specifying the Classpath in a MANIFEST.MF File

When packaging a Java application as an executable JAR, you can specify dependencies directly in the META-INF/MANIFEST.MF file. This eliminates the need to manually provide the classpath when running the JAR.

3.1 Why Use a MANIFEST.MF File?

  • Simplifies execution by allowing users to run the JAR without specifying dependencies manually.
  • Makes it easier to distribute and deploy applications with all required libraries.
  • Encapsulates the classpath settings within the JAR itself.

3.2 Example: Creating a JAR with a Manifest File

To specify dependencies, create a MANIFEST.MF file inside the META-INF directory with the following content:

1
2
3
Manifest-Version: 1.0
Class-Path: lib/helper.jar lib/database.jar
Main-Class: com.example.MainClass

The Manifest-Version: 1.0 specifies the manifest file version, while the Class-Path: entry lists the external JARs required at runtime, using paths relative to the JAR file location. The Main-Class: defines the application’s entry point by specifying the class that contains the main method.

3.3 Packaging the JAR

Once the manifest file is created, package the application using the jar command:

1
jar cvfm myapp.jar META-INF/MANIFEST.MF -C bin/ .

The c option creates a new JAR file, while v enables verbose output. The f option specifies the filename of the JAR, and m includes the manifest file. Finally, -C bin/ . adds all compiled class files from the bin/ directory.

3.4 Running the Application

Once packaged, you can run the JAR file as follows:

1
java -jar myapp.jar

3.5 Important Considerations

The Class-Path entries in MANIFEST.MF should use relative paths instead of absolute paths. External JAR files must be placed in the correct location, such as a lib/ directory next to the main JAR. If any required JAR is missing, the application will fail with a ClassNotFoundException.

4. Adding JARs to the lib/ext Directory

In older Java versions (before Java 9), any JAR files placed in the lib/ext directory of the JDK/JRE were automatically included in the classpath without needing explicit configuration. This provided a simple way to share libraries across multiple Java applications. To use this approach, you would:

  • Copy example.jar to $JAVA_HOME/jre/lib/ext/ on Linux/Mac or C:\Program Files\Java\jre\lib\ext on Windows.
  • Run the Java program as usual without specifying the JAR in the classpath

However, this mechanism was removed in Java 9 due to security and modularization improvements introduced by Project Jigsaw. For modern Java versions, consider using explicit classpath settings or dependency management tools like Maven or Gradle.

5. Adding JARs in Eclipse/IntelliJ IDE

Modern IDEs like Eclipse and IntelliJ IDEA provide built-in mechanisms to easily add JAR files to your project’s classpath. Below are step-by-step instructions for both.

5.1 Adding JARs in Eclipse

To include external JARs in an Eclipse project:

  • Right-click on your project and select Build Path -> Configure Build Path.
  • Navigate to the Libraries tab and click Add External JARs....
  • Browse and select the required JAR file, then click Apply and Close.

Once added, Eclipse automatically includes the JAR in the classpath for compilation and execution.

5.2 Adding JARs in IntelliJ IDEA

To add external JARs in IntelliJ IDEA:

  • Go to File -> Project Structure -> Modules.
  • Click on the Dependencies tab and then click the + (Add) button.
  • Select JARs or directories..., browse to the JAR file location, and click OK.

IntelliJ will automatically include the JAR in the project’s classpath.

6. Using a Build Tool

For larger projects, manually adding JARs can be cumbersome. Instead, build tools like Maven and Gradle manage dependencies efficiently by automatically downloading required libraries.

6.1 Adding Dependencies with Maven

To add a JAR dependency in a Maven-based project, include it in the pom.xml file:

1
2
3
4
5
6
7
<dependencies>
    <dependency>
        <groupId>org.example</groupId>
        <artifactId>example-lib</artifactId>
        <version>1.0</version>
    </dependency>
</dependencies>

Maven will automatically download the dependency from the configured repository and include it in the project’s classpath.

6.2 Adding Dependencies with Gradle

For Gradle projects, add the dependency in the build.gradle file:

1
2
3
dependencies {
    implementation 'org.example:example-lib:1.0'
}

After updating the build file, run gradle build (or gradle sync in IDEs) to download and configure the dependency.

6.3 Why Use a Build Tool?

  • Automatically downloads and manages dependencies.
  • Reduces manual effort in configuring JAR files.
  • Ensures compatibility and version management across teams.

For modern Java projects, using a build tool like Maven or Gradle is highly recommended over manually adding JARs.

6. Conclusion

In this article, we explored various ways to add JARs to the classpath in Java, including using the command line, environment variables, manifest files, IDE settings, and build tools like Maven and Gradle. Choosing the right approach depends on your project requirements and setup.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button