Using Java at Bowdoin


Java is a "simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language" (taken from The Java Language: A White Paper, Sun Microsystems, Inc). While you may not agree with, or even understand, all of these adjectives, we have Java implemented on both the DEC Alphas and the Macs at Bowdoin. This document introduces you to the use of Java on the Alphas. The Macintosh implementation is available through the CodeWarrior system, and can be best accessed by reading CodeWarrior documentation.

Detailed Java documentation is on line if you are logged into Arctos or Polar. Many extensive Web pages are also available on Java. A good book on Java is David Flanagan's Java in a Nutshell, published by O'Reilly. All the example Java programs in that book have been downloaded and are available for copying and running here.


Setting Up Your Account

Java is available on Arctos and Polar. To set up your account for running Java, add the following three lines at the end of your .cshrc file
     
setenv LD_LIBRARY_PATH "/usr/local/java.pkg/lib"
setenv CLASSPATH ".:/usr/local/java.pkg/classes"
set    path = ( $path /usr/local/java.pkg/bin )
Remember to give the command
source .cshrc
if you want the changes to take effect while currently logged in.


Running Java Programs

A Java program is written as a public class, which may be compiled and run as a standalone application, or else compiled and run as a so-called "applet." The Java program file in either event is identified by the suffix ".java". The compiled class always carries the suffix ".class". Below is a Java "Hello World" program that can be compiled and run as a standalone progrm on Polar or Arctos.

public class HelloWorld {
  public static void main (String[] args) {
    System.out.println("Hello World!");
  }
}
To compile this program, assuming it has been typed and stored as the file "HelloWorld.java," the following shell command should be issued:
polar> javac HelloWorld.java
To run this program, the following command should be issued:
polar> java HelloWorld
Below is a larger Java program which is suitable for compiling and running as a Java applet. An applet is a small Java program that runs out of an applet viewer or a Web browser (like Netscape).
// This example is from the book _Java in a Nutshell_ by David Flanagan.
// Written by David Flanagan.  Copyright (c) 1996 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.

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

public class Scribble extends Applet {
    private int last_x = 0;
    private int last_y = 0;
    private Color current_color = Color.black;
    private Button clear_button;
    private Choice color_choices;
    
    // Called to initialize the applet.
    public void init() {
        // Set the background color
        this.setBackground(Color.white);

        // Create a button and add it to the applet.
        // Also, set the button's colors
        clear_button = new Button("Clear");
        clear_button.setForeground(Color.black);
        clear_button.setBackground(Color.lightGray);
        this.add(clear_button);

        // Create a menu of colors and add it to the applet.
        // Also set the menus's colors and add a label.
        color_choices = new Choice();
        color_choices.addItem("black");
        color_choices.addItem("red");
        color_choices.addItem("yellow");
        color_choices.addItem("green");
        color_choices.setForeground(Color.black);
        color_choices.setBackground(Color.lightGray);
        this.add(new Label("Color: "));
        this.add(color_choices);
    }
    
    // Called when the user clicks the mouse to start a scribble
    public boolean mouseDown(Event e, int x, int y)
    {
        last_x = x; last_y = y;
        return true;
    }
    
    // Called when the user scribbles with the mouse button down
    public boolean mouseDrag(Event e, int x, int y)
    {
        Graphics g = this.getGraphics();
        g.setColor(current_color);
        g.drawLine(last_x, last_y, x, y);
        last_x = x;
        last_y = y;
        return true;
    }

