NumFormat.java Formats real numbers with DecimalFormat.

import java.text.*;

/** Formatting real numbers with DecimalFormat.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NumFormat {
  public static void main (String[] args) {
    DecimalFormat science = new DecimalFormat("0.000E0");
    DecimalFormat plain = new DecimalFormat("0.0000");

    for(double d=100.0; d<140.0; d*=1.10) {
      System.out.println("Scientific: " + science.format(d) +
                         " and Plain: " + plain.format(d));
    }
  }
}

ModificationTest.java Demonstrates changing fields of an object. Inherits from ReferenceTest.java.

/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

import java.awt.Point;

public class ModificationTest extends ReferenceTest {
  public static void main(String[] args) {
    Point p1 = new Point(1, 2); // Assign Point to p1
    Point p2 = p1; // p2 is new reference to *same* Point
    print("p1", p1); // (1, 2)
    print("p2", p2); // (1, 2)
    munge(p2); // Changes fields of the *single* Point
    print("p1", p1); // (5, 10)
    print("p2", p2); // (5, 10)
  }

  public static void munge(Point p) {
    p.x = 5;
    p.y = 10;
  }
}


/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

import java.awt.Point;

public class ReferenceTest {
  public static void main(String[] args) {
    Point p1 = new Point(1, 2); // Assign Point to p1
    Point p2 = p1; // p2 is new reference to *same* Point
    print("p1", p1); // (1, 2)
    print("p2", p2); // (1, 2)
    triple(p2); // Doesn?t change p2
    print("p2", p2); // (1, 2)
    p2 = triple(p2); // Have p2 point to *new* Point
    print("p2", p2); // (3, 6)
    print("p1", p1); // p1 unchanged: (1, 2)
  }

  public static Point triple(Point p) {
    p = new Point(p.x * 3, p.y * 3); // Redirect p
    return(p);
  }

  public static void print(String name, Point p) {
    System.out.println("Point " + name + "= (" +
                       p.x + ", " + p.y + ").");
  }
}

Tests the class type of an object using the isInstance method (preferred over instanceof operator).

/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

interface Barking {}

class Mammal {}

class Canine extends Mammal {}

class Dog extends Canine implements Barking {}

class Retriever extends Dog {}

public class InstanceOf {
  public static void main(String[] args) {
    Canine wolf = new Canine();
    Retriever rover = new Retriever();

    System.out.println("Testing instanceof:");
    report(wolf, "wolf");
    System.out.println();
    report(rover, "rover");

    System.out.println("\nTesting isInstance:");
    Class barkingClass = Barking.class;
    Class dogClass = Dog.class;
    Class retrieverClass = Retriever.class;
    System.out.println("  Does a retriever bark? " +
                       barkingClass.isInstance(rover));
    System.out.println("  Is a retriever a dog? " +
                       dogClass.isInstance(rover));
    System.out.println("  Is a dog necessarily a retriever? " +
                       retrieverClass.isInstance(new Dog()));
  }

  public static void report(Object object, String name) {
    System.out.println("  " + name + " is a mammal: " +
                       (object instanceof Mammal));
    System.out.println("  " + name + " is a canine: " +
                       (object instanceof Canine));
    System.out.println("  " + name + " is a dog: " +
                       (object instanceof Dog));
    System.out.println("  " + name + " is a retriever: " +
                       (object instanceof Retriever));
  }
}

URLTest.java Demonstrates try/catch blocks.

/** Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.  
 */
 
 // Further simplified getURL method. 
 
 public URL getURL() {
    if (url != null) {
      return(url);
    }
    System.out.print("Enter URL: ");
    System.out.flush();
    BufferedReader in = new BufferedReader(
                          new InputStreamReader(System.in));
    String urlString = null;
    try {
      urlString = in.readLine();
      url = new URL(urlString);
    } catch(MalformedURLException mue) {
      System.out.println(urlString + " is not valid.\n" +
                                 "Try again.");
      getURL();
    } catch(IOException ioe) {
      System.out.println("IOError when reading input: " + ioe);
      ioe.printStackTrace(); // Can skip return(null) now
    } finally {
      return(url);
    }
  }

import java.net.*; // For URL, MalformedURLException
import java.io.*;  // For BufferedReader

