A Closer Look at HelloWorld
Now that you've compiled and run your first program, you may be wondering how it works and how similar it is to other applications or applets. This section will first take a closer look at the HelloWorldApp application and then the HelloWorld applet. Be aware that the following chapters, Object-Oriented Programming Concepts (page 45) and Language Basics (page 65), will go into much more detail than is presented in this section.
Explanation of an Application
Let's dissect the HelloWorldApp application. First, we will look at the comments in the code before we touch on programming concepts, such as classes and methods.
/** * The HelloWorldApp class implements an application that * displays "Hello World!" to the standard output. */ public class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); //Display the string. } }
Comments
The Java programming language supports three kinds of comments:
/* text */
The compiler ignores everything from the opening /* to the closing */.
/** documentation */
This style indicates a documentation comment (doc comment, for short). As with the first kind of comment, the compiler ignores all the text within the comment. The SDK javadoc tool uses doc comments to automatically generate documentation. For more information on javadoc, see the tool documentation.13
// text
The compiler ignores everything from the // to the end of the line.
The boldface parts in the following code are comments:
/** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); //Display the string. } }
Defining a Class
The first boldface line in this listing begins a class definition block:
/** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); //Display the string. } }
A class is the basic building block of an object-oriented language, such as the Java programming language. A class is a blueprint that describes the state and the behavior associated with instances of that class. When you instantiate a class, you create an object that has the same states and behaviors as other instances of the same class. The state associated with a class or an object is stored in member variables. The behavior associated with a class or an object is implemented with methods, which are similar to the functions or procedures in procedural languages, such as C.
A recipesay, Julia Child's recipe for ratatouilleis like a class. It's a blueprint for making a specific instance of the recipe. Her rendition of ratatouille is one instance of the recipe, and Mary Campione's is (quite) another.
A more traditional example from the world of programming is a class that represents a rectangle. The class defines variables for the origin, width, and height of the rectangle. The class might also define a method that calculates the area of the rectangle. An instance of the rectangle class, a rectangle object, contains the information for a specific rectangle, such as the dimensions of the floor of your office or the dimensions of this page.
This is simplest form of a class definition:
class Ratatouille { . . . //class definition block }
The keyword class begins the class definition for a class named Ratatouille. The variables and the methods of the class are enclosed by the braces that begin and end the class definition block. The HelloWorldApp class has no variables and has a single method, named main.
The main Method
The entry point of every Java application is its main method. When you run an application with the Java interpreter, you specify the name of the class that you want to run. The interpreter invokes the main method defined in that class. The main method controls the flow of the program, allocates whatever resources are needed, and runs any other methods that provide the functionality for the application.
The boldface lines in the following listing begin and end the definition of the main method.
/** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); //Display the string. } }
Every application must contain a main method declared like this:
public static void main(String[] args)
The main method declaration starts with three modifiers:
public: Allows any class to call the main method
static: Means that the main method is associated with the HelloWorldApp class as a whole instead of operating on an instance of the class
void: Indicates that the main method does not return a value
When you invoke the interpreter, you give it the name of the class that you want to run. This class is the application's controlling class and must contain a main method. When invoked, the interpreter starts by calling the class's main method, which then calls all the other methods required to run the application. If you try to invoke the interpreter on a class that does not have a main method, the interpreter can't run your program. Instead, the interpreter displays an error message similar to this:
In class NoMain: void main(String argv[]) is not defined
As you can see from the declaration of the main method, it accepts a single argument: an array of elements of type String, like this:
public static void main(String[] args)
This array is the mechanism through which the Java Virtual Machine passes information to your application. Each String in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. The HelloWorldApp application ignores its command-line arguments, so there isn't much more to discuss here.
Using Classes and Objects
The HelloWorldApp application is about the simplest program you can write that actually does something. Because it is such a simple program, it doesn't need to define any classes except HelloWorldApp.
However, the application does use another class, System, that is part of the Java API. The System class provides system-independent access to system-dependent functionality. One feature provided by the System class is the standard output streama place to send text that usually refers to the terminal window in which you invoked the Java interpreter.
Impurity Alert!
Using the standard output stream isn't recommended in 100% Pure Java programs. However, it's fine to use during the development cycle. We use it in many of our example programs because otherwise, our code would be longer and more difficult to read.
The following boldface line shows HelloWorldApp's use of the standard output stream to display the string Hello World:
/** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); //Display the string. } }
This one line of code uses both a class variable and an instance method.
Let's take a look at the first segment of the statement:
System.out.println("Hello World!");
The construct System.out is the full name of the out variable in the System class. The application never instantiates the System class but instead refers to out directly through the class. The reason is that out is a class variablea variable associated with a class rather than with an object. The Java Virtual Machine allocates a class variable once per class, no matter how many instances of that class exist. The Java programming language also has the notion of class methods used to implement class-specific behaviors.
Although System's out variable is a class variable, it refers to an instance of the PrintStream class (another Java API-provided class that implements an easy-to-use output stream). When it is loaded into the application, the System class instantiates PrintStream and assigns the new PrintStream object to the out class variable. Now that you have an instance of a class, you can call one of its instance methods:
System.out.println("Hello World!");
An instance method implements behavior specific to a particular objectan instance of a class.
The Java programming language also has instance variables. An instance variable is a member variable associated with an object rather than with a class. Each time you instantiate a class, the new object gets its own copy of all the instance variables defined in its class.
If this discussion of member variables, methods, instances, and classes has left you with nothing but questions, the chapters Object-Oriented Programming Concepts (page 45) and Language Basics (page 65) can help.
The Anatomy of an Applet
By following the steps outlined in Creating Your First Applet (page 13 for Win32 and page 20 for UNIX/Linux), you created an appleta program to be included in HTML pages and executed in Java-enabled browsers. Remember that an applet is a program that adheres to some conventions that allow it to run within a Java-enabled browser.
Here again is the code for the HelloWorld applet:
import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } }
Importing Classes and Packages
HelloWorld.java begins with two import statements that import the Applet and Graphics classes:
import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } }
By importing classes or packages, a class can easily refer to classes in other packages. In the Java programming language, packages are used to group classes, similar to the way libraries group C functions. If you removed the first two lines, you could still compile and run the program, but you could do so only if you changed the rest of the code like this (as shown in boldface):
public class HelloWorld extends java.applet.Applet { public void paint(java.awt.Graphics g) { g.drawString("Hello world!", 50, 25); }\ }
As you can see, importing the Applet and Graphics classes lets the program refer to them later without any prefixes. The java.applet. and java.awt. prefixes tell the compiler which packages it should search for the Applet and Graphics classes. The java.applet package contains classes that are essential to applets. The java.awt package contains classes used by all programs with a GUI.
You might have noticed that the HelloWorldApp application uses the System class without any prefix, yet it does not import the System class. The reason is that the System class is part of the java.lang package, and everything in the java.lang package is automatically imported into every program written in the Java programming language.
You can import not only individual classes but also entire packages. Here's an example:
import java.applet.*; import java.awt.*; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } }
Every class is in a package. If the source code for a class doesn't have a package statement at the top declaring in which package the class is, the class is in the default package. Almost all the example classes in this tutorial are in the default package.
Within a package, all classes can refer to one another without prefixes. For example, the java.awt package's Component class refers to the same package's Graphics class without any prefixes and without importing the Graphics class.
Defining an Applet Subclass
The first boldface line of the following listing begins a block that defines the HelloWorld class:
import java.applet.Applet;\ import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) {\ g.drawString("Hello world!", 50, 25); } }
The extends keyword indicates that HelloWorld is a subclass of the Applet class. In fact, every applet must define a subclass of the Applet class. Applets inherit a great deal of functionality from the Applet class, ranging from the ability to communicate with the browser to the ability to present a graphical user interface (GUI). You will learn more about subclasses in the chapter Object-Oriented Programming Concepts (page 45).
Implementing Applet Methods
The boldface lines of the following listing implement the paint method:
import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } }
The HelloWorld applet implements just one method: paint. Every applet should implement at least one of the following methods: init, start, or paint. Unlike Java applications, applets do not need to implement a main method.
Applets are designed to be included in HTML pages. Using the <APPLET> HTML tag, you specify (at a minimum) the location of the Applet subclass and the dimensions of the applet's on-screen display area. The applet's coordinate system starts at (0,0), which is at the upper-left corner of the applet's display area. In the previous code snippet, the string Hello world! is drawn starting at location (50,25), which is at the bottom of the applet's display area.
Running an Applet
When it encounters an <APPLET> tag, a Java-enabled browser reserves on-screen space for the applet, loads the Applet subclass onto the computer on which it is executing, and creates an instance of the Applet subclass.14
The boldface lines of the following listing comprise the <APPLET> tag that includes the Hello-World applet in an HTML page:
<HTML> <HEAD> <TITLE> A Simple Program </TITLE> </HEAD> <BODY> Here is the output of my program: <APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25> </APPLET> </BODY> </HTML>
The <APPLET> tag specifies that the browser should load the class whose compiled code (bytecodes) is in the file named HelloWorld.class. The browser looks for this file in the same directory as the HTML document that contains the tag.
When it finds the class file, the browser loads it over the network, if necessary, onto the computer on which the browser is running. The browser then creates an instance of the class. If you include an applet twice in one HTML page, the browser loads the class file once and creates two instances of the class.
The WIDTH and HEIGHT attributes are like the attributes of the same name in an <IMG> tag: They specify the size in pixels of the applet's display area. Most browsers do not let the applet resize itself to be larger or smaller than this display area. For example, all the drawing that the HelloWorld applet does in its paint method occurs within the 150 x 25 pixel display area reserved by the <APPLET> tag.