Using Classpath
The classpath is an environment variable that's used by the Java compiler and the Java virtual machine for class definitions.
You can use it in your work and in conjunction with examples presented in the text. Here is an example
Suppose you are trying the application, BagDemonstration.java, from the text that works with the IntArrayBag class. That imports the packages IntArrayBag and EasyReader as follows
// FILE: BagDemonstration.java
// This small demonstration program shows how to use the IntArrayBag class
// from the edu.colorado.collections package.
import edu.colorado.collections.IntArrayBag;
import edu.colorado.io.EasyReader;
public class BagDemonstration
{
You know the compiler will be looking for the classes IntArrayBag and EasyReader in a directory that includes edu/colorado/collections and edu/colorado/io as subdirectories. However, if we can set classpath to the name of a directory so the compiler will expect to find edu/collections as all its subdirectories there. These happen to be in /users/ernie/321 so you can use them by either of the two methods
- You only need to do this once.
Set the environment variable CLASSPATH.
- cd $HOME
- edit the file named .profile (note the leading period in the name)
- Add the following to the end of the file
#set & export CLASSPATH
CLASSPATH=/users/ernie/321
export CLASSPATH
- save the changes made in the editing session and exit the editor
- enter . .profile at a shell prompt. That is type a period, a space, another period,the word profile, and press Enter.
- You have set the environment variable named CLASSPATH, and you don't need to do it again. You can change it by editing .profile and executing . .profile as above.
- Now to compile the program enter javac BagDemonstration.java, an to execute it use java BagDemonstration
- You need to do this every time you compile or execute a java program. Set the value of classpath as an option on the command line.
- Classpath can be used as an option to the compiler and Java virtual machine. In this case when compiling the program you need to enter
javac -classpath /users/ernie/321 BagDemonstration.java
to compile the program and you need to enter
java -classpath /users/ernie/321 BagDemonstration
to execute the program.

for compiling and executing programs written in Java

This work is licensed under a Creative Commons License.
Ernest Ackermann
Department of Computer Science, Mary
Washington College
CPSC 104 | CPSC
220 | CPSC 321
This page was last modified on
.