/** A small class to demonstrate try/catch blocks.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class URLTest {
  public static void main(String[] args) {
    URLTest test = new URLTest();
    test.getURL();
    test.printURL();
  }

  private URL url = null;

  /** Read a string from user and create a URL from it. If
   *  reading fails, give up and report error. If reading
   *  succeeds but URL is illegal, try again.
   */

  public URL getURL() {
    if (url != null) {
      return(url);
    }
    System.out.print("Enter URL: ");
    System.out.flush();
    BufferedReader in = new BufferedReader(
                          new InputStreamReader(System.in));
    String urlString;
    try {
      urlString = in.readLine();
    } catch(IOException ioe) {
      System.out.println("IOError when reading input: " + ioe);
      ioe.printStackTrace(); // Show stack dump.
      return(null);
    }
    try {
      url = new URL(urlString);
    } catch(MalformedURLException mue) {
      System.out.println(urlString + " is not valid.\n" +
                         "Try again.");
      getURL();
    }
    return(url);
  }

  /** Print info on URL. */

  public void printURL() {
    if (url == null) {
      System.out.println("No URL.");
    } else {
      String protocol = url.getProtocol();
      String host = url.getHost();
      int port = url.getPort();
      if (protocol.equals("http") && (port == -1)) {
        port = 80;
      }
      String file = url.getFile();
      System.out.println("Protocol: " + protocol +
                         "\nHost: " + host +
                         "\nPort: " + port +
                         "\nFile: " + file);
    }
  }
}

/** Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.  
 */
 
  // Simplified getURL method.
  
  public URL getURL() {
    if (url != null) {
      return(url);
    }
    System.out.print("Enter URL: ");
    System.out.flush();
    BufferedReader in = new BufferedReader(
                          new InputStreamReader(System.in));
    String urlString = null;
    try {
      urlString = in.readLine();
      url = new URL(urlString);
    } catch(MalformedURLException mue) {
      System.out.println(urlString + " is not valid.\n" +
                                    "Try again.");
      getURL();
    } catch(IOException ioe) {
      System.out.println("IOError when reading input: " + ioe);
      ioe.printStackTrace(); // Show stack dump
      return(null);
    }
    return(url);
  }

ExecTest.java illustrates use of the Exec class.

/** A test of the Exec class.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class ExecTest {
  public static void main(String[] args) {
    // Note: no trailing "&" -- special shell chars not
    // understood, since no shell started. Besides, exec
    // doesn?t wait, so the program continues along even
    // before Netscape pops up.
    Exec.exec("/usr/local/bin/netscape");

    // Run commands, printing results.
    Exec.execPrint("/usr/bin/ls");
    Exec.execPrint("/usr/bin/cat Test.java");

    // Don?t print results, but wait until this finishes.
    Exec.execWait("/usr/java1.3/bin/javac Test.java");

    // Now Test.class should exist.
    Exec.execPrint("/usr/bin/ls");
  }
}

DropBall.java Uses a while loop to determine how long it takes a ball to fall from the top of the Washington Monument to the ground.

/** Simulating dropping a ball from the top of the Washington
 *  Monument. The program outputs the height of the ball each
 *  second until the ball hits the ground.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class DropBall {
  public static void main(String[] args) {
    int time = 0;
    double start = 550.0, drop = 0.0;
    double height = start;
    while (height > 0) {
      System.out.println("After " + time +
                   (time==1 ? " second, " : " seconds,") +
                   "the ball is at " + height + " feet.");
      time++;
      drop = freeFall(time);
      height = start - drop;
    }
    System.out.println("Before " + time + " seconds could " +
                       "expire, the ball hit the ground!");
  }

  /** Calculate the distance in feet for an object in
   *  free fall.
   */

  public static double freeFall (float time) {
    // Gravitational constant is 32 feet per second squared
    return(16.0 * time * time); // 1/2 gt^2
  }
}

Loading Images

JavaMan1.java Applet that loads an image from a relative URL.
*************************************************************
import java.applet.Applet;
import java.awt.*;

