Java Reference
In-Depth Information
convention that filenames correspond to class names may seem arbitrary. However, this
convention makes it easier to maintain and organize your programs.
Compiling the Program
To compile the
Example
program, execute the compiler,
javac
, specifying the name of the
source file on the command line, as shown here:
The
javac
compiler creates a file called
Example.class
that contains the bytecode version
of the program. Remember, bytecode is not executable code. Bytecode must be executed
by a Java Virtual Machine. Thus, the output of
javac
is not code that can be directly ex-
ecuted.
To actually run the program, you must use the Java interpreter,
java
. To do so, pass the
class name
Example
as a command-line argument, as shown here:
When the program is run, the following output is displayed:
When Java source code is compiled, each individual class is put into its own output file
named after the class and using the
.class
extension. This is why it is a good idea to give
your Java source files the same name as the class they contain—the name of the source file
will match the name of the
.class
file. When you execute the Java interpreter as just shown,
you are actually specifying the name of the class that you want the interpreter to execute. It
will automatically search for a file by that name that has the
.class
extension. If it finds the
file, it will execute the code contained in the specified class.
NOTE
If, when you try to compile the program, the computer cannot find
javac
(and assuming
that you have installed the JDK correctly), you may need to specify the path to the
command-line tools. In Windows, for example, this means that you will need to add the
path to the command-line tools to the paths defined for the
PATH
environmental variable.
For example, if JDK 8 was installed under the Program Files directory, then the path to
the command-line tools will be similar to
C:\Program Files\Java\jdk1.8.0\bin
. (Of