Java Reference
In-Depth Information
Note that you should avoid storing your source files within the directory structure that was created for
the SDK, as this can cause problems. Set up a separate directory of your own to hold the sourcecode for
a program and keep the code for each program in its own directory.
Assuming your program contains no errors, the compiler generates a byte code program that is the
equivalent of your source code. The compiler stores the byte code program in a file with the same name as
the source file, but with the extension .class . Java executable modules are always stored in a file with the
extension .class . By default, the .class file will be stored in the same directory as the source file.
The command line options we have introduced here are by no means all the options you have available
for the compiler. You will be able to compile all of the examples in the topic just knowing about the
options we have discussed. There is a comprehensive description of all the options within the
documentation for the SDK. You can also specify the -help command line option to get a summary of
the standard options you can use.
If you are using some other product to develop your Java programs, you will probably be using a much
more user-friendly, graphical interface for compiling your programs that won't involve entering
commands such as that shown above. The file name extensions for your source file and the object file
that results from it will be just the same however.
Executing a Java Application
To execute the byte code program in the .class file with the Java interpreter in the SDK, you make
the directory containing the .class file current, and enter the command:
java -enableassertions MyProgram
Note that we use MyProgram to identify the program, NOT 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 will get an error message:
Exception in thread "main" java.lang.NoClassDefFoundError: MyProgram/class
While the compiler expects to find the name of your source file, the java interpreter expects the name of
a class, which is MyProgram in this case, not the name of a file. The MyProgram.class file contains
the MyProgram class. We will explain what a class is shortly.
The -enableassertions option is necessary for SDK1.4 programs that use assertions, but since we
will be using assertions once we 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 wish.
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 Java interpreter, but strangely, this abbreviation
does not apply to the compiler. Here's how the command would look:
java -ea -cp . MyProgram
Search WWH ::




Custom Search