Writing Your First Java Program

Writing Your First Java Program

In the grand old tradition of C programming books, I'll begin by showing you how to display "Hello, World!" from a Java program. However, before I proceed, I should point out the difference between three types of Java programs:

  • Standalone Java application-This is a Java program that can be executed by a Java interpreter. A Java standalone application is just like the standalone C or C++ programs that you might know. The application has a main method and the java interpreter can run the application. General-purpose Java applications take the form of standalone applications.

  • Java applet-This is a Java class that can be loaded and executed by the appletviewer program or by a Java-capable Web browser. You have to first embed the applet inside an HTML document using the <applet> tag and then load that HTML document to activate the applet. As a Webmaster, you'll mostly write Java applets.

  • Java servlet-This is a Java class loaded and executed by a Web server (or a server that helps the Web server such as the Apache Tomcat server). To develop servlets, you need the Java 2 Enterprise Edition.

Whether you write a standalone application or an applet or a servlet, the basic steps are similar except for the last step when you execute the program. You use the java interpreter to run standalone programs and appletviewer to test applets. For servlets, you simply place them in a specific directory and insert HTML code to refer to the servlets. These development steps are as follows:

  1. Use a text editor to create the Java source file. A Java application is a class (a type of object-collection of data and methods). The source file's name must be the class name with a .java extension.

  2. Process the source file with javac (the Java compiler) to generate the class file with a .class extension.

  3. If it's a standalone application, run the class with the java interpreter with the following command:

    java classname
  4. If the program is an applet, create an HTML document and embed the applet using the <applet> tag (see 'The <applet> Tag' section for the syntax). Then, load that HTML document using appletviewer or a Java-capable Web browser. When the browser loads the HTML document, it also activates all embedded Java applets.

Writing a Standalone 'Hello, World!' Program

The classic C-style "Hello, World!" application is easy to write in Java. That's because many of Java's syntactical details are similar to that of C and C++. The following code implements a simple "Hello, World!" program in Java (you have seen this in an earlier section, but it's so short that I'll just show you again):

public class HelloWorld
    public static void main(String[] args)
        System.out.println("Hello, World!");

Even this simple Java program illustrates some key features of Java:

  • Every Java program is a public class definition.

  • A standalone application contains a main method that must be declared public static void. The interpreter starts execution at the main method.

Save this program in a file named HelloWorld.java. Then, compile it with the following command:

javac HelloWorld.java
Insider Insight 

If you get an error saying 'command not found,' then you need to add the Java 2 SDK binary directory to the PATH environment variable. If you installed the Java2 SDK in the /usr/java/j2sdk1.4.1_01, then type the following command to add the binary directory to PATH:


The javac compiler creates a class file named HelloWorld.class. To run the application, use the Java interpreter and specify the class name as a parameter, like this:

java HelloWorld

The program prints the following output:

Hello, World!

Writing a Simple Java Applet

The other model of a Java program is the applet that runs inside the appletviewer program or a Java-capable Web browser. Specifically, a Java applet is a class in the Java Abstract Windowing Toolkit (AWT). In an applet, you do not have to provide a main method. Instead, you provide a paint method where you place code to draw in an area of a window. You can use the applet model to implement GUIs and other graphical programs.

For a "Hello, World!" applet, I'll do the following:

  • Instead of displaying the message in a default font, pick a specific font to display the message.

  • Use the information about the font sizes to center the message within the area where the applet is required to display its output.

  • Draw the text in red instead of the default black color.

Listing 26-1 shows the Java code that implements the "Hello, World!" applet.

Listing 26-1: The HelloWorld Java Applet
Start example
// File: HelloWorld.java
// Displays "Hello, World!" in Helvetica font and in red color.

import java.applet.*;
import java.awt.*;

// H e l l o W o r l d
// Applet class to display "Hello, World!"

public class HelloWorld extends java.applet.Applet
    String hellomsg = "Hello, World!";

// p a i n t
// Method that paints the output

    public void paint(java.awt.Graphics gc)
// Draw a rectangle around the applet's bounding box
// so we can see the box.
        gc.drawRect(0, 0, getSize().width-1, 

// Create the font to be used for the message.
        Font helv = new Font("Helvetica", Font.BOLD, 24);

// Select the font into the Graphics object.

// Get the font metrics (details of the font size).
        FontMetrics fm = gc.getFontMetrics();
        int mwidth = fm.stringWidth(hellomsg);
        int ascent = fm.getAscent();
        int descent = fm.getDescent();

// Compute starting (x.y) position to center string
// The size() method returns size of the applet's
// bounding box.
        int xstart = getSize().width/2 - mwidth/2;
        int ystart = getSize().height/2 + ascent/2 - descent/2;

// Set the color to red.

// Now draw the string.
        gc.drawString(hellomsg, xstart, ystart);
End example

By browsing through this code, you can learn a lot about how to display graphics output in Java. Here are the key points to note:

  • The import statement lists external classes that this program uses. The name that follows the import statement can be the name of a class or can be a name with a wildcard (*), which tells the Java compiler to import all the classes in a package. This example uses the Applet class as well as a number of graphics classes that are in the java.awt package.

  • The HelloWorld applet is defined as an extension of the Applet class. That's what the statement public class HelloWorld extends java.applet.Applet means.

  • An applet's paint method contains the code that draws the output. The paint method receives a Graphics object as argument. You have to call methods of the Graphics object to display output.

  • The getSize method returns the size of the applet's drawing area.

  • To use a font, you have to first create a Font object and then call the setFont method of the Graphics object.

  • To draw text in a specific color, invoke the setColor method of the Graphics object with an appropriate Color object as argument.

  • If you know C++, you'll notice that Java's method invocation is similar to the way you call the member function of a C++ object. Indeed, there are many similarities between C++ and Java.

Save the listing in a file named HelloWorld.java. Then, compile it with the command:

javac HelloWorld.java

This step creates the applet class file: HelloWorld.class. To test the applet, you have to create an HTML document and embed the applet in that document, as shown in the following example:

<title>Hello, World! from Java</title>


<h3>"Hello, World!" from Java</h3>

A Java applet is given an area where it displays
its output. In this example, the applet draws a
border around its assigned area and then displays
the "Hello, World!" message centered in that box.

<applet code=HelloWorld width=200 height=60>
If you see this message, then you do not have a
Java-capable browser.

Here is the applet!

As this HTML source shows, you have to use the <applet> tag to insert an applet in an HTML document. In the 'Using the <applet> Tag' section, you'll learn the detailed syntax of the <applet> tag.

You can use two tools to test the applet. The first one is appletviewer, which comes with JDK. To view the HelloWorld applet, you have to run the appletviewer program and provide the name of the HTML document that includes the applet. Suppose that the HTML document is in the file named hello.html. Then, you'd run appletviewer with the following command:

appletviewer hello.html

Figure 26-1 shows how the appletviewer displays the applet.

Figure 26-1: Running the 'Hello, World!' Java Applet in appletviewer.

Notice that appletviewer displays only the applet; the rest of the text in the HTML document is ignored. However, the appearance is quite different in a Java-capable Web browser.

To view the applet in a Web browser, start the Mozilla Web browser and select File>Open File from the menus. From the Open File dialog, go to the directory where you have the hello.html file and the HelloWorld.class file (for the applet). Then, select the hello.html file, and click Open. Mozilla then renders the HTML document containing the HelloWorld applet.

Unlike the appletviewer, Mozilla should display the entire HTML document and the Java applet appears embedded in the document just like an image. The applet draws inside the rectangle assigned to it through the width and height attributes of the <applet> tag.