Java Reference
In-Depth Information
Using CLASSPATH Effectively
Problem
You need to keep your class files in a common directory, or you're wrestling with
CLASSPATH.
Solution
Set CLASSPATH to the list of directories and/or JAR files that contain the classes you want.
Discussion
CLASSPATH is one of the more “interesting” aspects of using Java. You can store your class
files in any of a number of directories, JAR files, or ZIP files. Just like the PATH your sys-
tem uses for finding programs, the CLASSPATH is used by the Java runtime to find classes.
Even when you type something as simple as
java HelloWorld
, the Java interpreter looks in
each of the places named in your CLASSPATH until it finds a match. Let's work through an
example.
The CLASSPATH can be set as an environment variable on systems that support this (Mi-
crosoft Windows and Unix, including Mac OS X). You set it the same way you set other en-
vironment variables, such as your PATH environment variable.
Alternatively, you can specify the CLASSPATH for a given command on the command line:
C:\> java -classpath c:\ian\classes MyProg
Suppose your CLASSPATH were set to
C:\classes;.
on Windows or
~/classes:.
on Unix (on
the Mac, you can set the CLASSPATH with JBindery). Suppose you had just compiled a file
named
HelloWorld.java
into
HelloWorld.class
and tried to run it. On Unix, if you run one of
the kernel tracing tools (
trace
,
strace
,
truss
,
ktrace
), you would probably see the
Java
program
open
(or
stat
, or
access
) the following files:
▪ Some file(s) in the JDK directory
▪ Then ~
/classes/HelloWorld.class
, which it probably wouldn't find
▪ Finally,
./HelloWorld.class
, which it would find, open, and read into memory