System Interface 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.

An Application

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


Example 2-1 A Java Application

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

Note that, like 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.

The application is compiled by

$ javac HelloWorldApp.java

It is run by

$ java HelloWorldApp arg1 arg2 ...

An Applet

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


Example 2-2 A 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; extends says that the class HelloWorld inherits from the class Applet.

The applet is compiled by

$ javac HelloWorld.java

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


<title>Test</title>
<hr>
<applet code="HelloWorld.class" width=100 height=50>
</applet>
<hr>