Return to the Java Programming Corner.


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.


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:

with class TestFoo:
public class TestFoo {;}
and class TestBaz:
package com.baz.test;
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/
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
C:> dir src\farewells
C:> dir lib
C:> dir classes
C:> javac -sourcepath src -classpath classes;lib\Banners.jar \
       src\farewells\ -d classes
C:> dir classes
C:> dir classes\farewells
Base.class      GoodBye.class
Note that the compiler compiled src\farewells\, even though we didn't specify it on the command line. To trace automatic compiles, use the -verbose option.