Java classpath and external library (with some personal notes as well)

The majority of this post is from Wikipedia.

Classpath is a parameter—set either on the command-line, or through an environment variable—that tells the Java Virtual Machine or the Java compiler where to look for user-defined classes and packages.

Contents

Overview and architecture

Similar to the classic dynamic loading behavior, when executing Java programs, the Java Virtual Machine finds and loads classes lazily (it loads the bytecode of a class only when this class is first used). The classpath tells Java where to look in the filesystem for files defining these classes.

The virtual machine searches for and loads classes in this order:

  1. bootstrap classes: the classes that are fundamental to the Java Platform (comprising the public classes of the Java Class Library, and the private classes that are necessary for this library to be functional).
  2. extension classes: packages that are in the extension directory of the JRE or JDK, jre/lib/ext/
  3. user-defined packages and libraries

By default only the packages of the JDK standard API and extension packages are accessible without needing to set where to find them. The path for all user-defined packages and libraries must be set in the command-line (or in the Manifest associated with the Jar file containing the classes).

Setting the path to execute Java programs

Supplying as application argument

Suppose we have a package called org.mypackage containing the classes:

  • HelloWorld (main class)
  • SupportClass
  • UtilClass

and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).

The file structure will look like this:

java_1

When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we use the following command:

java_2

where:

  • java is a java application launcher, a type of sdkTool(A command-line tool, such as javac, javadoc, or apt)
  • -classpath D:\myprogram sets the path to the packages used in the program (on Linux, -cp /home/user/myprogram) and
  • org.mypackage.HelloWorld is the name of the main class

Setting the path through an environment variable

The environment variable named CLASSPATH may be alternatively used to set the classpath. For the above example, we could also use on Windows:

set CLASSPATH=D:\myprogram
java org.mypackage.HelloWorld

The rule is that -classpath option, when used to start the java application, overrides the CLASSPATH environment variable. If none are specified, the current working directory is used as classpath. This means that when our working directory is D:\myprogram\ (on Linux, /home/user/myprogram/), we would not need to specify the classpath explicitly. When overriding however, it is advised to include current folder "." into the classpath in the case when loading classes from current folder is desired.

The same applies not only to java launcher but also to javac, the java compiler.

Setting the path of a Jar file

If a program uses a supporting library enclosed in a Jar file called supportLib.jar, physically in the directory D:\myprogram\lib\ and the corresponding physical file structure is:

java_3

the following command-line option is needed:

java -classpath D:\myprogram;D:\myprogram\lib\supportLib.jar org.mypackage.HelloWorld

or alternatively:

set CLASSPATH=D:\myprogram;D:\myprogram\lib\supportLib.jar
java org.mypackage.HelloWorld

Adding all JAR files in a directory

In Java 6 and higher, one can add all jar-files in a specific directory to the classpath using wildcard notation.

Windows example:

java -classpath ".;c:\mylib\*" MyApp

Linux example:

java -classpath '.:/mylib/*' MyApp

This works for both -classpath options and environment classpaths.

Setting the path in a Manifest file

Suppose that a program has been enclosed in a Jar file called helloWorld.jar, put directly in the D:\myprogram directory. We have the following file structure:

java_4

The manifest file defined in this Jar file has this definition:

Main-Class: org.mypackage.HelloWorld
Class-Path: lib/supportLib.jar

It’s important that the manifest file ends with either a new line or carriage return.

To launch the program, we can use the following command:

java -jar D:\myprogram\helloWorld.jar [app arguments]

This will automatically start the org.mypackage.HelloWorld specified in the Main-Class with the arguments and user cannot replace this class name using java -jar options. The Class-Path meantime describes the location of the supportLib.jar file relative to the location of the helloWorld.jar. Neither absolute file path (which is permitted in -classpath parameter on the command line) nor jar-internal paths are supported. This particularly means that if main class file is contained in a jar, org/mypackage/HelloWorld.class must be a valid path on the root within the jar.

Multiple classpath entries are separated with spaces:

Class-Path: lib/supportLib.jar lib/supportLib2.jar

OS specific notes

Being closely associated with the file system, the command-line Classpath syntax depends on the operating system. For example:

  • on all Unix-like operating systems (such as Linux and Mac OS X), the directory structure has a Unix syntax, with separate file paths separated by a colon (“:”).
  • on Windows, the directory structure has a Windows syntax, and each file path must be separated by a semicolon (“;”).

This does not apply when the Classpath is defined in manifest files, where each file path must be separated by a space (” “), regardless of the operating system.

Diagnose

Application programmers may want to find out/debug the current settings under which the application is running:

System.getProperty("java.class.path")

JavaDoc

External links

Personal notes:

Pay attention to the directory structure. It is wise that you put the compiled Java code (HelloWorldApp.class) in a separate folder when using java to execute the code with additional external libraries.

Here is a simple example, assuming that you only have one Java source file (HelloWorldApp.java) to compile.

Here is the directory

D:\HelloWorldJava\lib\samplelib.jar (//external library)

D:\HelloWorldJava\helloworldapp\HelloWorldApp.java (java source code)

First step is to compile the source code (Windows environment shown here)

Command prompt (Windows):

javac -classpath D:\HelloWorldJava;D:\HelloWorldJava\lib\samplelib.jar D:\HelloWorldJava\helloworldapp\HelloWorldApp.java

 Note that you need to specify the full path to the java source file (*.java).

Now you have a HelloWorldApp.class file. You should create a sub-folder and move this java class file to that sub-folder.

Command prompt (Windows):

java -classpath D:\HelloWorldJava;D:\HelloWorldJava\lib\samplelib.jar D:\HelloWorldJava helloworldapp.HelloWorldApp

If you put the compiled class file in the directory D:\HelloWorldJava, you will likely end up with “Error: Could not find or load main class HelloWorldApp

On Linux platform, make sure the compiled java class is in the folder that has the correct package name. In the example below, the folder should be named “javaapplication1”. You will see error if not.

package javaapplication1;
public class JavaApplication1 {
    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        // TODO code application logic here

        System.out.println("Hello world! Today is Wed, June 10th, 2015");
     
    }  

}

Another example on Linux (3/15/2016 by Eric)

Let’s say you have a Java program to send Twitter direct message to someone and it has the following directory structure, with one source file (main class) and one external jar library

/home/eric/MyDirectMessage/com/mydirectmessage/MyDirectMessage.java

/home/eric/MyDirectMessage/lib/twitter4j305.jar

Note that the header of the source file contains the following package information (directory info)

package com.mydirectmessage;

….

Now, let’s compile it first

$ javac -cp /home/eric/MyDirectMessage/lib/twitter4j305.jar /home/eric/MyDirectMessage/com/mydirectmessage/MyDirectMessage.java

Now, the java class file has been created in the same folder as the java source file “MyDirectMessage.java”

Next, you could execute it

$ java -cp /home/eric/MyDirectMessage:/home/eric/MyDirectMessage/lib/twitter4j305.jar com.mydirectmessage.MyDirectMessage

Or, you could navigate to the target directory /home/eric/MyDirectMessage first, then

~/MyDirectMessage$ java -cp .:./lib/twitter4j305.jar com.mydirectmessage.MyDirectMessage

That’s it.