Java - An Introductory Language Tutorial

by E. Andrew Johnson, The Open Group Research Institute

Overview - What is Java

History of the development of Java

History of the development of Java

Highlights of the Java Language

Java - It's Simple

Java - It's Object Oriented

Java - It's Safe

Java - It's Secure

Java - It's Portable

Java - It's Fast (potentially)

Java - It's Multi-threaded

The Java Language

Program Structure

First Java Program

// HelloWorld.java
// First Java program, to get experience with using the Java tools
class HelloWorld
{
    public static void main (String args[])
    {
        System.out.println("Hello, World!");
    }
}

To compile this program, enter the command:javac HelloWorld.java

This will produce the binary bytecode file HelloWorld.class as output.

To execute this program, enter the command:java HelloWorld

Hello, World! should appear on your terminal.

Lexical Structure

Analysis of HelloWorld Program

Control Constructs

Exception Handling

Java Built-in Types

Java Built-in Types (cont.)

Operators

Operators (cont.)

Java Pointers

Constructed Types: Arrays and Classes

Constructed Types: Classes

Java Class Example

Java Class Example: Notes

Java Class Example (revised)

Java Class Example (revised): Notes

Object-Oriented Features

Storage Management

Initialization

First Java Application

// Java program to compute the current value if the $24 paid for
// Manhattan Island in 1624 had been deposited in the bank
// at a specified annual rate, compounded annually.
class Manhattan
{
    public static void main (String args [] ) {
        long amt = 2400;  // Express in cents
        int rate;
        short yr;
        if (args.length == 0)
            rate = 2;      // default rate is 2% if none specified
        else
            rate = Integer.parseInt(args[0]);
        for (yr = 1624; yr < 1996; yr++) {
            amt += amt * rate / 100;
        }
        System.out.println("The amount in the bank in " + yr
            + " would be $" + amt / 100 + "." + amt % 100);
    }
}

Notes on Application

Packages

Packages (cont.)

Method Signatures

Real Application (part 1)

