Classpath, Code Libraries, and Jar Files

Contact Us or call 1-877-932-8228
Classpath, Code Libraries, and Jar Files

Classpath, Code Libraries, and Jar Files

By now, you may have noticed that every demo and solution folder contains its own copy of util and KeyboardReader. Not only is it inefficient, but it means that we would have to locate and update each copy if we wanted to change KeyboardReader.

A better solution would be to have one master copy somewhere that all of our exercises could access.


Java has a CLASSPATH concept that enables you to specify multiple locations for .class files, at both compile-time and runtime.

By default, Java uses rt.jar in the current Java installation's jre/lib directory, and assumes that the classpath is the current directory (the working directory in an IDE).

If you create a classpath, the default one disappears, so any classpath that you create must include the current directory using a period (.) character.

To use an external library, you would need to create a classpath in one of two ways:

  1. you can create a system or user environment variable, with multiple directories and/or .jar files, separated by the same delimiter used by your PATH (a semicolon in Windows).
  2. You could use the -classpath option in java and javac (-cp is a shorthand version of that).

Here is an example of a pair of commands to compile and run using an external library stored in a jar file. Note that we need the jar file at both compile-time and runtime. The -cp option in both commands replaces the system classpath with one specifically for that command.

javac -cp c:\Java102\ClassFiles\utilities.jar;. *.java 
java -cp c:\Java102\ClassFiles\utilities.jar;. Payroll

Many Integrated Development Environments (IDEs) have a means to specify project properties; usually an item like "Build Path" will have options to specify external jar files (as well as choose from various libraries supplied with the environment).

Creating a jar File (a Library)

If you wish to create your own library of useful classes, you can bundle one or more classes and/or directories of classes in a jar file. Yyou can also add other resources such as image files.

A jar file contains files in a zipped directory structure. The root level of the file structure should match the root of the package structure; for example, to put KeyboardReader in a jar file, we would want to start at the directory where util is visible, and jar that

The following command will create a jar file called utilities.jar for all files in the util package (just KeyboardReader, in this case).

jar -cvf utilities.jar util\*.class
  • The options are create, verbose, and use a list of files supplied at the end of the command.