To run the program you type the command
java HelloWorld
This executes the main method of HelloWorld. When you run the program, it displays
Hello, world
Now you have a small program that does something, but what does it mean?
The program declares a class called HelloWorld with a single member: a method called main. Class
members appear between curly braces { and } following the class name.
The main method is a special method: the main method of a class, if declared exactly as shown, is executed
when you run the class as an application. When run, a main method can create objects, evaluate expressions,
invoke other methods, and do anything else needed to define an application's behavior.
The main method is declared publicso that anyone can invoke it (in this case the Java virtual machine)and
static, meaning that the method belongs to the class and is not associated with a particular instance of the
class.
Preceding the method name is the return type of the method. The main method is declared void because it
doesn't return a value and so has no return type.
Following the method name is the parameter list for the methoda sequence of zero or more pairs of types and
names, separated by commas and enclosed in parentheses ( and ). The main method's only parameter is an
array of String objects, referred to by the name args. Arrays of objects are denoted by the square brackets
[] that follow the type name. In this case args will contain the program's arguments from the command line
with which it was invoked. Arrays and strings are covered later in this chapter. The meaning of args for the
main method is described in Chapter 2 on page 73.
The name of a method together with its parameter list constitute the signature of the method. The signature
and any modifiers (such as public and static), the return type, and exception throws list (covered later in
this chapter) form the method header. A method declaration consists of the method header followed by the
method bodya block of statements appearing between curly braces.
In this example, the body of main contains a single statement that invokes the println methodthe
semicolon ends the statement. A method is invoked by supplying an object reference (in this case
System.outthe out field of the System class) and a method name (println) separated by a dot (.).
HelloWorld uses the out object's println method to print a newline-terminated string on the standard
output stream. The string printed is the string literal "Hello,world" , which is passed as an argument to
println. A string literal is a sequence of characters contained within double-quotes " and ".
Exercise 1.1: Enter, compile, and run HelloWorld on your system.
Exercise 1.2: Try changing parts of HelloWorld and see what errors you might get.