CS 66-460
Introduction to Graphical Human Machine Interfaces

Java (Part 2)

MONDAY, APRIL 7, 1997

Instructor: G. Bowden Wise
Rensselaer Polytechnic Institute
Spring 1997


Outline


Java
Comments

Java supports to styles of comments, both borrowed from C and C++:


Java
Data Types

Integers

  byte     1 byte  [-128, +128]
  short    2 bytes [-32,768, +32,768]
  int      4 bytes [-2,147,483,648, +2,147,483,647]
  long     8 bytes [-9,223,372,036,854,775,808L, 
                    +9,223,372,036,854,775,808L]

Floating Point Numbers

  float    4 bytes +- 3.40282347E+38F
                   (7 significant digits)
  double   8 bytes +- 1.79769313486231570E+308
                   (15 significant digits)

Characters

  char     2 bytes  UNICODE

Boolean

  boolean  1 byte   true, false


Java
Conversions Between Numeric Types

In general, binary operations on numeric types are converted to the largest type when there are variables of mixed numeric types

Java will convert operands in the following order:

Conversions from a larger type to a smaller one require an explicit cast:

   double x = 9.997;
   int    n = x;       // compile time error

   int    n = (int) x; // ok: explicit cast

Java allows assignments from one type to another provided the resulting variable is large enough:

byte .. short .. int .. long .. float .. double
You can always assign a variable of a type that is to the left to the type on its right in the above list.


Java
Conversions and Boolean Types

Java does not allow boolean values to be converted to any numeric types. C/C++ programmers may find this a nuisance, no longer can you do this:

   // function foo() returns an int
   if ( foo(a) )
   {
   }
instead you must do this:
   if ( foo(a) != 0 )
   {
   }

  
Java does not allow assignments within boolean expressions. It is not possible to do this:

   if ( a = 10 )
   {
   }


Java
Constants


Java
Variables


Java
Assignment and Initialization


Java
Operators

1  ++          arithmetic        R   pre or post increment
   --          arithmetic        R   pre or post decrement
   +, -        arithmetic        R   unary plus or minus
   \~          integral          R   bitwise complement (unary)
   !           boolean           R   logical complement (unary)
   (type)      any               R   cast

2  *, /, \%    arithmetic        L   multiplication, division, modulus

3  +, -        arithmetic        L   addition, subtraction
   +           String            L   concatenation

4  <<          integral          L   left shift
   >>          integral          L   right shift with sign extension
   >>>         integral          L   right shift with zero extension

5  <, <=       arithmetic        L   less than, less than or equal
   >, >=       arithmetic        L   greater than, greater than or equal
 
   instanceof object, type       L   type comparison

6  ==          primitive         L   equal (same values)
   !=          primitive         L   not equals (different values)

   ==          object            L   equal (same objects)
   !=          object            L   not equal (differnt objects)

7  &           integral          L   bitwise AND
   &           boolean           L   boolean AND

8  ^           integral          L   bitwise XOR
   ^           boolean           L   boolean XOR

Java
Operators (continued)

9  |           integral          L   bitwise OR
   |           boolean           L   boolean OR

10 &&          boolean           L   conditional AND
11 ||          boolean           L   conditional OR
12 ?:          boolean,any,any   R   conditiional (ternary) assignment

13 =           variable, any     R   assignment
   *=, /=      variable, any     R   assignment with operation
   \%=
   +=, -=
   <<=, >>=
   >>>=
   &=, ^=
   |=


Java
Control Flow
Conditional Statements

if statements:

   if (yourSales >= target)
      quotaMet = true;
or use blocks
   if (yourSales >= target)
   {                       
      quotaMet = true;
      bonus = 1000;       
   }


Java
Control Flow
Conditional Statements

if () else statements:

   if (yourSales >= target)  
      quotaMet = true;
   else
      quotaMet = false;
or use blocks
   if (yourSales > target)
   {
       quotaMet = true;
       bonus = 1000;
   }
   else if (yourSales == target)
   {
       quotaMet = true;
       bonus = 0;
   }   else
   {
       quotaMet = false;
       paycut = -1000;
   }


Java
Control Flow
Indeterminate Loops

