OOPortal OOPortal


Structured Programming   «Prev  Next»
Lesson 8 Closer look at HelloWorld
Objective Understand the elements of the HelloWorld program
Let's now examine the HelloWorld program in more detail. This program consists of a single class named HelloWorld that contains a single method named main(). Following is the source code for the program. Move your mouse cursor over the source code to see a more detailed description of each element.
error-file:tidyout.log
Java Helloworld

main() method

The main() method is a special method in Java, as it serves as the starting point for a Java program. All Java programs must have a class with a main() method. When you run a program with the Java interpreter, you specify the name of the class that contains your program's main() method. The interpreter then starts running the program with the instructions in the main() method of the class.
All of the Java programs you will be writing in this course will have a main() method that begins with:
public static void main(String[] args)

This portion of the main() method is referred to as the method header and is followed by a pair of curly brackets "{}" enclosing the instructions for the method. You're probably wondering what all of the strange and symbols words such as public, static, void, String[] args are for. Move your mouse cursor over the following source code to see a more detailed description of each part of the main() method header.
error-file:tidyout.log
Java helloworld
An in-depth understanding of each part of the main() method header isn't critical at this point. What is critical is that the main() method of your programs contain these parts. In more general terms, the method header of main() in HelloWorld indicates that the method can be accessed by any other class; it is associated with the class HelloWorld; it does not return a value; and it is passed as a list of text strings.

Displaying a message

When you run the HelloWorld program, the message "Hello World!" is displayed in your command prompt window. This is accomplished within the main() method by the statement:.
System.out.println("Hello World!");

It's difficult to describe in detail how this statement works without using a fair amount of object-oriented programming terminology, but essentially what is happening is that some existing instructions that come with the Java 2 SDK are being used to display the message. More specifically, a class that comes with the Java 2 SDK named System has a variable named out that refers to an object that has a method named println(). When the first statement in the main() method is executed (i.e., when the first instruction is carried out), the println() method is executed (i.e., the instructions in the println() method are carried out) to display the message "Hello World!"
In the next lesson you will learn how comments and indentation make programs easier to understand.