/** An applet that loads an image from a relative URL. 
 *
>>>>>>>>>>>>>>>>>>>

public class JavaMan1 extends Applet {
  private Image javaMan;

  public void init() {
    javaMan = getImage(getCodeBase(),"images/Java-Man.gif");
  }

  public void paint(Graphics g) {
    g.drawImage(javaMan, 0, 0, this);
  }
}
>>>>>>>>>>>>>>>>>>>>
JavaMan2.java Illustrates loading an image from an absolute URL.
********************
import java.applet.Applet;
import java.awt.*;
import java.net.*;

/** An applet that loads an image from an absolute
 *  URL on the same machine that the applet came from.
 *
***********************

public class JavaMan2 extends Applet {
  private Image javaMan;

  public void init() {
    try {
      URL imageFile = new URL("http://www.corewebprogramming.com" +
                              "/images/Java-Man.gif");
      javaMan = getImage(imageFile);
    } catch(MalformedURLException mue) {
      showStatus("Bogus image URL.");
      System.out.println("Bogus URL");
    }
  }

  public void paint(Graphics g) {
    g.drawImage(javaMan, 0, 0, this);
  }
}
>>>>>>>>>>>>>>>>>>>>>
# JavaMan3.java An application that loads an image from a local file. Uses the following image and two files:

    * Java-Man.gif which should be placed in images subdirectory.
    * WindowUtilities.java Simplifies the setting of native look and feel.
    * ExitListener.java WindowListener to support terminating the application.
*******************
JavaMan3.java
*******************
import java.awt.*;
import javax.swing.*;

/** An application that loads an image from a local file. 
 *  Applets are not permitted to do this.
 *
**********************

class JavaMan3 extends JPanel {
  private Image javaMan;

  public JavaMan3() {
    String imageFile = System.getProperty("user.dir") +
                       "/images/Java-Man.gif";
    javaMan = getToolkit().getImage(imageFile);
    setBackground(Color.white);
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(javaMan, 0, 0, this);
  }
  
  public static void main(String[] args) {
    JPanel panel = new JavaMan3();
    WindowUtilities.setNativeLookAndFeel();
    WindowUtilities.openInJFrame(panel, 380, 390);
  }   
}
>>>>>>>>>>>>>>>>>>
Preload.java An application that demonstrates the effect of preloading an image before drawing. Specify -preload as a command-line argument to preload the image. In this case, the prepareImage method is called to immediately start a thread to load the image. Thus, the image is ready to display when the user later selects the Display Image button. 
>>>>>>>>>>>>>>>>>>>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;

/** A class that compares the time to draw an image preloaded
 *  (getImage, prepareImage, and drawImage) vs. regularly
 *  (getImage and drawImage).
 *  


 *  The answer you get the regular way is dependent on the
 *  network speed and the size of the image, but if you assume
 *  you load the applet "long" (compared to the time the image
 *  loading requires) before pressing the button, the drawing
 *  time in the preloaded version depends only on the speed of
 *  the local machine.
 *
 **********************

public class Preload extends JPanel implements ActionListener {

  private JTextField timeField;
  private long start = 0;
  private boolean draw = false;
  private JButton button;
  private Image plate;

  public Preload(String imageFile, boolean preload) {
    setLayout(new BorderLayout());
    button = new JButton("Display Image");
    button.setFont(new Font("SansSerif", Font.BOLD, 24));
    button.addActionListener(this);
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(button);
    timeField = new JTextField(25);
    timeField.setEditable(false);
    timeField.setFont(new Font("SansSerif", Font.BOLD, 24));
    buttonPanel.add(timeField);
    add(buttonPanel, BorderLayout.SOUTH);
    registerImage(imageFile, preload);

  }

  /** No need to check which object caused this,
   *  since the button is the only possibility.
   */

  public void actionPerformed(ActionEvent event) {
    draw = true;
    start = System.currentTimeMillis();
    repaint();
  }

  // Do getImage, optionally starting the loading.

  private void registerImage(String imageFile, boolean preload) {
    try {
      plate = getToolkit().getImage(new URL(imageFile));
      if (preload) {
        prepareImage(plate, this);
      }
    } catch(MalformedURLException mue) {
      System.out.println("Bad URL: " + mue);
    }
  }

  /** If button has been clicked, draw image and
   *  show elapsed time. Otherwise, do nothing.
   */

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (draw) {
      g.drawImage(plate, 0, 0, this);
      showTime();
    }
  }

  // Show elapsed time in textfield.

  private void showTime() {
    timeField.setText("Elapsed Time: " + elapsedTime() +
                      " seconds.");
  }

  // Time in seconds since button was clicked.

  private double elapsedTime() {
    double delta = (double)(System.currentTimeMillis() - start);
    return(delta/1000.0);
  }

  public static void main(String[] args) {
    JPanel preload;

    if (args.length == 0) {
      System.out.println("Must provide URL");
      System.exit(0);
    }
    if (args.length == 2 && args[1].equals("-preload")) {
      preload = new Preload(args[0], true);
    } else {
      preload = new Preload(args[0], false);
    }

    WindowUtilities.setNativeLookAndFeel();
    WindowUtilities.openInJFrame(preload, 1000, 750);
  }
}
<<<<<<<<<<<<<<<<<<

