JDK 1.1 for Solaris Developer's Guide

Java Programs

Java programs are written in two forms: applications and applets.

Java applications are run by invoking the Java interpreter from the command line and specifying the file containing the compiled application.

Java applets are invoked from a browser. The HTML code interpreted by the browser names a file containing the compiled applet. This causes the browser to invoke the Java interpreter which loads and runs the applet.

Sample Application

Example 3-1 is the source of an application that displays "Hello World" on stdout. The method accepts arguments in the invocation, but does nothing with them.

Example 3-1 Sample Java Application Code

// HelloWorld Application
class HelloWorldApp{
    public static void main (String args[]) {
        System.out.println ("Hello World");

Note that, as in C, the method or function to be initially executed is identified as main. The keyword public lets the method be run by anyone; static makes main refer to the class HelloWorldApp and no other instance of the class; void says that main returns nothing; and args[] declares an array of type String

To compile the application, enter

$ javac HelloWorldApp.java

It is run by

$ java HelloWorldApp arg1 arg2 ...

Sample Applet

Example 3-2 is the source of the applet that is equivalent to the application in Example 3-1.

Example 3-2 Sample Java Applet

// HelloWorld Applet
import java.awt.Graphics;
import java.applet.Applet;
public class HelloWorld extends Applet {
    public void paint (Graphics g) {
        g.drawstring ("Hello World", 25, 25);

In an applet, all referenced classes must be explicitly imported. The keywords public and void mean the same as in the application; extend says that the class HelloWorld inherits from the class Applet.

To compile the applet, enter

$ javac HelloWorld.java

The applet is invoked in a browser by HTML code. A minimum HTML page to run the applet is:

<applet code="HelloWorld.class" width=100 height=50>