Using CLASSPATH and SOURCEPATH

  Return to the Java Programming Corner.


Setting The CLASSPATH

The CLASSPATH setting can be used to set the user class path, overriding the user class path in the CLASSPATH environment variable. If neither CLASSPATH or -classpath is specified, the user class path consists of the current directory. If you DO use either option, then the current directory WILL NOT be included in the class path.

Click here for a more in-depth discussion on setting the class path.

If the -sourcepath option is not specified, the user class path is searched for source files as well as class files.

Setting The SOURCEPATH

Specify the source code path to search for class or interface definitions. As with the user class path, source path entries are separated by semicolons (;) and can be directories, JAR archives, or ZIP archives.

If packages are used, the local path name within the directory or archive must reflect the package name.

Note that classes found through the classpath are subject to automatic recompilation if their sources are found.

Sourcepath is similar to classpath, the difference being the sourcepath contains .java files and the classpath contains .class files. They both represent search paths for dependencies.

For example, say one has the directory structure:

foo/src/TestFoo.java
baz/src/TestBaz.java
with class TestFoo:
package com.foo.test;
public class TestFoo {;}
and class TestBaz:
package com.baz.test;
import com.foo.test.TestFoo;
class TestBaz extends TestFoo {;}
These two classes have a dependency: TestBaz requires TestFoo to compile. To compile TestBaz, the following would NOT work:
javac -d baz/classes baz/src/TestBaz.java
because the compiler would not be able to find TestFoo So, you have two options for compiling TestBaz.

Separating Source Files and Class Files

It often makes sense to keep source files and class files in separate directories, especially on large projects. We use -d to indicate the separate class file destination. Since the source files are not in the user class path, we use -sourcepath to help the compiler find them.
C:> dir
classes\  lib\      src\
C:> dir src
farewells\
C:> dir src\farewells
Base.java      GoodBye.java
C:> dir lib
Banners.jar
C:> dir classes
C:> javac -sourcepath src -classpath classes;lib\Banners.jar \
       src\farewells\GoodBye.java -d classes
C:> dir classes
farewells\
C:> dir classes\farewells
Base.class      GoodBye.class
Note that the compiler compiled src\farewells\Base.java, even though we didn't specify it on the command line. To trace automatic compiles, use the -verbose option.