import java.io.*;
class Mortgage {
    // Convert double to dollars and cents
    static String format(double dollars)
    {   String numString = Double.toString(dollars);
        int dotpos = numString.indexOf(`.');
        if (dotpos < 0)  // Check if whole number
            return numString;
        // Check if excess fraction digits
        else if (dotpos < numString.length() - 2)  
            return numString.substring(0, dotpos + 3); // `.'+ 2 digits
        else return numString + "0"; // Assume only 1 fraction digit
    }

Real Application (part 2)

    public static void main(String args[]) throws IOException
    {   DataInputStream din = new DataInputStream(System.in);
        System.out.println("Enter principal (e.g. 8250.00 :");
        double bal = new Double(din.readLine()).doubleValue();
        System.out.println("Enter annual interest rate (e.g. 10.25) :");
        double intyr = new Double(din.readLine()).doubleValue() / 100.;
        System.out.println("Enter number of years :");
        short nyears = (short) new Integer(din.readLine()).intValue();
        System.out.println("\nprincipal=" + bal + "  interest=" + intyr
                            + "  years=" + nyears);
        double intmo = intyr / 12.;
        int npmts = nyears * 12;
        double pmt = bal * (intmo / (1. - Math.pow(1. + intmo, -npmts)));

Real Application (part 3)

        System.out.println("payment\ttotal\tinterest principal balance");
        System.out.println("number\tpayment\tpayment\tpayment");
        System.out.println("\t\t\t\t" + bal);
        for (short mo = 1; mo <= npmts; ++mo) {
            double prinpmt, intpmt = bal * intmo;
            if (mo < npmts)
                prinpmt = pmt - intpmt;
            else prinpmt = bal;
            bal -= prinpmt;
            System.out.println(mo + "\t" + format(intpmt + prinpmt)
                + "\t" + format(intpmt)
                + "\t" + format(prinpmt)
                + "\t" + format(bal));
        }
    }
}

Application Execution

% java Mortgage
Enter principal (e.g. 8250.00 :
14000
Enter annual interest rate (e.g. 10.25) :
10
Enter number of years :
4

principal=14000  interest=0.1  years=4
payment total   interest principal balance
number  payment payment payment
                                14000
1       355.07  116.66  238.41  13761.60
2       355.07  114.68  240.39  13521.20
3       355.07  112.67  242.40  13278.80
...
47      355.07  5.84    349.23  352.14
48      355.07  2.93    352.14  0
%

Real Application Notes

Conversions

Applet Programming

Applets - Basic Principles

Application
Stand-alone Java program: starts at main and runs to completion
Applet
Sub-program that runs underneath some other control program

Basic Principles (cont.)

Basic Applet Methods

Basic Applet Methods (cont.)

First Applet

// HelloWorldApplet.java
// First Java applet, to get experience with using a Java-capable browser
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorldApplet extends Applet
{
    public void paint (Graphics gr)
    {
        gr.drawString("Hello, World!", 10, 100);
    }
}

Notes on First Applet

Running Applet

Applet Display

Notes on Applet Tag

Applet Parameters

Actions and Events

GUI Interfaces

Mortgage Applet (1)

import java.applet.Applet;
import java.awt.*;
public class MortgageApp extends Applet
{   TextField balField;
    TextField intField;
    TextField nyrField;
    Button OK;
    TextArea msgArea;

Mortgage Applet (2)

    // Convert double to dollars and cents
    static String format(double dollars)
    {   String numString = Double.toString(dollars);
        int dotpos = numString.indexOf(`.');
        if (dotpos < 0)  // Check if whole number
            return numString;
        // Check for excess fraction digits
        else if (dotpos < numString.length() - 2)
            return numString.substring(0, dotpos + 3); // `.'+ 2 digits
        else return numString + "0"; // Assume only 1 fraction digit
    }

Mortgage Applet (3)

    public void init()
    {   balField = new TextField("", 15);
        intField = new TextField("", 5);
        nyrField = new TextField("", 5);
        OK = new Button("Compute");
        msgArea = new TextArea("", 15, 60);
        msgArea.setEditable(false);
        add(new Label("Enter principal"));
        add(balField);
        add(new Label("Enter annual interest rate"));
        add(intField);
        add(new Label("Enter number of years"));
        add(nyrField);
        add(OK);
        add(msgArea);
    } 

Mortgage Applet (4)

    public boolean action(Event evt, Object arg)
    {   if (evt.target == OK) {
            this.update();
            return true;
        }
        else return false;
    }

Mortgage Applet (5)

    void update()
    {   String balString = balField.getText();
        String intString = intField.getText();
        String nyrString = nyrField.getText();
        if (balString.trim().length() == 0)
            msgArea.setText("Principal amount missing");
        else if (intString.trim().length() == 0)
            msgArea.setText("Interest rate missing");
        else if (nyrString.trim().length() == 0)
            msgArea.setText("Number of years missing");
        else {
            double bal = new Double(balString).doubleValue();
            double intyr = new Double(intString).doubleValue() / 100.;
            short nyears = (short) new Integer(nyrString).intValue();

Mortgage Applet (6)

            StringBuffer msg = new StringBuffer();
            msg.append("\nprincipal=" + bal + "  interest=" + intyr
                     + "  years=" + nyears + "\n");
            double intmo = intyr / 12.;
            int npmts = nyears * 12;
            double pmt = bal * (intmo / (1.- Math.pow(1.+ intmo,-npmts)));
            msg.append("payment\ttotal\tinterest\tprincipal\tbalance\n");
            msg.append("number\tpayment\tpayment\tpayment\n");
            msg.append("\t\t\t\t" + bal + "\n");

Mortgage Applet (7)

            for (short mo = 1; mo <= npmts; ++mo) {
                double prinpmt, intpmt = bal * intmo;
                if (mo < npmts)
                    prinpmt = pmt - intpmt;
                else prinpmt = bal;
                bal -= prinpmt;
                msg.append(mo + "\t" + format(intpmt + prinpmt)
                    + "\t" + format(intpmt)
                    + "\t" + format(prinpmt)
                    + "\t" + format(bal) + "\n");
            }
            msgArea.setText(msg.toString());
        }
    }
}

Running Mortgage Applet

<HTML>
<HEAD>
<TITLE> Mortgage Calculator
</HEAD>
<BODY>
<APPLET code="MortgageApp.class" WIDTH=500 HEIGHT=300>
If you see this text, it means that you are not running a Java-capable browser.
</APPLET>
</BODY>
</HTML>

Mortgage Applet - Initial Window

Mortgage Applet - One Field Entered

Mortgage Applet - Fields Completed

Notes on Mortgage Applet