while statements:

   while (balance < goal)
      balance += 10;
or use a block:
   while (balance < goal)
   {
      amt = 10;
      balance += amt;
   }

do statements:

   do
   {
      amt = 10;
      balance += amt;
   } while (balance < goal)


Java
Control Flow
Determinate Loops

for and while statements:

   for (int i=0; i < 10; i++)             
      System.out.println ("i: " + i);

   while (i < 10)
      System.out.println ("i: " + i++);
with blocks:

   for (int i=0; i < 10; i++)             
   {
      sum += i;
      System.out.println 
           ("i: " + i + "sum: " + sum);
   }

   while (i < 10)
   {
      sum += i;
      System.out.println 
           ("i: " + i + "sum: " + sum);
      i++;
   }


Java
Control Flow
Multiple Selections

switch statements:

   import jave.util.Date.*;
   Date today = new Date();
   String day = "";
   switch (today.getDay())     
   {
     case 0:
       day = "Sunday";
       break;
     case 1:
       day = "Monday";
       break;
     case 2:
       day = "Tuesday";
         break;
     case 3:
       day = "Wednesday";
         break;
     case 4:
       day = "Thursday";
         break;
     case 5:
       day = "Friday";
         break;
     case 6:
       day = "Saturday";
         break;
     }
   System.out.println ("Today is: " + day);


Java
Control Flow
Break

Un-labeled break statements:

   while (years <= 100)
   {
      balance = (balance + payment) *
                (1       + interest);
      if (balance > goal)
         break;
      years++;
   }

Labeled break statements:

   test: if (check(i))  {
            for (int j=0; j < 10; j++) {
               for (k=0; k < 10; k++) {
                  if (a[i][j] == null)
                     break test;
               }
            }
         }


Java
Control Flow
Continue

Un-labeled continue statements are used to break to the top of a loop:

   while (years <= 100)
   {
      balance = (balance + payment) *
                (1       + interest);

      if (balance ==  500)
      {
         balance = 550;
         continue;
      }
      years++;
   }

Labeled continue statements:


Java
Arrays

Examples:

   int[]  I = new int[100];
   for (int i=0; i < 100; i++)
      I[i] = i; // fill array with 0 to 99

   int lookupTable[]  = { 1, 10, 15, 20, 25, 30};


Java
Arrays (continued)

public class ShellSort
{
   public static void sort(int[] a)
   {
      int n    = a.length;
      int incr = n / 2;
      while (incr >= 1)
      {
         for (int i=incr; i < n; i++)
         {
            int temp = a[i];
            int    j = i;
            while ( j>= i  && temp < a[j-incr])
            {
               a[j] = a[j-incr];
               j -= incr;
            }
            a[j] = temp;
         }
         incr /= 2;
      }
   }

   public static void main (String[] args)
   {
      int[] a = new int [10];
      for (int i=0; i < a.length; i++)
         a[i] = (int) (Math.random() * 100);

      System.out.print ("Unsorted: ");
      for (int i=0; i < a.length; i++)
         System.out.print (a[i] + " ");
      System.out.println (" ");

      sort (a);

      System.out.print ("Sorted:   ");
      for (int i=0; i < a.length; i++)
         System.out.print (a[i] + " ");
      System.out.println (" ");
   }
}


Java
Arrays (continued)

public class LotteryDrawing
{
   public static int[] drawing (int high, int number)
   {
      int numbers[] = new int [high];
      int result [] = new int [number];

      // fill in array with numbers 1 2 3 ... high
      for (int i=0; i < high; i++) numbers[i] = i+1;

      for (int i=0; i < number; i++)
      {
         int j = (int) (Math.random() * (high - i));
         result[i] = numbers[j];
         numbers[j] = numbers[high - 1 - i];
      }
      return result;
   }

   public static void main(String[] args)
   {
      int   high = 50;
      int number = 5;

      int[] a = drawing (high, number);

      for (int i=0; i < a.length; i++)
         System.out.println (a[i]);
   }
}