    // Called when the user clicks the button or chooses a color
    public boolean action(Event event, Object arg) {
        // If the Clear button was clicked on, handle it.
        if (event.target == clear_button) {
            Graphics g = this.getGraphics();
            Rectangle r = this.bounds();
            g.setColor(this.getBackground());
            g.fillRect(r.x, r.y, r.width, r.height);
            return true;
        }
        // Otherwise if a color was chosen, handle that
        else if (event.target == color_choices) {
            String colorname = (String) arg;
            if (arg.equals("black")) current_color = Color.black;
            else if (arg.equals("red")) current_color = Color.red;
            else if (arg.equals("yellow")) current_color = Color.yellow;
            else if (arg.equals("green")) current_color = Color.green;
            return true;
        }
        // Otherwise, let the superclass handle it.
        else return super.action(event, arg);
    }

}
To run this applet, which is saved as the file "Scribble.java," you need to compile it, as before, and then link to the compiled "Scribble.class" file from within an HTML file, which can be executed by the appletviewer application or a Web browser. To run this applet, use the HTML file "Scribble.html," which is shown below:
<HTML>
<HEAD>
<TITLE>The Scribble Applet</TITLE>
</HEAD>
<BODY>
If you're using a Java-enabled browser, please scribble away in the
applet below.  If your browser can't run Java applets, you're out of
luck.  Sorry!
<P>
<APPLET code="Scribble.class" width=500 height=300>
</APPLET>
</BODY>
</HTML>
(Both the Scribble.java and the Scribble.html files can be copied from the directory ~allen/courses/cs250/java/examples/section1) This file should be in the same directory as your Scribble.java and Scribble.class files. Note the HTML command in this file, beginning with "<APPLET ", which identifies the object code file for the applet to be executed. After compiling the program, you can run it using the appletviewer by issuing the following command:

polar> appletviewer Scribble.html

Basic Java syntax

Java syntax is similar to C/C++ syntax, though the language is more consistent in many ways. Below is a brief summary of its main features.
Comments

Double slashes (//) indicate that the rest of the line is a comment

Variable Declarations
float x, y;
boolean b;
char c;        // characters in Java use 16-bit Unicode (not ASCII)
int i, j;
a : ARRAY[INTEGER];

Expressions and Operators

Operators in Java mirror those in C/C++, except that + applies to String values as well as numbers, and the dereferencing and referencing operators * and & are not available (since there are no pointers in Java).

Class declaration
[import java.applet.*]
[import java.awt.*]

public class <CLASSNAME> [extends <CLASSNAME>] {
   <declaration of variables for any object of this class>
   <declaration of functions for any object of this class>
}  // class <CLASSNAME>

Here, the optional "extends" clause is used when the program is written as an extension, or subclass, of an existing class. Often, the existing class is "Applet", in which case the optional first two "import" lines allow simplified referencing of methods from the classes that this class uses. Java programs that are activated through HTML files are commonly written as subclasses of the standard class Applet; they usually import methods from the classes java.applet and java.awt. This case is illustrated in the long example above.

Method Declarations
<type> <METHODNAME> (<params>) {
   <local variable declarations>
   <statements>
   [return <expression>]
}
A Java "method" is similar to a C/C++ function, except that it is always defined inside a class declaration. The type returned by a method may be any class, or else "void". If it is not void, the optional "return" statement should be used in order to return a value to the caller.

As in C++, a class constructor is a method that is called to create and initialize an object of a class. (There are no constructors in the examples above.) However, unlike C++, there are no destructors in Java. All objects are dynamically allocated, and reclamation of memory used by unreferenced objects at run time is done by automatic garbage collection.

Loops
for (<initialization> ; <condition> ; <increment>) {
   <statements>
}

Conditionals
if (<condition>) {
   <statements>
 [else {
   <statements>
  }
 ]
}
The else clause is optional, as are the braces {} when <statements> contain only one statement.

Input, Output, and Other Major Packages

Standard input and output are performed through methods in the java.io package. The major packages in the Java API (application programming interface) are:
java.applet -- a small superclass of all applets
java.awt -- abstract windowing toolkit; classes for graphics and GUI interfaces
java.io -- stream and file I/O classes
java.lang -- core language classes (implicitly imported by all programs)
java.net -- classes for networking, including URL,
java.util -- some useful general classes, like date, random, vector, and stack