Java Classpath
Learn how to set classpath in Java either as an environment variable and pass as the command-line argument. During runtime of any Java application, the CLASSPATH is a parameter that tells the JVM where to look for classes and packages.
- The default value of the classpath is “ . ” (dot) , meaning that only the current directory is searched for dependencies.
- Specifying either the CLASSPATH environment variable or the -cp command line switch overrides this value.
- The order in which you specify multiple classpath entries is important. The Java interpreter will look for classes in the directories in the order they appear in the classpath variable.
Java Classpath separators are OS specific.
Windows – ; [Semicolon]Linux/Unix – : [Colon]
1. Setting CLASSPATH as Environment Variable
When you have set the location of jar files that are always required during the application runtime, then it’s probably best to add them in the machine’s environment variable ‘CLASSPATH’ .
During application runtime, application class loader will always scan the jar files and classes at specified paths in this variable.
To set CLASSPATH environment variable, find the location of user environment variables in your machine and add all paths where Jar files are stored. Use the separator between different two folders, jar files or classes.
You can find the user environment variables window by –
- From the desktop, right-click the Computer icon.
- Choose Properties from the context menu.
- Click the Advanced system settings link.
- Click Environment Variables. In the section System Variables, find the CLASSPATH environment variable and select it. Click Edit. If the CLASSPATH environment variable does not exist, click New .
- Add all folders separated with a separator. Click OK. Close all remaining windows by clicking OK.
If you are creating CLASSPATH for the first time, you need to specify the name for the variable name in Windows 10. Use ‘.’ (dot) to denote the current directory.
2. Setting CLASSPATH from Command Line
Use -classpath argument to set classpath from command prompt/console. Use the following command to set the classpath for different requirements.
Let’s say we have a folder named dependency where JAR files and other classes are placed.
2.1. Add a Single Jar in CLASSPATH
Below syntax examples will add single jar file in classpath.
//WINDOWS $ set CLASSPATH=.;C:\dependency\framework.jar //Linux/Unix $ export CLASSPATH=.:/dependency/framework.jar
2.2. Add Multiple Jars in CLASSPATH
Below syntax examples will add more than one jar file in classpath. To do so, simply use the delimiter for your operating system (either ; or : ) as a separator between the locations specified for the CLASSPATH.
To add all JAR files present in a directory, use wildcard character ( ‘*’ ).
//WINDOWS $ set CLASSPATH=C:\dependency\framework.jar;C:\location\otherFramework.jar $ set CLASSPATH=C:\dependency\framework.jar;C:\location\*.jar //Linux/Unix $ export CLASSPATH=/dependency/framework.jar:/location/otherFramework.jar $ export CLASSPATH=/dependency/framework.jar:/location/*.jar
2.3. Add Multiple Classes in CLASSPATH
Many times, you may need to add individual classes in classpath as well. To do so, simply add the folder where classfile is present. e.g. let’s say there are five .class files are present in location folder which you want to include in classpath.
//WINDOWS $ set CLASSPATH=C:\dependency\*;C:\location //Linux/Unix $ export CLASSPATH=/dependency/*:/location
As a best practice, always organize all JAR files and application classes inside one root folder. This may be the workspace for the application.
Please note that subdirectories contained within the CLASSPATH would not be loaded. In order to load files that are contained within subdirectories, those directories and/or files must be explicitly listed in the CLASSPATH.
If your CLASSPATH environment variable was set to a value that is not correct, then you can unset CLASSPATH by specifying an empty value to it.
3. Executing Programs with ‘-classpath’ or ‘-cp’ Option
Apart from setting the classpath to the environment variable, you can pass an additional classpath to Java runtime while launching the application using –classpath option or –cp option.
Use the . (dot) to include the current path in the classpath where the .class file has been generated.
$ javac –classpath C:\dependency\framework.jar MyApp.Java $ java –classpath .;C:\dependency\framework.jar MyApp
4. Print Current CLASSPATH Value
Anytime you wish to verify all path entries in CLASSPATH variable, you can verify using the echo command.
//Windows c:/> echo %CLASSPATH% //Linux/Unix $ echo $CLASSPATH
If CLASSPATH is not set you will get a CLASSPATH: Undefined variable error (Solaris or Linux) console or simply %CLASSPATH% printed in the windows command prompt.
Adding Classes to the JAR File’s Classpath
You may need to reference classes in other JAR files from within a JAR file.
For example, in a typical situation an applet is bundled in a JAR file whose manifest references a different JAR file (or several different JAR files) that serves as utilities for the purposes of that applet.
You specify classes to include in the Class-Path header field in the manifest file of an applet or application. The Class-Path header takes the following form:
Class-Path: jar1-name jar2-name directory-name/jar3-name
By using the Class-Path header in the manifest, you can avoid having to specify a long -classpath flag when invoking Java to run your application.
Note: The Class-Path header points to classes or JAR files on the local network, not JAR files within the JAR file or classes accessible over Internet protocols. To load classes in JAR files within a JAR file into the class path, you must write custom code to load those classes. For example, if MyJar.jar contains another JAR file called MyUtils.jar, you cannot use the Class-Path header in MyJar.jar's manifest to load classes in MyUtils.jar into the class path.
An Example
We want to load classes in MyUtils.jar into the class path for use in MyJar.jar. These two JAR files are in the same directory.
We first create a text file named Manifest.txt with the following contents:
Warning: The text file must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.
We then create a JAR file named MyJar.jar by entering the following command:
jar cfm MyJar.jar Manifest.txt MyPackage/*.class
This creates the JAR file with a manifest with the following contents:
Manifest-Version: 1.0 Class-Path: MyUtils.jar Created-By: 1.7.0_06 (Oracle Corporation)
The classes in MyUtils.jar are now loaded into the class path when you run MyJar.jar.
How to Add JAR file to Classpath in Java?
JAR is an abbreviation of JAVA Archive. It is used for aggregating multiple files into a single one, and it is present in a ZIP format. It can also be used as an archiving tool but the main intention to use this file for development is that the Java applets and their components(.class files) can be easily downloaded to a client browser in just one single HTTP request, rather than establishing a new connection for just one thing. This will improve the speed with which applets can be loaded onto a web page and starts their work. It also supports compression, which reduces the file size and the download time will be improved.
Methods: JAR file can be added in a classpath in two different ways
Method 1 – Using Eclipse IDE
Step 1: Right-Click on your project name
Step 2: Click on Build Path
Step 3: Click on configure build path
Step 4: Click on libraries and click on “Add External JARs”
Step 5: Select the jar file from the folder where you have saved your jar file
Step 6: Click on Apply and Ok.
Method 2 – Using the command line
Command 1: By including JAR name in CLASSPATH environment variable
CLASSPATH environment variable is not case-sensitive. It can be either Classpath or classpath which is similar to PATH environment variable which we can use to locate Java binaries like javaw and java command.
Command 2: By including name of JAR file in -a classpath command-line option
This option is viable when we are passing –classpath option while running our java program like java –classpath $(CLASSPATH) Main. In this case, CLASSPATH shell variable contains the list of Jar file which is required by the application. One of the best advantages of using classpath command-line option is that it allows us to use every application to have its own set of JAR classpath. In other cases, it’s not available to all Java program which runs on the same host.
Command 3: By including the jar name in the Class-Path option in the manifest
When we are running an executable JAR file we always notice that the Class-Path attribute in the file inside the META-INF folder. Therefore, we can say that Class-Path is given the highest priority and it overrides the CLASSPATH environment variable as well as –classpath command-line option. Henceforth, we can deduce that its a good place to include all JAR files required by Java Application.
Command 4: By using Java 6 wildcard option to include multiple JAR
From Java 1.6+ onwards we can use a wildcard for including all jars in a directory to set classpath or else to provide Java program using classpath command-line option. We can illustrate the Java command example to add multiple JAR into classpath using Java 6 wildcard method as follows,
java.exe -classpath D:\lib\*Main
In this method, we include all JAR files inside ‘D:\lib’ directory into the classpath. We must ensure that syntax is correct. Some more important points about using Java 6 wildcard to include multiple JAR in classpath are as follows:
Whenever JAR and classfile are present in the same directory then we need to include both of them separately
Java -classpath /classes: /lib/*
In Java 6 wildcard which includes all JAR, it will not search for JARs in a subdirectory.
Wildcard is included in all JAR is not honored in the case when we are running Java program with JAR file and having Class-Path attribute in the manifest file. JAR wildcard is honored when we use –cp or –classpath option
Command 5: Adding JAR in ext directory example be it ‘C:\Program Files\Java\jdk1.6.0\jre\lib\ext’
By using the above method we can add multiple JAR in our classpath. JAR from ext directory can be loaded by extension Classloader. It has been given higher priority than application class loader which loads JAR from either CLASSPATH environment variable or else directories specified in –classpath or –cp