How do I update my classpath to include a jar file?
Author: Deron Eriksson
Description: This Java tutorial shows how to update your classpath to compile and execute Java code.
Tutorial created using: Windows XP || JDK 1.6.0_10

Page:    1 2 >

Suppose we have a JavaSW file that references a class in a Java library, such as the StringUtils class in the commons-lang library. We can reference StringUtils by its simple class name in our class by importing it, as shown in the file below.

import org.apache.commons.lang.StringUtils;

class Howdy {
	public static void main(String [] args) {
		System.out.println("Hello there");
		String x = "kat";
		String y = StringUtils.replace(x, "k", "c");

The file is located in the C:\stuff directory.


The commons-lang-2.3.jar file is located in the C:\stuff\lib directory.


Now, we'd like to compile and execute the Howdy class. To do this, we need to set the classpathW so the javac compiler and the javaSW interpreter know where the commons-lang jarW file is located.

There are two main techniques that you can use to do this. The first technique is to use the "-cp" or "-classpath" switch on "javac" and "java" to set the classpath. When setting the classpath, on Windows you can separate the different locations with semicolons, and on unix you can separate the different locations with colons. A period signifies the current directory.

At the command prompt in the C:\stuff directory, I can type the following to compile the file. If I didn't include commons-lang in the classpath, I'd get a compilation error since the java compiler wouldn't know what StringUtils is, since it wouldn't know where to find it.

javac -cp /stuff/lib/commons-lang-2.3.jar;.

This generates the Howdy.class file. In order to execute this class, we need to supply the classpath referencing commons-lang-2.3.jar to the java interpreter so that it knows what to do when the StringUtils.replace() method is called.

java -cp /stuff/lib/commons-lang-2.3.jar;. Howdy

Using technique #1, we can see the compilation and execution below:

Technique #1 for updating classpath

(Continued on page 2)

Page:    1 2 >