Java Reference
In-Depth Information
as those shown in this section. However, the file name extensions for your source file and the object file that
results from it are just the same.
Executing a Java Application
To execute the bytecode program in the
.class
file with the Java interpreter in the JDK, you make the dir-
ectory containing the
.class
file current and enter the command:
java MyProgram
Note that you use just the name
MyProgram
to identify the program, not the name of the file that the com-
piler generates,
MyProgram.class
. It is a common beginner's mistake to use the latter by analogy with the
compile operation. If you put a
.class
file extension on
MyProgram
, your program won't execute, and you
get an error message:
Exception in thread "main" java.lang.NoClassDefFoundError: MyProgram/class
Although the
javac
compiler expects to find the name of a
file
that contains your source code, the
java
interpreter expects the name of a
class
(and that class must contain a
main()
method, as I explain later in
this chapter). The class name is
MyProgram
in this case. The
MyProgram.class
file contains the compiled
MyProgram
class. I explain what a class is shortly.
The
-enableassertions
option is necessary for programs that use
assertions
, and because you use as-
sertions after you have learned about them it's a good idea to get into the habit of always using this option.
You can abbreviate the
-enableassertions
option to
-ea
if you want. The previous command with asser-
tions enabled is:
java -enableassertions MyProgram
If you want to override an existing
CLASSPATH
definition, the option is the same as with the compiler. You
can also abbreviate
--classpath
to
-cp
with the compiler or the Java interpreter. Here's how the command
looks using that abbreviation:
java -ea -cp . MyProgram
To execute your program, the Java interpreter analyzes and then executes the bytecode instructions. The
JVM behaves identically in all computer environments that support Java, so you can be sure your program
is completely portable. As I already said, your program runs just as well on a Linux Java implementation as
it runs on an implementation for Microsoft Windows, Solaris, or any other operating system that supports
Java. (Beware of variations in the level of Java supported, though. Some environments lag a little, so imple-
mentations supporting the current JDK version might be available later than under Windows or Solaris.)
Executing an Applet
The Java compiler in the JDK compiles both applications and applets. However, an applet is not executed in
the same way as an application. You must embed an applet in a web page before it can be run. You can then
execute it either within a Java-enabled web browser, or by using the
appletviewer
, a bare-bones browser
provided as part of the JDK. It is a good idea to use the
appletviewer
to run applets while you are learning.