6.4 Searching for Classes on the Class Path
A program typically uses other precompiled classes and libraries, in addition to the ones provided by the Java standard libraries. In order for the JDK tools to find these files efficiently, the CLASSPATH environment variable or the -classpath option can be used, both of which are explained below.
In particular, the CLASSPATH environment variable can be used to specify the class search path (usually abbreviated to just class path), which is the pathnames or locations in the file system where JDK tools should look when searching for third-party and user-defined classes. Alternatively, the -classpath option (short form -cp) of the JDK tool commands can be used for the same purpose. The CLASSPATH environment variable is not recommended for this purpose, as its class path value affects all Java applications on the host platform, and any application can modify it. However, the -classpath option can be used to set the class path for each application individually. This way, an application cannot modify the class path for other applications. The class path specified in the -classpath option supersedes the path or paths set by the CLASSPATH environment variable while the JDK tool command is running. We will not discuss the CLASSPATH environment variable here, and will assume it to be undefined.
Basically, the JDK tools first look in the directories where the Java standard libraries are installed. If the class is not found in the standard libraries, the tool searches in the class path. When no class path is defined, the default value of the class path is assumed to be the current directory. If the -classpath option is used and the current directory should be searched by the JDK tool, the current directory must be specified as an entry in the class path, just like any other directory that should be searched. This is most conveniently done by including ‘.’ as one of the entries in the class path.
We will use the file hierarchies shown in Figure 6.4 to illustrate some of the intricacies involved when searching for classes. The current directory has the absolute pathname /top/src, where the source files are stored. The package pkg will be created under the directory with the absolute pathname /top/bin. The source code in the two source files A.java and B.java is also shown in Figure 6.4.
Figure 6.4 Searching for Classes
The file hierarchy before any files are compiled is shown in Figure 6.4a. Since the class B does not use any other classes, we compile it first with the following command, resulting in the file hierarchy shown in Figure 6.4b:
>javac -d ../bin B.java
Next, we try to compile the file A.java, and we get the following results:
>
javac -d ../bin A.java
A.java:3: cannot find symbol
symbol : class B
location: class pkg.A
public class A { B b; }
^
1 error