Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 1 ■ WRITING YOUR FIRST JAVA PROGRAM

That's a complete Java program. You can now run your program by clicking the Run button in the
toolbar or by choosing RRun from the RRun menu. Figure 1.5 shows where to find the Run button.


Figure 1-5. Where to find the Run button.


Eclipse then displays a console panel under the code area that shows the output of your program.
In this case, it says, “Hello, World!” Writing a program that outputs “Hello, World!” is an old tradition, by
the way. If you tell experienced developers that you're at the “Hello, World!” stage in learning how to
program, they'll know that you've just taken your first steps on the road to being a software developer.
Most software developers remember that day fondly.
The String[] args part is the mechanism that a Java program uses to read in options (more properly
called arguments) that you can give to your program. The word String refers to a collection of characters
that we can treat as a single object. A name is a classic example of a string. The [] indicates an array,
which is a collection of values (strings in this case). The collection (that is, the array) of strings is called
args. We add the capability to use an argument to our Hello program later in the chapter, we cover arrays
in the next chapter, and we cover strings in Chapter 3, “Data Types.”


Adding More Functionality


Now that you have a working program, let's make it do more. Specifically, let's make it read in your
name and say hello to you rather than to the whole world.
Look at the declaration for the main method. The args array holds all the values that were provided
to the Java runtime engine when someone started your program. Often, these are configuration settings
of various types. One common practice is to pass in the path to a file that contains more information
(such as difficulty settings for a game or the most recently opened files for a word processor)—that is, the
path to a configuration file. We read files later in the book. For now, we get the arguments from Eclipse.
First, though, we need to write the code to read the arguments and put the first argument into our
message. Listing 1-3 shows how to do this.

Free download pdf