Java Reference
In-Depth Information
method. Furthermore, these sorts of statement blocks can be nested arbitrarily
deep within each other.
The first three lines and the last two lines of Example 1-1 are part of the basic
framework of a Java application. It is the fourth line of the example that is of pri-
mary interest to us. This is the line that prints the words “Hello World!” The Sys-
tem.out.println() method sends a line of output to “standard output,” which is
usually the screen. This method is used throughout this chapter and in many other
chapters in this topic. It isn't until Chapter 3, Input/Output , however, that you'll
really understand what it is doing. If you are curious before then, look up the
java.lang.System and java.io.PrintStream classes in Java in a Nutshell (or some
other Java reference manual).
One final point to note about this program is the use of comments. Example 1-1
uses C++-style comments that begin with // and continue until the end of the line.
Thus, anything between the // characters and the end of a line is ignored by the
Java compiler. You'll find that the examples in this topic are thoroughly com-
mented. The code and the comments are worth studying because the comments
often draw your attention to points that are not mentioned in the main text of the
topic.
Running “Hello World”
The first step in running our program is to type it in. * Using a text editor, type in
the Hello program as shown in Example 1-1. For now, however, omit the package
declaration on the first line. Save the program in a file named Hello.java .
The second step is to compile the program. If you are using the Java Software
Development Kit (SDK) from Sun, you compile code with the javac command. cd
to the directory that contains your Hello.java file, and type this command (assum-
ing that javac is in your path):
% javac Hello.java
If the Java SDK has been properly installed, javac runs for a short while and then
produces a file named Hello.class . This file contains the compiled version of the
program. As I said earlier, everything you write in Java is a class, as the .class
extension on this file indicates. One important rule about compiling Java programs
is that the name of the file minus the .java extension must match the name of the
class defined in the file. Thus, if you typed in Example 1-1 and saved it in a file
named HelloWorld.java , you would not be able to compile it.
To run the program (again using the Java SDK) type:
% java Hello
* Although this example is included in the online example archive, I'm suggesting that you type it in so
that you start imprinting basic Java idioms in your brain. I'm also going to have you modify the exam-
ple, in order to explain certain aspects of running the program.
† If you are using some other Java programming environment, read and follow the vendor's instructions
for compiling and running programs.
Search WWH ::




Custom Search