Java Reference
In-Depth Information
This command should produce the output:
Hello World!
The java command is the Java interpreter; it runs the Java Virtual Machine. You
pass java the name of the class that you want to run. Note that you are specifying
the class name, Hello , not the name of the file, Hello.class , that contains the com-
piled class.
The previous steps have shown you how to compile and run Java programs that
don't have package declarations. If you omitted the package declaration when you
typed in Hello.java , these instructions should have worked for you (if they didn't,
check that you typed the program in correctly). In practice, however, all nontrivial
Java programs (including the examples in this topic) do have package declara-
tions. Using packages makes compiling and running Java programs a bit more
complicated. As I just noted, a Java program must be saved in a file that has a
name that matches the class name. When a class is in a package, there is a further
requirement that the class be saved in a directory that matches the name of the
package.
Go ahead and reinsert the package declaration into Hello.java :
package com.davidflanagan.examples.basics;
Now make yourself a new directory (or folder) in which you'll do all your work
with the examples from this topic. For example, on a Windows system, you might
create a folder named c:\jenut2 . On a Linux system, you might use ˜/jenut2 .
Within this directory, create a subdirectory named com . Then create a subdirectory
of com named davidflanagan . Then create an examples subdirectory of david-
flanagan . Finally, create a subdirectory in examples named basics . Now copy your
Hello.java program (with the package declaration) into this directory. On a Win-
dows system, the resulting file might be:
c:\jenut2\com\davidflanagan\examples\basics\Hello.java
After you've created the directory structure and put your Java program in it, the
next step is to tell the Java compiler and interpreter where to find it. The compiler
and interpreter simply need to know the base directory you've chosen; they will
look for the Hello.class file in subdirectories of this base directory, based on the
package name. To tell Java where to look, you have to set the CLASSPATH environ-
ment variable in the manner appropriate for your operating system. If you used
the suggested name for your base directory on a Windows system ( c:\jenut2 ), you
can use a command like the following:
C:\> set CLASSPATH=.;c:\jenut2
This tells Java to look first for classes in the current directory ( . ), followed by the
c:\jenut2 directory.
On a Unix system using the csh shell, you can use the following command:
% setenv CLASSPATH .:/home/david/jenut2
Search WWH ::




Custom Search