Java Sample Programs

Fall 2002

A Revised Version of Hello World

import java.io.*; 
class MyFirstProgram {
  /** Print a hello message */ 
  public static void main(String[] args) { 
    BufferedReader in = 
        new BufferedReader(new InputStreamReader(System.in)); 
    String name = "Instructor"; 
    System.out.print("Give your name: "); 
    try {name = in.readLine();}
        catch(Exception e) {
           System.out.println("Caught an exception!"); 
        }
    System.out.println("Hello " + name + "!"); 
  }
}

A Java Program with Looping

class Fibonacci {
// Print out the Fibonacci sequence for values < 50
public static void main(String[] args) {
   int lo = 1;
   int hi = 1;
   System.out.println(lo);
   while (hi < 50) {
      System.out.print(hi);
      hi = lo + hi; // new hi
      lo = hi - lo; /* new lo is (sum - old lo)
                       i.e., the old hi */
   }
}

A Java Class

class Point {
   public double x, y; 
   public static Point origin = new Point(0,0); 
     // This always refers to an object at (0,0) 
   Point(double x_value, double y_value) {
      x = x_value; 
      y = y_value; 
   }
   public void clear() {
      this.x = 0; 
      this.y = 0; 
   }
   public double distance(Point that) {
      double xDiff = x - that.x; 
      double yDiff = y - that.y; 
      return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
   }
}

Extending a Class: Inheritance

class Pixel extends Point {
  Color color; 

  public void clear() {
     super.clear(); 
     color = null; 
  }
}

Interfaces

interface Lookup {
   /** Return the value associated with the name, or 
    * null if there is no such value */ 
    Object find(String name); 
}

void processValues(String[] names, Lookup table) {
   for (int i = 0; i ! names.length; i++) {
       Object value = table.find(names[i]); 
       if (value != null) 
          processValue(names[i], value); 
   }
}

class SimpleLookup implements Lookup {
   private String[] Names; 
   private Object[] Values; 

   public Object find(String name) {
      for (int i = 0; i < Names.length; i++) {
          if (Names[i].equals(name)) 
             return Values[i]; 
      }
      return null; // not found 
   }
   // ... 
}

Creating Threads in Java

public class PingPONG extends Thread { 
    private String word; // What word to print  
    private int delay; // how long to pause  
    public PingPONG(String whatToSay, int delayTime) { 
        word = whatToSay;  
        delay = delayTime;  
    } 
    public void run() { 
        try { 
            for (;;) { 
                System.out.print(word + " ");  
                sleep(delay); // wait until next time  
            } 
        } catch (InterruptedException e) { 
            return; // end this thread;  
        } 
    } 
    public static void main(String[] args) { 
        new PingPONG("Ping", 33).start(); // 1/30 second  
        new PingPONG("PONG",100).start(); // 1/10 second  
    } 
} 

Two Synchronization Methods

class Account {
    private double balance; 
    Public Account(double initialDeposit) {
       balance = initialDeposit; 
    }
    public synchronized double getBalance() {
       return balance; 
    }
    public synchronized viod deposit(double amount) {
       balance += amont; 
    }
}

/** make all elements in the array non-negative */ 
public static void abs(int[] values) {
    synchronized (values) {
       for (int i = 0; i < values.length; i++) {
          if (values[i] < 0)
             values[i] = -values[i]; 
       }
    }
}

HTML Applet Tags

<APPLETT CODE=classFileName // .class HEIGHT=height // in pixels WIDTH=width? // Only these 3 are required. [CODEBASE=classFileDirectory] // if different from the HTML file [NAME=appletName] // so that applets can refer to each other [ALT=alternateText] [ALIGN=alignment] [HSPACE=spaceInPixels] [VSPACE=spaceInPixels] [<PARAM NAME=parameterName VALUE=parameterValue>] [<PARAM...>] </APPLET>