CSC224 Mar29

slide version

single file version

Contents

  1. 4 Uses of Classes in Java
  2. Application Program
  3. An Application Program Example
  4. A Class with Utility Methods
  5. A Class with Utility Methods Example
  6. A Class Defining a Type
  7. Example Class Type I
  8. Example Class Type II
  9. Application using the StopWatch class type

4 Uses of Classes in Java[1] [top]

The Java class unit is used in Java for several different purposes:

Application Program[2] [top]

An Application Program Example[3] [top]

An application class must have a main method in order to be executable.

/**
 * Application class that prompts for an input string, 
 * converts the string to upper case and prints the 
 * converted string.
 * @author glancast
 */
public class StringApp
{
    /**
     * The main program of this application
     * @param args - command line arguments (not used)
     */
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        String line;

        greeting();

        System.out.print("Enter an input line: ");
        line = in.nextLine();
        line = line.toUpperCase();
        System.out.printf("\nHere is your input converted to upper case:\n");
        System.out.println(line);
    }  

    /** 
     * Prints an introductory message to explain
     * what input this application expects and what it does.
     */
    public static void greeting()
    {
        String msg = 
            "This program will read an input line, convert it\n" +
            "to upper case, and print the converted string.";

        System.out.println(msg);
    }

}

A Class with Utility Methods[4] [top]

A Class with Utility Methods Example[5] [top]


public class Stats {
    
    /**
     * Returns the maximum of an int array.
     * @param a
     */
    public static int maximum(int[] a)
    {
        int max = Integer.MIN_VALUE;
        for(int i = 0; i < a.length; i++) {
            if ( a[i] > max ) {
                max = a[i];
            }
        }
        return max;
    }
    
    /**
     * Returns the mean (average) of values in an integer array
     * @param a - the array
     * @return the mean value of the array members
     */
    public static double mean(int[] a)
    {
        double sum = 0.0;
        for(int i = 0; i < a.length; i++) {
            sum += a[i];
        }
        return sum / a.length;
    }
}

A Class Defining a Type[6] [top]

A type defines both data and operations on that data.

A Java class can be used to define a new type.

Variables can then be defined of that class type.

Each variable can have its own instance value of the class type.

Example Class Type I[7] [top]

A StopWatch could be an concrete object in some application/problem context.


public class StopWatch {

  /* private instance members */
  private double start;

  /* public instance methods */
  /**
   * Initialize this stopwatch start time to present time
   */
  public StopWatch()
  {
    start = System.currentTimeMillis();
  }
	
  /**
   * Reset this stopwatch to the present time
   */
  public void reset()
  {
    start = System.currentTimeMillis();
  }
	
  /**
   * Returns the elapsed time in milliseconds since this 
   * stopwatch was created or since it was reset.
   */
  public double elapsedTime()
  {
    double now = System.currentTimeMillis();
    return (now - start);
  }
}

Example Class Type II[8] [top]

The Counter class may not correspond to any object directly specified in a problem or application context, but this class may be used in writing and application in such a context.

public class Counter {
  /* private instance members */
  private String id;
  private int value;
	

  /* public instance constructor and methods */
  /**
   * Initialize this counter's id name = idName and value = 0.
   * @param idName
   */
  public Counter(String idName)
  {
    id = idName;
    value = 0;
  }
	
  /**
   * Increment this counter's value by 1
   */
  public void increment()
  {
    value++;
  }
	
  /**
   * Return the value of this counter.
   */
  public int val()
  {
    return value;
  }
	
  /**
   * (Inherited) method; new implementation
   * Returns a string representation of this instance.
   */
  public String toString()
  {
    return value + " " + id;
  }
}

Application using the StopWatch class type[9] [top]


import java.util.Random;
import java.util.Scanner;

public class RandomApp 
{
  public static void main(String[] args) {
    int n;
    int[] a;
    Scanner in = new Scanner(System.in);
    StopWatch sw = new StopWatch();

    System.out.print("How many random integers? ");
    n = in.nextInt();
    a = new int[n];

    Random r = new Random();
    sw.reset();
    for(int i = 0; i < a.length; i++) {
	a[i] = r.nextInt(100);
    }
    double tm = sw.elapsedTime();
    System.out.printf("Time to initialize array of %d random integers: %f (msec)\n", 
                         n, tm);

    sw.reset();
    double m = Stats.mean(a);
    double sd = Stats.stddev(a);
    tm = sw.elapsedTime();

    System.out.printf("For %d random values: mean = %f, stddev = %f\n", n, m, sd);
    System.out.printf("Elapsed time to calculate mean and stddev: %f (msec)\n", tm);
  }
}