Java
The String Class

   String empty = "";
   String hello = "Hello";

   // concatenation
   String hello2 = hello + " world";

   // substrings
   String world = hello2.substring(6, 5);

   // characters:
   char w = world.charAt(0);

   // cannot change individual characters 
   // compile time error
   world[0] = 'W'; 

   // but can replace whole string:
   world    = "World"; 

   // for comparing two strings:
   if (world.equals(hello2))

   // DO NOT USE THE == operators
   // it will compare the addresses of the objects
   if ( world == hello2 )


Java
The StringBuffer Class

Example:

class ReverseString {
  public static String reverseIt(String source) {
                int i, len = source.length();
                StringBuffer dest = new StringBuffer(len);

                for (i = (len - 1); i >= 0; i--) {
                    dest.append(source.charAt(i));
                }
                return dest.toString();
  }
}

public class Reverse
{
 static public void main (String[] args)
  {
    String s = "Reverse Me";
    String r = ReverseString.reverseIt (s);

    System.out.println ("  String: " + s);
    System.out.println ("Reversed: " + r);
  }
}


Java
Other Data Structures

Other data structures are available from the java.util package:


Object Oriented Programming
Procedural vs. Object-Oriented

Procedural programming


Object Oriented Programming
Procedural vs. Object-Oriented

Object-oriented programming


Object Oriented Programming

One definition of an object-oriented langage is that the langauge provides support for the following


OOP
Some Definitions


OOP
Class Relationships

There are three common relationships among classes:


Java
Support for OOP?


Java OOP
Classes

What goes in a class:

Within each section, we can have:


Java OOP
The Life Cycle of an Object

When implementing classes, you implement:


Java OOP
Controlling Access to Class Members

Java provides 5 levels of access control for class members - both data and methods:


Java OOP
Controlling Access to Class Members

When to use:


Java OOP
Controlling Access to Class Members


Java OOP
Class Declarations

When we define a class, we specify

In general, a class declaration in Java looks like:

[modifiers]  class ClassName [extends SuperClass] 
                             [implements InterfaceNames]
{
}

Modifiers:


Java OOP
Class Data Member Declarations

When we define class data members, we specify

In general, a class data member in Java looks like:

accessSpecifier] [static] [final] [volatile] type variableName

Examples:

   static final double PI = 3.14159; // constant
   private double width;             // private instance data


Java OOP
Class Member Method Declarations

When we define class methods, we specify


Java OOP
Class Member Method Declarations

In general, a class data member in Java looks like:

[accessSpecifier] [static] [abstract] [final] [native] [synchronized] 
                  returnType methodName ([paramlist]) 
                  [throws exceptionsList]

Examples:

   public static int getX() { return x; }

   public double area() { return width * height; }

   public abstract void draw ();   

   public void OpenFile () throws IOException 
   { 
      ... 
   }

   public void sort (int[] a)
   { 
      ... 
   }


Java OOP
Abstract Classes

  
Example: a hierarchy of shapes with methods for:


Java OOP
Abstract Class Example

abstract class Shape
{
  public Shape (String name) { shName = name; }
  public abstract double area();
  public abstract double circumference();
  public String getName () { return shName; }
  private String shName;
}

class Circle extends Shape
{
  public Circle ()         { super("Circle"); this.r = 1.0; }
  public Circle (double r) { super("Circle"); this.r = r;  }
  public double area()          { return java.lang.Math.PI * r * r; }
  public double circumference() { return 2 * java.lang.Math.PI * r; }
  public double getRadius() { return r; }
  protected double r;
}

class Rectangle extends Shape
{
  public Rectangle ()                   
  { super("Rectangle");  this.w = 1.0; this.h = 1.0; }
  public Rectangle  (double w, double h) 
  { super ("Rectangle"); this.w = w; this.h = h; }
  public double area () { return w*h; }
  public double circumference() { return 2*(w + h); } 
  public double getWidth()  { return w; }
  public double getHeight() { return h; }
  private double w;
  private double h;
}

public class shapes
{
  public static void main(String args[])
  {
   Shape[] shapes = new Shape[3];

   shapes[0] = new Circle (2.0);
   shapes[1] = new Rectangle();
   shapes[2] = new Rectangle(4.0, 2.0);

   double total_area = 0;

   for (int i=0; i < shapes.length; i++)
     {
        total_area += shapes[i].area();
        System.out.println (shapes[i].getName() + ": area= " + 
                            shapes[i].area()    + ", circumference= " +
                            shapes[i].circumference());
     }
   System.out.println ("Total area = " + total_area);
  }
}


