Java Reference
In-Depth Information
or
C:\>java -classpath C:\;C:\jbook;C:\javaprograms com.jdojo.intro.Welcome
Can you run your
Welcome
class example without worrying about the
CLASSPATH
setting? The answer is yes and
no. Sometimes,
CLASSPATH
setting becomes a bit tricky. If you don't set any value for
CLASSPATH
as in
SET CLASSPATH=
the JVM uses the current working directory as the one and the only entry for the
CLASSPATH
. The current working
directory is specified by a dot. Therefore, the following two
CLASSPATH
settings are the same for the JVM:
SET CLASSPATH=
and
SET CLASSPATH=.
If you set some value for the
CLASSPATH
, you have to add a dot separately to indicate that you also want to include
the current working directory in the
CLASSPATH
. Note that you lose the default
CLASSPATH
setting (which is the current
working directory) when you set it explicitly. Suppose you have set the
CLASSPATH
using the following command:
SET CLASSPATH=
Now, you want to run your Welcome class. The only thing you have to do is that you must change your working
directory to
C:\javaprograms
, so
C:\javaprograms
becomes your current working directory. Using this directory as
the default entry for
CLASSPATH
, the JVM will find your class correctly. The command prompt should look as follows:
C:\javaprograms>java com.jdojo.intro.Welcome
Finally, there are some words of caution for you when you work with the
CLASSPATH
and the package of a class to
locate the class file. The JVM uses
CLASSPATH
and fully qualified name of the class to locate the actual class file on the
machine. However, you cannot take some part from one and add it to another, even though the resulting path is the
same. Always keep in mind that it is not enough for the JVM just to locate the class file. It also verifies the bytecode in a
class file to make sure that it contains the class definition with proper package name. The following commands are not
the same. Note the use of the space in each of the commands to separate the
CLASSPATH
value and the fully qualified
name of the class.
C:\>java -cp C:\ javaprograms.com.jdojo.intro.Welcome
C:\>java -cp C:\javaprograms com.jdojo.intro.Welcome
C:\>java -cp C:\javaprograms\com jdojo.intro.Welcome
C:\>java -cp C:\javaprograms\com\jdojo intro.Welcome
C:\>java -cp C:\javaprograms\com\jdojo\intro Welcome
In the above examples, all the commands will look for the same class file
C:\javaprograms\com\jdojo\intro\
Welcome.class
. However, only the second command will run successfully, because the package declaration for the
Welcome
class is
com.jdojo.intro
.
The path of the class file is determined by the JVM on Windows as shown in Figure
2-7
. On other platforms, the
JVM uses the file-separator character specific to the platforms.