Basic template for a Java applet

AppletTemplate.java
>>>>>>>>>>>>>>>>>>>>
import java.applet.Applet;
import java.awt.*;

********************

public class AppletTemplate extends Applet {

  // Variable declarations.

  public void init() {
    // Variable initializations, image loading, etc.
  }

  public void paint(Graphics g) {
    // Drawing operations.
  }
}
>>>>>>>>>>>>>>>>>>>>>

ForwardSnippet.java Partial servlet illustrating how to use a RequestDispatcher to forward requests

ForwardSnippet.java Partial servlet illustrating how to use a RequestDispatcher to forward requests

public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
    throws ServletException, IOException {
  String operation = request.getParameter("operation");
  if (operation == null) {
    operation = "unknown";
  }
  if (operation.equals("operation1")) {
    gotoPage("/operations/presentation1.jsp",
             request, response);
  } else if (operation.equals("operation2")) {
    gotoPage("/operations/presentation2.jsp",
             request, response);
  } else {
    gotoPage("/operations/unknownRequestHandler.jsp",
             request, response);
  }
}

private void gotoPage(String address,
                      HttpServletRequest request,
                      HttpServletResponse response)
    throws ServletException, IOException {
  RequestDispatcher dispatcher =
    getServletContext().getRequestDispatcher(address);
  dispatcher.forward(request, response);
}

Example illustrating inheritance and abstract classes

***********************************
# Example illustrating inheritance and abstract classes.

    * Shape.java The parent class (abstract) for all closed, open, curved, and straight-edged shapes.
    * Curve.java An (abstract) curved Shape (open or closed).
    * StraightEdgedShape.java A Shape with straight edges (open or closed).
    * Measurable.java Interface defining classes with measurable areas.
    * Circle.java A circle that extends Shape and implements Measurable.
    * MeasureUtil.java Operates on Measurable instances.
    * Polygon.java A closed Shape with straight edges; extends StraightEdgedShape and implements Measurable.
    * Rectangle.java A rectangle that satisfies the Measurable interface; extends Polygon.
    * MeasureTest.java Driver for example.
**************************************
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Shape.java 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** The parent class for all closed, open, curved, and 
 *  straight-edged shapes.
 *
 ############################
public abstract class Shape {
  protected int x, y;

  public int getX() {
    return(x);
  }

  public void setX(int x) {
    this.x = x;
  }

  public int getY() {
    return(y);
  }

  public void setY(int y) {
    this.y = y;
  }
}
#############################
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Curve.java An (abstract) curved Shape (open or closed)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** A curved shape (open or closed). Subclasses will include
 *  arcs and circles.
 *
***********************

public abstract class Curve extends Shape {}
##############################
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
StraightEdgedShape.java A Shape with straight edges (open or closed). 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** A Shape with straight edges (open or closed). Subclasses
 *  will include Line, LineSegment, LinkedLineSegments,
 *  and Polygon.
 *
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public abstract class StraightEdgedShape extends Shape {}
################################
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Measurable.java Interface defining classes with measurable areas
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** Used in classes with measurable areas. 
 *
 **************

public interface Measurable {
  double getArea();
}
#################################
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Circle.java A circle that extends Shape and implements Measurable.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** A circle. Since you can calculate the area of
 *  circles, class implements the Measurable interface.
 *
***********************************
public class Circle extends Curve implements Measurable {
  private double radius;

  public Circle(int x, int y, double radius) {
    setX(x);
    setY(y);
    setRadius(radius);
  }

  public double getRadius() {
    return(radius);
  }

  public void setRadius(double radius) {
    this.radius = radius;
  }

  /** Required for Measurable interface. */

  public double getArea() {
    return(Math.PI * radius * radius);
  }
}
############################
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MeasureUtil.java Operates on Measurable instances
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/** Some operations on Measurable instances. 
 *

************************
public class MeasureUtil {
  public static double maxArea(Measurable m1,
                               Measurable m2) {
    return(Math.max(m1.getArea(), m2.getArea()));
  }

  public static double totalArea(Measurable[] mArray) {
    double total = 0;
    for(int i=0; i
~~~~~~~~~~~~~~~~~~~~~~