Java OOP
Compiling Java Programs


Java OOP
Interfaces

public interface Drawable 
{
 public void setColor (Color t);
 public void setPosition (double x, double y);
 public void draw        (DrawWindow dw);
}


Java OOP
Using Interfaces

Example:

public class DrawableRectangle extends Rectangle
                               implements Drawable
{
 public DrawableRectangle ( double w, double h) { super(w,h); }

  public void setColor (Color t) { this.c = t; }
  public void setPosition (double x, double y) { this.x=x; this.y = y; }
  public void draw        (DrawWindow dw)
  { dw.drawRect (x, y, w, g, c); }

  private Color c;
  private double x, y;
}


Java OOP
Class Design Hints


Java Applets


Java Applets
Viewing Applets

To create and view an applet:


Java Applets
HTML

Required HTML tags:


Java Applets
HTML

Optional attributes of the APPLET tag:

To pass parameters to applets we use the PARAM tag which has two attributes:

<APPLET CODE="SampleForm.class" WIDTH=150 HEIGHT=25>
<PARAM NAME="Name" VALUE="Joe">
<PARAM NAME="Address" VALUE="1234 Main">
<PARAM NAME="Amount" VALUE="50.00">
</APPLET>

Java Applets
The Lifecycle of an Applet

There are four methods in the Applet class that give you the framework on which to build any serious applet:


Java Applets
Restrictions

Because applets are designed to be loaded from a remote site and then executed locally, there are a number of security restrictions for applets.

In general, applets are not allowed to do things like:

Different Web browsers may relax some of these restrictions. Netscape provides less security when loading an applet from a local file than it does for loading an applet via a URL, for example.

In addition, the appletviewer does not impose most of the above restrictions.


Java Applets
Passing Parameters to Applets

Parameters may be passed to an applet from the HTML file in which the applet has been embedded.

Here is an example:

<HTML>
<HEAD>
<TITLE> An Applet with Parameters </TITLE>
</HEAD>
<BODY>
<APPLET CODE="SampleForm.class" WIDTH=150 HEIGHT=25>
<PARAM NAME="Name" VALUE="Joe">
<PARAM NAME="Address" VALUE="1234 Main">
<PARAM NAME="Amount" VALUE="50.00">
</APPLET>
</BODY>
</HTML>

These values are usually retrieved in the applet's init() method by calling the applet's getParameter() method:

   String name = getParameter("name");
Note that the parameters in the getParameter method and the PARAM tag must match exactly.


Java Applets
Dialog Boxes


Java Applets
Dialog Boxes Example

class CalculatorApplet extends Applet
{
   public void init()
   {
      add(new Button ("Calculator");
   }

   public boolean action (Event evt, Object arg) 
   {
      if (arg.equals ("Calculator"))
      {
         if (calc.isShowing()) calc.hide(); 
         else                  calc.show();
      }
      else
         super.action (evt, arg);
      return true;
   }
   Frame calc = new Calculator();
}


Java AWT

The Abstract Windowing Toolkit is provided by the java.awt package.

The AWT is divided into three categories:


Java AWT
Graphics

The AWT provides a number of classes for graphics:


Java AWT
Interface Components

The AWT provides a number of GUI components:


Java AWT
Layout Managers


Java AWT
Related Classes

The AWT provides a class for grouping checkboxes:

The AWT provides classes for menus:


Java AWT
Some Notes...


Java AWT
Events


Java AWT
Events Example

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

public class GUI1 extends Applet
{
  public void init()
  {
    b1 = new Button ("Press me");
    field1 = new TextField ("Welcome!", 20);

    setLayout (new GridLayout (2, 1));
    add (b1);
    add (field1);
  }
  
  public boolean action (Event event, Object arg)
  {
    if (event.target == b1) {
      field1.setText ("Thank you!!!" );
      return true;
    }
    else {
      return super.action (event,arg);
    }
  }

  private Button     b1;
  private TextField  field1;

}



Bowden Wise
Mon Apr 7 11:40:34 EDT 1997