lectures

Document Sample
lectures Powered By Docstoc
					Imperative programming

Von Neumann‟s computer model:

            computer
               =
     memory    +     processor


    to store             to execute
    values              instructions
Instructions

Instruction:
 direction to modify memory
    instructions are stored in memory, too,
    but don‟t modify themselves

Program:
 long sequence of instructions,
 which are executed one by one
 by the processor
Programming languages

Programming
 language:
 notation for
 programs



since 1945:
 3000 different languages published
History of programming
languages

    1945   Mach.lang.
    1950   Assembler
    1955    Fortran
    1960      Algol         Cobol        Lisp
    1965     Basic
    1970     Pascal         Databases   Prolog
    1975    Simula          (SCI251)
    1980        C
                                         Functional
    1985                    SQL         Programming
    1990     C++
    1995     Java                       Haskell
    2000                 Imperative
                        Programming
Memory capacity

1965s:   8 kB RAM     punched cards
1970s:   16 kB RAM    tape
1980s:   64 kB RAM    floppy
1985s:   640 kB RAM
1990s:   4 MB RAM     harddisk
1995s:   16 MB RAM    CD
2000s:   128 MB RAM   DVD
Problems associated
with programming

in olden times:
 how can memory be utilized efficiently?

now:
 how can memory be understood in full?
Order out of chaos

 person      county     employee      lecturer

  club       province   department     chair

 league       state      division    department

federation   country     company       faculty

  union       union      holding     university
Memory structure

named memory
 location             variable
group of variables
 belonging together   object

group of objects
                      object
 belonging together
Program structure

direction to change
 memory                  statement
group of instructions
 belonging together       method

group of methods
                           class
 belonging together
Programming paradigms

 Imperative     Assembler   Declarative

     Fortran      Basic        Functional    Lisp

   Procedural     Algol           Excel     Haskell

      Pascal       C

   Object-                     Logic
   oriented      Simula

       C++        Java           Prolog
Java      why?

Imperative and procedural
  and object oriented
Fun to learn
Extensive libraries
  also for window programs
 Cool : programming for the Internet
Machine language

Instructions are specific
 for a target processor
Translating 1/4: Assembler

An assembler translates machine-specific
 source code to object code,
 which is executed subsequently

          assembler




          assembler
Higher programming
language

Single program can be translated for
 many different processors




Source code also intelligible for
 human writer/reader
Translating 2/4: Compiler

A compiler translates source code to
 machine specific object code,
 which is executed subsequently

           compiler




           compiler
Translating 3/4: Interpreter

A processor sepcific interpreter
 reads source code and executes it


                              interpreter




                              interpreter
Translating 4/4:
Compiler+Interpreter

A universal compiler translates source
 code to byte code, which can easily be
 interpreted

                              interpreter

           compiler

                              interpreter
Programming cycle
 Model


 Specify


 Implement
              Edit

             Compile

              Run
Java program types

Java Applet
 program “lives” on a WWW-page

Java Application
 program has window of its own
                 JavaScript is not Java!
Javascript
 program assists in web page construction
Java        versus        JavaScript

 Imperative               Imperative
 Can be Internet based    Internet based
 Object oriented          “Only” procedural
 Compiled byte code       Interpreted directly
 In fixed rectangle       Influences browser
 Extensive method         Fixed number built-in
  libraries                 methods
 For programmers          For web designers
Source code structure

 Statements to
  modify memory

Statements are
 grouped in
 methods
Methods are
 grouped in
 classes
Statement forms

 Assignment -statement:
  modify memory
 Call of another method:
  first execute statements of that method,
  then continue were you were

     which might be calls to yet other methods
       so “where am I” tracking might grow complicated!
Object orientation

Object:
 part of memory that belongs together

Object oriented programming:
 methods involves (mostly) an object
 mentioned at the call
Example Java program

              import java.awt.Graphics;
              import java.applet.Applet;

one class     public class Hello extends Applet
              {
...with one     public void paint (Graphics g)
  method        {
                   g.drawString(“Hello!”, 20, 20);
...with one     }
statement     }

                         braces delimit
                       class and method
Class and method header

                 import java.awt.Graphics;
   public:
                 import java.applet.Applet;
may be used
from outside
                 public class Hello extends Applet
                 {
                   public void paint (Graphics g)
                   {
     name:            g.drawString(“Hello!”, 20, 20);
 determined by     }
  programmer     }
Statement: method call

                       import java.awt.Graphics;
                       import java.applet.Applet;

                       public class Hello extends Applet
                       {
statement:               public void paint (Graphics g)
method call              {
                            g.drawString(“Hello!”, 20, 20);
                         }
                       }

                           always                    other
     object involved        a dot
                                    method name
                                                     details
Communication with browser
    class is
 extension of
 library class        import java.awt.Graphics;
    Applet            import java.applet.Applet;

  browser calls       public class Hello extends Applet
  paint method,       {
   providing a          public void paint (Graphics g)
Graphics object ...     {
                           g.drawString(“Hello!”, 20, 20);
                        }
 ... which comes      }
     in useful!
 Class libraries

                    import java.awt    . Graphics;
                    import java.applet . Applet;
library classes
may be used...      public class Hello extends Applet
                    {
                      public void paint (Graphics g)
    if they are       {
     imported,           g.drawString(“Hello!”, 20, 20);
                      }
 mentioning their   }
     package
Method header and call

           import java.awt.Graphics;
           import java.applet.Applet;

           public class Hello extends Applet
           {
 method
             public void paint (Graphics g)
 header
             {
 method
                g.drawString(“Hello!”, 20, 20);
   call
             }
           }

            we get                 we provide
          a parameter           three parameters
WWW-page with Applet

            <HTML>
  special   Here is a <B>simple</B>
 HTML-tag   applet: <BR>
<APPLET>
            <APPLET code = Hello.class
                    width = 100
                    height= 50 >
            </APPLET>
            </HTML>

                       byte code which results
                      from compiling Hello.java
Embedding an Applet
 import java.awt.Graphics;
 import java.applet.Applet;

 public class Hello extends Applet

                                        compiler
 {
   public void paint (Graphics g)
   {
      g.drawString(“Hello!”, 20, 20);
   }
 }


Hello.java                                         Hello.class


  <HTML>
  Here is a <B>simple</B>
  applet: <BR>

  <APPLET code = Hello.class
          width = 100
          height= 50 >
  </APPLET>
  </HTML>


Hello.html
  SDK:
  Software Development Kit

  Sun‟s Java SDK

  compiler:
   javac

  bytecode-
 interpreter:
appletviewer
Integrated Development
Environment: JCreator
JCreator: New File
JCreator: syntax
highlighting editor
JCreator: Error messages
JCreator: Run applet
JCreator: set options
Run applet in Explorer
JCreator: JDK help
Summary

Imperative programming:
 program consists of statements,
 modifying memory

Object oriented programming:
 variables belonging together
 are grouped in objects
Summary

 Statement :
  direction to modify memory
 Method :
  named group of statements
 Class :
  named group of methods
Summary

Translating higher language (source code)
to machine language (object code)

Assembler
Interpreter
Compiler
Compiler - bytecode - interpreter
Summary
import java.awt.Graphics;
import java.applet.Applet;

public class Hallo extends Applet

                                       compiler
{
  public void paint (Graphics g)
  {
     g.drawString(“Hallo!”, 20, 20);
  }
}


Hello.java                                        Hello.class


 <HTML>
 Hier is een <B>simpel</B>
 applet: <BR>

 <APPLET code = Hallo.class
         width = 100
         height= 50 >
 </APPLET>
 </HTML>


Hello.html
Summary

            import java.awt.Graphics;
            import java.applet.Applet;

            public class Hallo extends Applet
            {
 method-
              public void paint (Graphics g)
 header
              {
 method-
                 g.drawString(“Hallo!”, 20, 20);
   call
              }
            }

             we get               we provide
           a parameter         three parameters
Class and method header

                 import java.awt.Graphics;
                 import java.applet.Applet;
 method from
                 public class Hello extends Applet
class Graphics
                 {
                   public void paint (Graphics g)
                   {
                      g.drawString(“Hello!”, 20, 20);
                         g.drawLine(10,20,50,60);
                         g.fillRect (70,30,20,20);
other methods        }
from Graphics    }
Methods from Graphics
                      x
drawString               hello
drawLine      y

drawRect
drawOval
fillRect
fillOval
setColor
              determines color of
              subsequent drawing
                                         method from
                                          class of
Classes and objects                       object g


Class describes                     ... (Graphics g)
 object capability     { g.drawLine(10,20,50,60);
                         g.fillRect (70,30,20,20);

Object can do and         g.setColor( Color.blue );
 remember things           g.fillRect (30,50,20,20);


Class also provides       g.setColor( Color.blue );
                       }
 constants
Colors


Color .   green             red
                  yellow
                    white
             cyan      magenta

                    blue
                                  black
Drawing
g.setColor( Color.white );
g.fillRect(0,0,200,100);
g.setColor( Color.black );
g.fillRect(10,0,10,100);
g.fillRect(50,0,10,100);
g.fillRect(90,0,10,100);
g.fillRect(0,40,200,10);
g.fillRect(0,70,200,10);
g.setColor( Color.blue );
g.fillRect(0,50,10,20);
g.setColor( Color.red );     Composition with blue and red
g.fillRect(100,0,100,40);    (freely after Piet Mondrian)
Modifying the drawing
g.setColor( Color.white );   Correction of bar width
g.fillRect(0,0,200,100);
g.setColor( Color.black );
g.fillRect(10,0,10,100);     Correction of picture
g.fillRect(50,0,10,100);      height
g.fillRect(90,0,10,100);
g.fillRect(0,40,200,10);     Correction of picture
g.fillRect(0,70,200,10);
g.setColor( Color.blue );
                              width
g.fillRect(0,50,10,20);
g.setColor( Color.red );                 lots of work ...
g.fillRect(100,0,100,40);
Variables                           declaration:
                                   announcement
                                     of variables
int bar, width, height;            and their type

bar = 10;                           assignment
width = 200;                        statements:
height = 100;                       variables get
g.fillRect(10, 0,,bar, 100);
               0 10, height);          a value
                  bar, height);
g.fillRect(50, 0, 10, 100);
                  bar, height);
g.fillRect(90, 0, 10, 100);
                  width, bar);
g.fillRect(0, 40, 200, 10);
                  width, bar);
g.fillRect(0, 70, 200, 10);       use of variables
Statement forms

Method call

     object . method ( parameters ) ;



Assignment statement

     variable = value ;

                  becomes
Declarations

Declaration structure
      type variabele , variabele ;

                           zero or more

      int: whole numbers
      double: floating point numbers
      class name : object variables
Variables
int x1, x2, x3, y1, y2;                x1 x2 x3
x1=10; x2=50; x3=90;
y1=40; y2=70;
g.fillRect(x1, 0 ,bar, height);   y1
g.fillRect(x2, 0, bar, height);
g.fillRect(x3, 0, bar, height);   y2
g.fillRect(0, y1, width, bar);
g.fillRect(0, y2, width, bar);
g.setColor( Color.blue);
g.fillRect(0, y1+bar,
           x1, y2-y1-bar );
Expressions

Expression:
 program phrase having a value
Use of expressions:
   Right hand side of assignment statement
      x3 = x2+40 ;

   Method parameter

      g.fillRect(0, y1+bar, x1, y2-(y1+bar) ) ;
Expression structure

constant             5


variable             hoogte


... operator ...     x+y +1


( ... )              x - (y + 1)


   expressie
  expression expression
Operators

+   addition
-   subtraction         division of int values:
*   multiplication       result is truncated!

/   division
% remainder after division

           14 / 3 == 4           14 == 4*3 + 2
           14 % 3 == 2
Operator precedence

Multiplication    and division
 precedes addition and subtraction
                      1 + 2 * 3 == 7

Equal precedence:
 left to right        10 - 5 - 2 == 3

Want it otherwise?
 place parentheses!   (1+2) * 3 == 9
Program                                     with comments
import java.awt.Graphics;
 asd
import java.awt.Color;
import java.applet.Applet;
                                                             // black bars
                                                             g.setColor(Color.black);
/* This applet displays a Mondrian like                      g.fillRect(x1, 0, balk, hoogte);
                                                             g.fillRect(x2, 0, balk, hoogte);
   "composition with red and blue”
                                                             g.fillRect(x3, 0, balk, hoogte);
*/                                                           g.fillRect(0, y1, breedte, balk);
                                                             g.fillRect(0, y2, breedte, balk);
public class Mondri extends Applet
{ public void paint(Graphics g)                              // colored fields
  { int breedte, hoogte, balk, x1, x2, x3, y1, y2;           g.setColor(Color.blue);
                                                             g.fillRect(0, y1+balk, x1, y2-(y1+balk) );
     // position of lines
      breedte = 200; x1 = 10; x2 = 50; x3 = 90;              g.setColor(Color.red);
      hoogte = 100; y1 = 40; y2 = 70;                        g.fillRect(x3+balk, 0,
      balk = 10;                                                        breedte-(x3+balk), y1);
                                                         }
     // background                                   }
     g.setColor(Color.white);
     g.fillRect(0, 0, breedte, hoogte);
Comments

Intended for human reader
 ignored by compiler

Two notations:
   from /* to */
   from // to line end
Drawing
public void paint(Graphics g)
{ g.drawRect(20,60,40,40);
   g.drawLine(20,60,40,40);
   g.drawLine(40,40,60,60);
    g.drawRect(70,60,40,40);
    g.drawLine(70,60,90,40);
    g.drawLine(90,40,110,60);
    g.drawRect(120,40,60,60);
                                 big mess of
    g.drawLine(120,40,150,10);
                                 coordinates!
    g.drawLine(150,10,180,40);
}
New methods
                  private void drawHouse(…)
Method:
                  { … . drawRect (…);
 named group of      … . drawLine (…);
 statements          … . drawLine (…);
                  }

                  public void paint(Graphics g)
    method call   { … . drawHouse (…);
     executes       … . drawHouse (…);
     its body       … . drawhouse (…);
                  }
Parameters
             drawHouse (Graphics gr, …)
private void drawHouse(…)
    gr
{ … . drawRect (…);                          declaration
   gr
   … . drawLine (…);                           of extra
   … . drawLine (…);
   gr                                         parameter
}

public void paint(Graphics g)      which Graphics object
{ … . drawHouse (g, …);
                   (…);                 is involved?
  … . drawHouse (g, …);
                   (…);
  … . drawHouse (g, …);
                   (…);
}                                   pass extra
                                    parameter
    The object this
public class Houses extends Applet
{ private void drawHouse (Graphics gr, …)
   { gr . drawRect (…);
       gr . drawLine (…);
       gr . drawLine (…);
   }

    public void paint(Graphics g)       which     ??? object
                                        which Houses object
    { … . drawHouse (g,(g, …);
       this . drawHouse …);                 is involved?
      this . drawHouse …);
      … . drawHouse (g,(g, …);
      … . drawHouse (g,(g, …);
      this . drawHouse …);
    }                                this: the object
                                     already involved
}                                       with paint
More parameters




                                            draw three
public void paint(Graphics g)
                                         slightly different
{ this . drawHouse (g, …);20,100, 40);
                                              houses
  this . drawHouse (g, …);
                         70,100, 40);
  this . drawHouse (g, …);
                        120,100, 60);
}
                                              even more
                                             parameters!
Parameters
                                     int x, int y, int w)
private void drawHouse (Graphics gr, … )x, int y, int w)
                                     int
{ int tx, ty;
{
             w;
   tx = x + w/2;
              – w/2;
   ty = y - w - w/2;
                 (x, y-w, w, w);
   gr . drawRect (…);
                 (x, y-w, w, w);
                 (x, y-w, tx, ty);
   gr . drawLine (…);
   gr . drawLine (…);ty, x+w, y-w);
                 (…);
   gr . drawLine (tx,
}
}                                                 (tx,ty)

                                   (x, y-w)           (x+w,
                                                       y-w)

                                      (x,y)
                                                w
Flexibility

The more parameters,
 the more flexible the method
private void drawHouse(Graphics gr, int x, int y, int w,
   int h, int roofh, Color c, Color roofc, … ) {


                                                      roofh
               and the more
            cumbersome to call...                     h
                                      (x,y)
                                                w
Flexibility




Many parameters:         Few parameters:
 hard to program now     easy to prgram now
 easy to extend later    might be hard to
                           extend later
Communication among
methods

 Parameters :
  caller passes value to method
                                     like a
 Method result :                 mathematical
  methods returns                   function
  value to caller
Methods with result

    result type


       private int square (int x)
       {
          return x*x ;
       }



                           value of result
                    in special return statement
Methods with result
                               first, some
                               statements


    private int succesorsThirdPower (int x)
    { int s;
       s = x+1;
       return s*s*s ;
    }
Method calling
                                         without
                                          result
Call of a void-method
 is a statement
       g.drawString(“hello”, 10, 10) ;

Call of a method with a result
 is an expression

       x = this.square (5) ;
         … this.square (5) + 1 …
Summary of constructs

Statements               Expressions
 Assignment              Constant          5
   x=5;                   Variable          x
 Call of void method     Operator expr. x+1
   this.drawHouse (…);    Expr. in parentheses
 Return statement                        (x+1)

   return x*x;            Call of method
                           with a result
                                 this.square(5)
Summary chapter 2

 Statement :
  directions to change memory
 Method :
  named group of statements
 Class :
  named group of methods
Summary chapter 3+4

Calling methods
   in Graphics: drawLine, fillRect, setColor


Defining new methods
   e.g: drawHouse


Passing parameters to methods
   to make methods more flexible
Summary chapter 3+4

Variables
   to temporarily store values
   declaration states type, e.g. int, double


Expression
   calculation resulting in a value
   uses constants, variables, operators
Summary chapter 3+4

Statements                Expression
 Assignment               Constant          5
  x=5;                     Variable          x
 Calling a void method    Operator expr. x+1
  this.drawHouse (…);      Expression in parenth.
 Return statement                        (x+1)

  return x*x;              Calling a method with a
                            result
                                  this.square(5)
Methods and objects

        gr . drawString (“Hi”, 50, 50) ;


   Graphics object           method from
      involved              class Graphics


                                             static
       x = Math . sqrt(2.0) ;
                                             method

     no object              method from
      involved               class Math
Parameters

Parameters make a method more flexible:
 it can be used in various situations

Parameters make an applet more flexible:
  it can be used in various situations
                                     then what?
not the parameter of paint !
should always be a Graphics-object
Class extensions inherit
methods             allowed: method
                                               of Greeting
                                               and Applet
   public class Greeting extends Applet
   {
     public void paint(Graphics g)             like this one:
                person;
     { String person, greeting;

           person = this . .getParameter(“name”);
                             ???
                      this getParameter(“name”);
           greeting = “Hello ” + person + “!”;
           g.drawString(greeting, 50, 20 );
       }
   }                  yielding a text String
Passing parameters to
Applets

 <APPLET code=Greeting.class width=100 height=100>

   <PARAM name=name value=Jeroen>

 </APPLET>


        as specified          will be the result
        when calling           of the call to
       getParameter            getParameter
String

String object contains text
Ways to obtain a String object:
  constant                            “Hello”

  calling a method               this.getParameter
   yielding a String                      (“name”)

  calling an operator
   yielding a String              “Hello” + person

                not addition,
              but concatenation
Numbers versus texts

 int x;                      String s;
 x = 37;                     s = “37”;
 x = 12 + 5;                 s = “12” + “5”;
         17                             “125”

 x = Integer.parseInt(s);    s = “” + x ;

                                concatenation operator
  conversion method            converts second operand
                                      to a String
                                 whenever the first is
Applet with int parameters
public void paint (Graphics gr)
{
   String text1, text2; int length, width;

    text1 = this.getParameter(“length”);
    text2 = this.getParameter(“width”);
    length = Integer.parseInt(text1);
    width = Integer.parseInt(text2);
    gr.drawString(“perimeter: ” + 2*(length+width), 0, 0 );
}
Passing parameters to
an Applet

 <APPLET code=Rectang.class width=100 height=100>
   <PARAM name=length value=12>
   <PARAM name=width value=8>
 </APPLET>

 <APPLET code=Rectang.class width=100 height=100>
   <PARAM name=length value=7>
   <PARAM name=width value=3>
 </APPLET>
Primitive          versus Object
types                           types

 int i;               String s;
 double d;            Color c;
  i   5                s
  d   3.1415926        c


 i = 5;                s = “hello”;
 d = 3.1415926;        c = Color.blue;

                             object variables
                           contain references
How to obtain objects

String constants           “hello”

Constants in a class       Color.blue

Result of a method        this.getParameter(“a”);
Result of an operator      “total: ” + sum
Home made                  new Color(0,0,0)



                         constructor method
Constructor method

Call of a constructor-methode:
makes new object in memory
treats it immediately
returns the newly created object

              Color c;
              c=
       gr.setColor( new Color(0,0,0) );

                                calling a constructor
                                 is an expression
 Colors


Color(...)   (0,255,0)               (255,0,0)
                       (255,255,0)

                         (255,255,255)


                (0,255,255)      (255,0,255)



                      (0,0,255)
                                               (0,0,0)
Mixing colors

new   Color(255, 0, 0)
new   Color(255, 64, 0)
new   Color(255, 128, 0)
new   Color(255, 192, 0)
new Color(255, 255, 0)
Creating new objects

Color c;
 c = new Color(255,128,0);
Button b;
 b = new Button(“press here”);
ScrollBar s;            objects for interaction
 s = new ScrollBar(...);      with the user
                                            redefine in
Methods of Applet                         your program!


paint                are called
init               by the browser



getParameter
                    may be called
add            from within the program
repaint
Applet’s init and paint

init:
 called by the browser
 when the applet starts first
paint:
 called by the browser
 each time the applet needs painting

          just after init , but also
         when a window re-appears
Applet’s add and repaint

add:
 to add interaction objects
                              typically: from init


repaint:
 to force an extra paint
Example: color mixer
 ScrollBar             Button
Using add
 public class Mixer extends Applet
 { ScrollBar s;
                                     object-variable:
                                        is part of
   public void init( )
                                       this object
   {      ScrollBar s ;
          s = new ScrollBar(...);    and therefore
          this.add( s );             may be used in
   }                                 every method!
   public void paint(Graphics gr)
   {
          .... s . getValue() ....
   }
Reacting on user actions

Event: action of the user
   click button
   slide scrollbar
   enter text in textfield
   ...
Event listener: object that reacts upon that
adding an Event listener to
an interaction object
 public class Mixer extends Applet
 {
   Scrollbar s;

   public void init( )
   {
     s = new Scrollbar(...);
     this.add( s );
     s . addAdjustmentListener (...);
   }

                the object that will be notified
               when the user adjusts scrollbar s
Notification mechanism

                   promise that adjustmentValueChanged
                           will indeed be defined


public class ... implements AdjustmentListener
{
  public void adjustmentValueChanged ( AdjustmentEvent e )
  {
      // statements which will be executed
      // in response to user actions
  }
}
Which event listener to use?
public class Mixer extends Applet
                   implements AdjustmentListener
{ ScrollBar s;
                                      Mixer object is
  public void init( )                event listener of
  { s = new ScrollBar(...);         its own scrollbar!
      this.add( s );
      s . addAdjustmentListener ( this );
  }
  public void adjustmentValueChanged (AdjustmentEvent e)
  {
       // here you may use s and this
  }
Reacting on ScrollBar events
  public void init ( )
  { s = new ScrollBar(...);
     this . add( s );
     s . addAdjustmentListener (this);
  }
  public void adjustmentValueChanged (AdjustmentEvent e)
  { this . repaint( );
  }
  public void paint (Graphics gr)
  { int x; x = s . getValue( );
    gr . setColor( new Color(x, ..., ...) );
    gr . fillRect( 0, 0, 100, 100 );
  }
Interaction objects
with event listeners

ScrollBar s;
 s.addAdjustmentListener(this);
implements AdjustmentListener
public void adjustmentValueChanged (AdjustmentEvent e){...}

Button b;
 b.addActionListener(this);
implements ActionListener
public void actionPerformed (ActionEvent e){...}
Complete Color mixer
class Mixer: outline
 public class Mixer extends Applet
                   implements ActionListener,
                            AdjustmentListener
 { Scrollbar red, green, blue;
                                            object variables
   Button black;

     public void init ( ) {...}                  redefining
     public void paint (Graphics gr) {...}     Applet-methods

     public void adjustmentValueChanged (...) {...}
     public void actionPerformed (...) {...}
 }                                        fullfilling promises
                                         made by implements
Mixer’s method init
 public void init ( )
 { red = new Scrollbar(0,0,1,0,255);          creation of
   green = new Scrollbar(0,0,1,0,255);        interaction
   blue = new Scrollbar(0,0,1,0,255);           objects
   black = new Button(“Black”);
   this . add(red); this . add(green);      building the
   this . add(blue); this . add(black);    user interface
   red . addAdjustmentListener (this);
   green . addAdjustmentListener (this);     addition of
   blue . addAdjustmentListener (this);    event listeners
   black . addActionListener (this);
 }
Mixer’s method paint

 public void paint (Graphics gr)
 { int rv, gv, bv;                               local
                                              declarations
     rv = red   . getValue();
     gv = green . getValue();                     get
     bv = blue . getValue();                   scrollbar
                                               positions
     gr . drawString( rw+“ ”+gw+“ ”+bw );
     gr . setColor ( new Color(rv,bv,gv) );   draw colored
     gr . drawRect ( 20,60,260,220 );           rectangle
 }
Mixer’s Event-listenters
 public void adjustmentValueChanged
              (AdjustmentEvent e)              reation to
 { this . repaint( );                           ScrollBar
 }

 public void actionPerformed (ActionEvent e)   reaction to
 { red . setValue(0);                            Button
   green . setValue(0);
   blue . setValue(0);
   this . repaint( );
 }
Summary Declarations
                                          object variable
public class Mixer ...
{                                       permanently,
  Scrollbar red;                        assigned to in   init

    public void paint ( Graphics gr )        parameter
    {                                   for communication,
      int rv;                           assigned to at call

        rv = red . getValue( );
                                            local variable
    }
}                                        temporarily
                                         assigned to with an
                                         assignment
Summary AWT-classes

 Applet               Graphics        ScrollBar
     init               drawString      getValue
     paint              fillRect        setValue
     getParameter       setColor
     add              Color           Button
     repaint
                       String
 ActionListener
   actionPerformed
 AdjustmentListener
   adjustmentValueChanged
Summary chapter 4

Objects
   existing: parameter or constant
   result of method or operator
   home-made using new
Methods
   “involve” an object
   except: static methods
Summary chapter 5

String
   constants: “hello”
   operator + concatenates string-objects
   conversion from and to int:
     s = n + “”;
     n = Integer.parseInt(s);
Color
   constants: Color.blue
   home made: new Color(r,g,b)
Summary chapter 5

Parameters for the entire Applet:
    class Greeting extends Applet
    { void paint(Graphics gr)
       { person = this.getParameter(“name”);
       }
    }


    <APPLET code=Greeting.class width=100 height=100>
      <PARAM name= name value=Jeroen>
    </APPLET>
Summary chapter 6

Applet-methods are inherited by
 extension classes
   Intended to call
     getParameter
     repaint
   Intended to re-define
     init                for creation of
     paint             interaction objects
Class challange

How to make interaction components
 and how to react on their use?
               now!
           approx 5 min.

Write a program showing a Scrollbar,
 and beneath it a numerical representation
 of its value
  peeking at ch. 6 is allowed,
  but try first without that!
Interaction
 public class Interact extends Applet
                    implements AdjustmenListener
 {     Scrollbar s;
      public void init()
      { s = new Scrollbar(0,0,1,0,100);
          this . add(s); s.addAdjustmentListener(this);
      }
      public void paint(Graphics gr)
      { gr.drawString( s.getValue()+””, 50,50);
      }
      public void adjustmentValueChanged(...)
      { this . repaint();
      }
 }
Repeating statements
public void paint (Graphics gr)
{ int x;                                  while the
   x = 1;                                condition
    while ( x<1000 )                       holds...
      x = 2*x;
                                         the body is
    gr . drawString( “” + x, 10, 10);   executed over
}                                         and over



           X    1024
                 128
                 256
                 512
                  64
                  32
                  16
                   1
                   4
                   2
                   8
Repeating multiple
statements
     private static int twoLog (int n)
     {
         int x, t;
         x=1; t=0;                     counter counts
                        n
         while ( x<1000 )               the number
         { x = 2*x;                     of doublings
              t = t+1;
         }                           braces pack two
         return t;                   statements into
     }                               a compound one
Repetition with a counter

     public void paint (Graphics gr) counter controls
     {                                 number of
       int t;                           iterations
       t=0;
       while ( t<10 )
       { gr.drawString( “:-)”, 0, 20*t );
            t = t+1;
       }
     }
                                      and comes in
                                          useful
Class challenge

Write a method power
 having two parameters
   base       (real number)
   exponent   (natural number)
 calculating

         baseexponent
Power method
    private static double power (double x, int n)
    {
         int t; double result;
         result = 1; t = 0;
         while ( t<n )
         { result = result * x ;
             t = t+1 ;
         }
         return result;
    }
Comparison operators

<    less than
<=   less than or equal
>    bigger than
>=   bigger than or equal
==   equal to
                     x=5     x becomes 5 !
!=   not equal to x==5      is x equal to 5 ?
Expressions

Expression with numeric value
    2 * (length + width)       primitive type int


Expression with text value
     “Hello ” + person         object- type String


Expression with truth value
    counter < exponent         primitive type boolean
Boolean expressions

Comparing values
    x <= y

Combining other Boolean
 expressions using logic
 operators                            George Boole
   &&       and   x<0 && y>0          (1815-1864)

   ||       or
  !         not   ! (x==0 && y==0)   x!=0 || y!=0
Constants

Constants with numeric value
  2      -5     137

Constants with text value
  “Hello”        “@#$%”   “123”   “”   “true”

Constants with truth value
  true        false
Using Boolean expressions

As condition of a while statement
   while (x<10) ...

As right hand side of an assignment
   boolean b;
   b = x<10 ;

As method result
   return x<10 ;
Class challenge

Write a method divisible , which
 determines whether x is divisible by d

  private static boolean divisible (int x, int d)
  {
        return x%d == 0 ;                     truth value
                                              as a result
  }
Class challenge

Write a method smallestDivisor , which
 determines the smallest divisor of x
  private static int smallestDivisor (int x)   try them all,
  {    int d;                                  one at a time
       d = 2;
      while ( ! divisible(x,d) )
        d = d+1;
      return d ;
  }
Changing variables
            x = x*2;

new value    becomes     old value


Shorthand notations:                  is multiplied by


     x = x*2;          x *= 2 ;
                                     is incremented with

     x = x+5;          x += 5 ;             is incremented


     x = x+1;          x += 1 ;      x ++ ;
Repetition with a counter

     int t ;
     t = 0;

      for
      while t<x
     for ( ( t=0 ) ; t<x ; t++ )
     {    // do something
          // useful with t
          t ++ ;
     }
for-statement
                     condition to
    initialisation                   step to next
                      continue


          int t ;
          for ( t=0 ; t<x ; t++ )
               gr.drawString( “#”, 0, t*10 );


          for ( t=1 ; t<=x ; t++ )

          for ( t=x ; t>=0 ; t -- )

          for ( t=2 ; !divisible(x,t) ; t++ )
Repeated repetition

Body of a for-statement is a statement
  which may be a for-statement itself!
                                            ++++++++++
int x, y;                                   ++++++++++
                                            ++++++++++
for (y=0; y<10; y++)                        ++++++++++
    for (x=0; x<10; x++)
                  y                         ++++++++++
                                            ++++++++++
        gr.drawString( “+”, 10*x, 10*y );   ++++++++++
                                            ++++++++++
                                            ++++++++++
                                            ++++++++++
Extreme cases

Zero repetitions
   for (y=0; y<0; y++)
      gr.drawString(“hi”, 10, 10);

Infinitely many repetitions
   while (true)
     audio.play( );
   gr.drawString(“hi”, 10, 10);      this statment
                                     will never be
                                       executed!
Unintensional infinity

  x=1;
  counter = 0;                forgot the
  while (counter<10)           braces...
  {    x = x*2;
       counter = counter+1;
  }
Compiler messages

Error messages
   variabele not declared
   missing semicolon
                                   this warning is
   ...
                                    theoretically
Warnings                            impossible!
   unreachable code
   statement has no effect
   while-statement doesn‟t terminate
The Halting-problem
is unsolvable
        Not so!
      This method      boolean stops (String filename)
       solves it:      { ....
                       }


                    void clever (String filename)
        Ha! What { while ( stops(filename) )
        about this?         x++;
                    }

         what is the      stops( “Clever.java” )     ?
          value of:
The Halting-problem
is unsolvable     stops( “Clever.java” )

                               void clever (String filename)
Two possibilities:             { while ( stopt(filename) )
                                       x++;
“Clever” does stop            }
   ...so stops returns true
   ...so clever hangs!                          contradiction!

“Clever” doesn‟t stop
   ...so stops returns false
   ...so clever stops immediately!


  thus, stops is impossible to write
Other Halting -like
problems

Will a statement be executed?
Is a program a virus?

but what about existing virus scanners?
 either too strict: false alarms     irritating

 or too generous: some viruses passed
                                        dangerous
Example: interst rates

                    TextField -objecten
                    for user interaction


                     TextField-objects
                        possess an
                      ActionListener
Outline of class Interest
 public class Interest extends Applet
                       implements ActionListener
 { TextField startT, renteT;
                                            object-variabels
     public void init ( ) {...}
     public void paint (Graphics gr) { ... }     re-defining
                                               Applet-methods
     public void actionPerformed (...)
     { this.repaint();
     }
 }
                                               fulfilling
                                          implements promise
Interest ’s method init

 public void init ( )                        creation of
 { startT = new TextField(“100”, 8 );        interaction
   rateT = new TextField(“5”, 4 );          components
     this . add(startT);                    setup of
     this . add(rateT);                   user interface

     startT . addActionListener (this);     addition of
     rateT . addActionListener (this);    event listeners
 }
Interest ’s method paint
public void paint (Graphics g)
{
   int start, rate, year; double capital;
    start = Integer.parseInt( startT.getText() );
    rate = Integer.parseInt( rate.getText() );
    capital = start;
    for (year=0; year<=10; year++)
    {    gr.drawString( “year:”+year + “amount:”+captial, ... );
         captial *= (1 + 0.01*rate) ;
    }
}
Class challenge

Write a method root , calculating the
 square root of a non-negative double
Without using Math.sqrt !

Use Newton approximation:
 when y approximates sqrt(x),
 then the average of y and x/y
 is a better approximation
Sqrt method
private static double sqrt (double x)
{    double y;                            does it stop?
     y = 1;
                                         mathematician:
         while ( y*y != x )              no, equality hold
             y = (y + x/y) / 2 ;         only in limiting case
         return y;                       programmer:
}                                        yes, precision is
                                         limited
safer:                                   computer scientist:
                                         no, roundof errors
while ( Math.abs (y*y - x) <0.000001 )
                                         prohibit reaching a
                                         stable state
Structure of repetition

Initialisation
  captial=start;               y=1;           total=0;

Repeated improvement
  captial*=(1+0.01*rate);      y=(y+x/y)/2;   total+=x;
Use of result
   gr . drawString (“”+captial);

   return y;

   sb . setValue ( total );
DrawString or return?
                                   useful for
gr.drawString (x, ...)        “complicated” layout
 result immediately visible

                        more flexible
                          useful for
                     for “simple” results
return x;
 result is returned to caller,
 who can decide what to do with it
Program constructions
                  to do                 to calculate
Statements                Expressions
 Assignment               Constant
 Call void-methode        Variable
 return-statement         Call methode
 while- statement         Expression with operators
 for- statement           Expression with parenth.
 { ... } - grouping       new-expression
Program constructions
                states type            set of possible values
                of variables             of an expression
Declaration                    Type
 Local variable                Primitive type
  for temporary use               int
 Object-variable                 double
  permanent part of object        boolean
 Parameter                     Object-type
  for passing values to           Color, String etc.
  methods
                                  TextField, Button etc.
                                  Applet, Hallo, etc.
Summary ch.7

while-statement: repeating statements


   while (x<1000)         while condition is valid
     x = 2*x;
                           body is repeatedly
                               executed
Summary ch.7

for-statement: repetition with a counter

        int t ;
        t = 0;

        for (    t<x
        while ( t=0 ) ; t<x ; t++ )
       {     // do something
            // useful with t
             t ++ ;
       }
Summary program
constructions
               can be done                can be calculated
Statements                   Expressies
 Assignment                  Constant
 Call void-method            Variable
 return-statement            Call method
 while-statement             Expression with operators
 for-statement               Expression with parenth.
 { ... } - grouping          new-expression
Summary program
constructions
                indicates              set of possible values
               variable type                of a variable
Declaration                    Type
 Local variable                Primitive type
  for temporary use               int
 Object variable                 double
  permanently part of             boolean
  the object
                                Object type
 Parameter                       Color, String etc.
  to pass values to a
  method                          TextField, Button etc.
                                  Applet, Hello, etc.
Executing statements
conditionally
if (temperature<0)
    gr.drawString(“It‟s freezing!”, 10, 10);


                            statement is only executed
                               when condition holds

while (temperature<0)
  temperature += 5;


                      statement is executed over and over
                             while condition holds
Two alternatives
if (temperatuur<0)
   gr.drawString(“It‟s freezing!”, 10, 10);
else
   gr.drawString(“It‟s thawing.”, 10, 10);



                          statement is only excecuted
                          when condition doesn‟t hold
Choice is a statement
as any other

for (n=1; n<20; n++)

     if (n%3==0)
        gr.drawString(n + “divisible”, 10, 10 *n);
     else
        gr.drawString(n + “indivisible”, 10, 10 *n );


one statement               if-statements acts as
  as a body,               body of for-statement
 so no braces
    needed
Multiple-statement body
if (temperatuur<0)
{ gr.drawString(“It‟s freezing!”, 10, 10);
     gr.drawString(“Isnt‟ that cold?”, 10, 20);
}


                   braces group two statements
                             into one
More than two alternatives
  if (age<4)
         tf.setText(“Free”);

  else   if (age<12)
                tf.setText(“Railrunner”);

         else      if (age<65)
                         tf.setText(“Full fare”);
                   else tf.setText(“Senior”);


                if-statement if-statement as a whole
                              as a whole
                   is body of else-part of else-part
                                is body
More than two alternatives

  if (age<4)
        tf.setText(“Free”);
  else if (age<12)
               tf.setText(“Railrunner”);
        tf.setText(“Railrunner”);
  else else if (age<65)
        if (age<65)
                      tf.setText(“Full fare”);
        tf.setText(“Full fare”);
                else tf.setText(“Senior”);
  else tf.setText(“Senior”);



              exeption to rule
             to indent the body
More than two alternatives
                                      return-statement
private String tariff(int age)       ends method body
{
        if (age<4)
              return “Free”;
        else if (age<12)
        if (age<12)
              return “Railrunner”;
        else if (age<65)
        if (age<65)
              return “Full fare”;
        else return “Senior”;
        return “Senior”;
}
Drawing circles
class Cirkel extends Applet implements ActionListener
{ int radius; Button b;
   public void init ( )
   { radius = 100;
       b = new Button(“grow”); this.add(b);
       b.addActionListener(this);
   }
   public void actionPerformed(ActionEvent e)
   { radius += 10; this.repaint();
   }
   public void paint(Graphics gr)
   { gr.fillOval(150-radius,150-radius,2*radius,2*radius);
   }
}
Drawing circles
class Cirkel extends Applet implements ActionListener
{
    int radius;
    Button small, big;

   public void init ( )
   { radius = 10;
       small = new Button(“shrink”); this.add(b);
       big = new Button(“grow”); this.add(b);
       small.addActionListener(this);
       big.addActionListener(this);
   }
Drawing circles
 public void actionPerformed(ActionEvent e)
 {
   if ( e.getSource() == small )&& radius>10 )
       radius -= 10;
                             )
   if ( e.getSource() == big && radius<150 )
       radius += 10;

     this . repaint();
 }

                                equality of
                         Button-object-references)
Secret drawing
class Secret extends Applet
{ boolean open; TextField pass;
    public void init ()
    { open = false;
        pass = new TextField(20); this.add(pass);
        pass.addActionListener(this);
    }
    public void paint (Graphics gr)
    { if (open)
       { gr.setColor(Color.green); gr.fillOval(50,50,100,100);
             gr.setColor(Color.blue); gr.fillOval(81,85,8,8);
             gr.fillOval(111,85,8,8); gr.drawArc(75,75,50,50,225,90);
        }
    }
Secret drawing
class Secret extends Applet implements ActionListener
{ boolean open; TextField pass;

   public void actionPerformed (ActionEvent e)
   {
     if ( pass.getText() . equals (“geheim”) )
     { open = true;
          this . repaint();
           pass . setVisible(false);
     }
   }
operator ==   or
method equals ?

 == tests variable equality
                                          hoi
  x   5   s                 s
                      hoi
  y   5   t                 t
                                          hoi

 equals tests String-contents equality
                                          hoi
method    s                 s
  for     t
                      hoi
                            t
String-                                   hoi
objects
Min./max. thermometer
class Thermo extends Applet
        impelements AdjustmentListener, ActionListener
{   ScrollBar meter; Button reset;
    int minimum, maximum;
    public void init ()
    { meter = new ScrollBar(ScrollBar.HORIZONTAL,0,1,-50,50);
        reset = new Button(“reset”);
        this.add(meter); this.add(reset);
        meter.addAdjustmentListener(this);
        reset.addActionListener(this);
        minimum = 0;
        maximum = 0;
    }
Min./max. thermometer
 public void paint (Graphics gr)
 { gr.drawString( “hoogste ” + maximum, 50,50);
    gr.drawString( “laagste ” + minimum, 50,70);
 }
 public void adjustmentValueChanged(AdjustmentEvent e)
 { int waarde;
   waarde = meter.getValue();
     if (waarde>maximum)
           maximum = waarde;
     if (waarde<minimum)
           minimum = waarde;
     this.repaint();
 }
Interaction components

 ScrollBar sb;                  TextField tf;
 sb = new ScrollBar(            tf = new TextField(
   hv, value, step, range);         width);
 sb.addAdjustmentListener(...); tf.addActionListener(...);
 n = sb.getValue();             s = tf.getText();
 sb.setValue(n);                tf.setText(s);
                                 n = Integer.parseInt(s);
Conversion

From String to int
  String s; int n;
  n     = Integer.parseInt (s);

From String to double
  String s; double d; Double dob;
  d ob = Double.valueOf (s);
  d    = dob.doubleValue ();
Graph-drawing program
entered values
     abc


 solutions
according to
abc-formula




 graph of the
   parabola
Design of class Parabola

declaration Objectvariables
                               makes interface
method init
method actionPerformed          converts a,b,c

method paint             “manages” drawing

method   zeroes                do the
method   axes                   actual
                                drawing
method   graph
method   parabola          calculates ax2+bx+c
Parabola: init
class Para extends Applet implements ActionListener
{
    TextField abox, bbox, cbox;
    double a, b, c;
    public void init ()
    { a = 0.5; b = 2.0; c = -4.0;
        abox = new TextField( “”+a, 8 );
        bbox = new TextField( “”+b, 8 );
        cbox = new TextField( “”+c, 8 );
        this.add(abox); this.add(bbox); this.add(cbox);
        abox.addActionListener(this);
        bbox.addActionListener(this);
        cbox.addActionListener(this);
    }
Parabola: actionPerformed

 public void actionPerformed(ActionEvent e)
 {
     a = Double.parseDouble( abox.getText() );
     b = Double.parseDouble( bbox.getText() );
     c = Double.parseDouble( cbox.getText() );
     this.repaint ();
 }
Parabola: paint
 public void paint (Graphics gr)
 {
   gr . setColor( Color.black );
   this .zeroes      (gr);
   gr . setColor( Color.red );
   this .axes        (gr);
   gr . setColor( Color.blue );
   this .graph       (gr);
 }

 private void axes (Graphics gr)
 { gr.drawLine(0, 250, 500, 250);
     gr.drawLine(250, 0, 250, 500);
 }
Parabola: zeroes
 public void zeroes (Graphics gr)
 {
     discriminant = b*b - 4*a*c;       -b ±    b2-4ac
     denomin      = 2*a;
                                              2a
     if (discriminant<0)
         gr.drawString(“geen nulpunten”);
     else
     { root = Math.sqrt(discriminant);
         gr.drawString( (-b -root)/denomin + “ and ”
                      +(-b+root)/denomin , 50, 50 );
     }

 }
Parabola: graph
 public void graph (Graphics gr)
 { int x, y,oldy; double xw, yw, scale;
    scale = 0.03;
    oldy = 0;
    for ( x=0 ; x<500 ; x++ )
    {
          xw = scale * ( x -250) ;
          y w = this.parabool( x w );
                                       ;
          y = (int) (250-( yw / scale ))

         if (x>0)
              gr.drawLine( x-1, oldy, x, y );
         oldy = y;
     }
 }
Summary lecture 5

if-statement
if-else-statement

                       x==y
compare int with
 compare String with   s.equals(t)
Summary ch. 8

if-statement
if-else-statement

                         x==y
compare integers with
 compare Strings with    s.equals(t)
Min./max. thermometer
class Thermo extends Applet
        implements AdjustmentListener, ActionListener
{   ScrollBar meter; Button reset;
    int minimum, maximum;
    public void init ()
    { meter = new Scrollbar(ScrollBar.HORIZONTAL,0,1,-50,50);
        reset = new Button(“reset”);
        this.add(meter); this.add(reset);
        meter.addAdjustmentListener(this);
        reset.addActionListener(this);
        minimum = 0;
        maximum = 0;
    }
Min./max. thermometer
 public void paint (Graphics gr)
 { gr.drawString( “hoogste ” + maximum, 50,50);
    gr.drawString( “laagste ” + minimum, 50,70);
 }
 public void adjustmentValueChanged(AdjustmentEvent e)
 { int waarde;
   waarde = meter.getValue();
     if (waarde>maximum)
           maximum = waarde;
     if (waarde<minimum)
           minimum = waarde;
     this.repaint();
 }
     All about
objects and classes,
  in one picture...
Program          and     Memory

 statements    change    variables

  grouped in             grouped in


  methods       treat      objects

  grouped in             have as type


    class        class      class
Class-definition              class Counter ...
                              { Button b;
                                 int t;
Description of methods          ... init()
 each consisting of              { b = new Button();
                                        t = 0;
 statements
                      treat       }
                                  ...   paint(...)
                                  {     g.drawString(t...);
                                  }
Description of objects
 by declaration of                ...   actionPerformed()
 variables                        {     t = t+1;
                                        this.repaint();
                                  }
                              }
Declaration

Declaration allocates space in memory
For a primitive value
                                     as described
   int x;                               in class
                             x   5
   x = 5;                             Scrollbar

For an object reference
   ScrollBar s;              s
   s = new ScrollBar(...);
Creation of new objects

Objects having a                 type of
 library class as type         desired object
     Scrollbar s;
     s = new Scrollbar(...);

Objects having a
 home-made class as type
     Thermo t;                  this is done
     t = new Thermo( );        by the browser
     t . init ( );
     t . paint (...);
Creation of objects

Structure of the object
 is described in the class
browser‟s
current
                                           class Thermo
applet                  Thermo                  extends Applet
                                           {
                                              Scrollbar meter;
            inherited                         int min, max;

        declared
                                 meter         // methods...
       in the class min              max
                                           }
                                    public void init ( )
                                    { Button reset;
Call of init                            min = 0; max = 0;
                                        meter = new ScrollBar(...);
                                        reset = new Button(...);
                                    }
                                                             Button

                      reset

browser‟s              this
current
applet      Thermo

                                                       Scrollbar




                      meter

            min   0       max   0
                                    reset = new Button(...);
                                    this . add(meter);
                                    this . add(reset);
Call of init                        reset . addActionListener(this);
                                    meter . addAdjListener(this);
                                    }
                                                             Button

                      reset
                                                   actListener
browser‟s              this
current
applet      Thermo

                      added                            Scrollbar

                                                    adjListener

                                               0    value
                      meter

            min   0       max   0
Situation after
completion of init

                                                  Button


                                        actListener
browser‟s
current
applet      Thermo

                      added                 Scrollbar

                                        adjListener

                                    0   value
                      meter

            min   0       max   0
Classes and objects

Class definition in program
                               Thermo
 Object creation by browser

Class definition in library
                               Scrollbar
 Object creation with new

Class definition in program
                                Space
 Object creation with new
Example: simulation of
moving particles in a space
Simulation -
  object


  Space -
  objects


 Particle -
  objects


  Button -
  objects
Class Simulation
 public class Simulation extends Applet
 {
        Button step, auto;
        Space r1, r2, r3;

       public void init ( )
       { stap = new Button (“step”);
          auto = new Button (“start”);      Class
          r1 = new Space(...);             Space
          r2 = new Space(...);            yet to be
          r3 = new Space(...);             defined!
           ...
       }
 }
Class Space                         Space is an
                                   extension of an
 private class Space                   existing
         extends Canvas           interaction object
 {
      Particle d1, d2, d3;
                                every Space object
     // methods to be defined    has three Particle
                                 objects of its own


 }
Class Particle                  Particle is
                               not extending
                                 anything
 private class Particle

 {                             position of
     int x, y;                 the Particle
     int dx, dy;
                               velocity of
     Color col;                the Particle
     // method to be defined
 }
                                    Simulation

                                     inherited form Applet                                      Button

     Objects                                           stap
                                     declared in the class
                                                        auto                                    Button
     browser‟s current                    r1           r2        r3
     applet

 Space                               Space                                                         Space

 inherited from Canvas

      d1       d2          d3             d1       d2            d3             d1     d2          d3




  x            x           x          x            x             x          x          x            x
  y            y           y          y            y             y          y          y           y
dx           dx          dx          dx          dx            dx         dx         dx           dx
dy           dy          dy          dy          dy            dy         dy         dy           dy
  col          col         col         col         col           col        col        col          col


Particle     Particle    Particle   Particle     Particle      Particle   Particle   Particle    Particle
Construction of a new object
new expression does two things:
    r1 = new Space ( ... ) ;            r1



Allocate memory               Space

                                 100   196

                                 d1    d2    d3
Call constructor
 method
value is reference to the new object
which can be stored
 Constructor method
                                            name is same
      private class Space extends Canvas to that of the class
      {     Particle d1, d2, d3;
            private Space ( int width, int height )
            {
                 this . setSize (width,height);
no result        this . setBackground (Color.gray);
 type!           d1 = new Particle (...);
                 d2 = new Particle (...);
                 d3 = new Paticle (...);
inherited   }
  from}
 Canvas
Class Particle
 private class Particle
 {    int x, y, dx, dy; Color col;

      public          Particle (...)       {...}
      public   void   setPos (...)         {...}
      public   void   setVelo (...)        {...}
      public   void   doStep ( )           {...}
      public   void   draw (Graphics g )   {...}
 }
Methods of class Particle
 private class Particle
 {    int x, y, dx, dy; Color col;

      public void setPos (int x0, int y0)
      { x = x0;
         y = y0;
      }
      public void draw ( Graphics gr)
      { gr . setcolor (col);
          gr . fillOval( x-3, y-3, 7, 7 );
      }
 }
Methods of class Particle
private class Particle
{     int x, y, dx, dy; Color col;
      public void doStep ( )
      { x += dx;
          y += dy;
          if (x<0)
          { x = -x;
              dx = -dx;
          }
          if (y<0)     { ... }
          if (x>maxx) { ... }
          if (y>maxy) { ... }
}
Methods of class Particle
private class Particle
{     int x, y, dx, dy; Color col;
     int maxx, maxy;

     public Particle (Color k, Space r )
     {    col = k;
         maxx = r . getSize( ) . width;
         maxy = r . getSize( ) . height;
     }



}
Summary of classes

class Simulation extends Applet impl ActList
   init
   actionPerformed
class Space extends Canvas
   Space
   paint
class Particle
   Particle
   setPos, setVelo, doStep, draw
Methods of class Simulation
public class Simulation extends Applet impl ActionListener
{     Button step, auto; Space r1, r2, r3;
     public void init ( )
     {    stap = new Button (“step”);
         auto = new Button (“start”);
         r1 = new Space (100, 196);
         r2 = new Space (196, 150);
         r3 = new Space ( 60, 75);
         this.add(stap); this.add(auto);
         this.add(r1); this.add(r2); this.add(r3);
         step.addActionListener(this);
         auto.addActionListener(this);
     }
}
Methods of class Simulation
 public class Simulation extends Applet impl ActionListener
 { Button step, auto; Space r1, r2, r3;

     public void actionPerformed (ActionEvent e )
     {    if (e.getSource() == stap)
               this.doStep( );
         else ...
     }
     private void doStep ( )
     {
          r1.doStep(); r2.doStep(); r3.doStep();
          r1.repaint (); r2.repaint (); r3.repaint ();
     }
 }
Methods of class Space
 private class Space extends Canvas
 { Particle d1, d2, d3;
      public Space (int width, int height)
      { this.setSize (width, height);
          this.setColor (Color.gray);
          d1 = new Particle(Color.red, this);
          d2 = new Particle(Color.red, this);
          d3 = new Particle(Color.red, this);
          d1.setPos(30, 40);
          d1.setVelo(10,10);
          ...
      }
 }
Method of class Space
 private class Space extends Canvas
 { Particle d1, d2, d3;
     public void doStep ( )
     { d1 . doStep ();
        d2 . doStep ();
        d3 . doStep ();
     }
     public void paint (Graphics gr)
     { d1 . draw (gr);
        d2 . draw (gr);
        d3 . draw (gr);
     }
 }
Animation

Animation
 program shows changing pictures
 automatically

Easily programmed using
 library class                 “thread”
                                of events
              Thread          which occur,
                            simultaneously
                           with other threads
Programming animations

Thread animation;
animation = new Thread ( this );

animation . start ( );                 this . run ( );


     calls run        and returns
   of the object     immediately
 that was passed (even when run
to the constructor is still running)
Method run
class Simulation extends Applet implements Runnable
{
    public void run ( )           infinite repetition!
    {
         while (true)
         {     this . doStep ( );       milliseconds
             try
             {   Thread . sleep
             Thread . sleep (50);(50);   }
             catch (Exception e)
             {}
        }
    }
}
Starting the animation

public void actionPerformed (ActionEvent e)
{    if (e.getSource ( )==auto)
     {    if (moving)
          { auto . setLabel (“Start”); moving = false;
          }
          else
          { animation = new Thread(this);
              animation . start ( );
              auto . setLabel (“Stop”); moving = true;
          }
     }
    else this . doStep ( );
}
Method run revisited
class Simulation extends Applet implements Runnable
{
    public void run ( )             finite repetition.
                                  oneindige herhaling!
    {
                (moving)
         while (true)
         {     this . doStep ( );
              try
              {   Thread . sleep (50);   }
              catch (Exception e)
              {}
        }
    }
}
Starting the animation
revisited
public void actionPerformed (ActionEvent e)
{   if (e.getSource ( )==auto)
    {    if (animation != null )
            (beweging)
         { auto . setLabel (“Start”); beweging = false;
                                       animation = null;
         }
         else
         { animatie = new Thread(this);
             animatie . start ( );
             auto . setLabel (“Stop”); moving = true;
         }
    }
    else this . doStep ( );
}
The value null
 x




null : reference to nothing
     x = null;


 null is a valid value
  for each object reference type
Class design                 and use

What is object?
    declarations of object variables
Wat can you do with the object?
    method headers
 How is it done?
    method bodies
Ways to design classes

Top-down
    start with the most complicated class
    using classes and methods which are
    yet to be written
Bottom-up
    start with the simplest class
    creating a library of methods
    which come in useful writing
    the other classes
Summary ch. 9

Make objects of a home-made class
   variables: what is the object
   methods: what can the object do
Animation

   Thread a;               public void run ( )
   a = new Thread(this);   { while (true)
   a . start ( );             { this . doStep ();
                                  Thread . sleep(50);
                              }
                           }
Useful classes (1/4)

Things from reality
String
   length, equals, substring, concat
Color
   Color, red, green, blue, black, white
Dimension
   Dimension, getWidth, getHeight
Useful classes(2/4)

Computer related things
BufferedImage
   setRGB, getRGB, getGraphics
AudioClip
   play, stop, loop
File
   getName, getDirectory, exists, delete
Useful classes(3/4)

Objects that can do something for you
Graphics
   drawLine, fillRect, setColor
StringTokenizer
   nextToken, hasMoreTokens
Useful classes(4/4)

Interaction componenten
  to use                to extend
ScrollBar            Applet
Button               Canvas
TextField            Frame
TextArea
Label
CheckBox
Extending previous work

First try: “cut&paste”
    class Two                       Three
                             class Twee
    {                        {
       int x, y;                int x, y;
                                int z;
        int old ( )             int old ( )
        { return x+y;
                    +1;         { return x+y;
        }                       }
    }                           int extra ( )
                                { return x+y+z;
           problems with        }
        version management    }
Extending previous work
                                         clumsy

Second try: “delegation”
   class Two                      Three
                           class Twee
   {                       {
      int x, y;               Twee t;
                              int z;
       int old ( )            int old ( )
       { return x+y;          { return t.old();
       }                      }
   }                          int extra ( )
                              { return t.x+t.y+z;
                              }
           assymmetrical
                            }
Extending previous work

Third try: “subclasses”
    class Two                     Three
                           class Twee
    {                            extends Two
       int x, y;           {
                              int z;
        int old ( )
        { return x+y;
        }
    }                          int extra ( )
                               { return x+y+z;
                               }
                           }
Subclasses

class Space extends Canvas

Space is a subclass of Canvas
Canvas is the superclass of Space

Each Space-object is also a Canvas-object
A Space-object is a special case of a
 Canvas-object
Inheritance

Objects of a subclass
 inherit variables and methods
 of the superclass
                       Thermo



          inhertited


                                meter
          declared
         by yourself min            max
Superclasses in standard
packages

Applet extends Panel
Panel extends Container



    super-
  superclass

  superclass
 Inherited methods

   Applet inherits add from class Container


 and many
many more...
Class hierarchies
    design:
medium precedes
  motorization                    Transporter


                       Vehicle          Plane               Boat


             MotorVehicle         Bicylce       MotorBoat          SailBoat


       Car            MotorBike                 SteamBoat


 Van                            design:
                            motorbike is more
                             motor than bike
Class hierarchies

                    Transporter


          Vehicle                 Boat



class Vehicle extends Transporter
 class Boat extends Transporter


                    “is a”
Class hierarchy in AWT
                                   Component


 Button       Container      Canvas        Label       TextComponent   Scrollbar


     Panel                Window                   TextArea    TextField


     Applet       Frame        Dialog


                              FileDialog

Button is a Component
Applet is also a Component
 (more precicely, a Container, and even a Panel)
Not every hierarchy is
a class hierarchy

                       “has a”
                                          browser's current
                                             Simulatie


 step     auto        r1                               r2                               r3
Button   Button     Space                            Space                            Space


          d1          d2        d3         d1         d2          d3        d1         d2         d3
         Particle   Particle   Particle   Particle   Particle   Particle   Particle   Particle   Particle
Classes vs. Interfaces

Class:
 Group of methods and declarations
Interface:
 Group of method headers


                  “wish list”
              to be implemented
               by another class
“Interface” in 3 readings

 Hardware:
  connectors are the
  “face” of the computer
 Software:
                      “GUI”
  buttons are the
  “face” of the software
 Programming:
                              class Hallo
  methods are the               implements
  “face” of the program         ActionListener {
Interface hierarchy in AWT

                      Event-
                     Listener


 Action-    Adjustment-    Component-   Mouse-
 Listener    Listener       Listener    Listener
Class hierarchy in AWT
                  EventObject


                  AWTEvent


  ActionEvent   AdjustmentEvent     ComponentEvent


                                InputEvent   FocusEvent


                       KeyEvent       MouseEvent
Everything in one hierarchy

                        Object


 String   Component   EventObject   Image




Methods in class Object :
 toString     redefinable in a subclass
 clone        makes exact copy
TextArea and String

class SymCount extends Applet
                  implements ActionListener
{   TextArea input; TextField output; Button count;


    void init ( )
    { input = new TextArea (5, 40);
       output = new TextField(40);
       count = new Button(“Count”);
       this.add(input); this.add(output); this.add(count);
       count.addActionListener(this);
    }
Useful classes (1/4)

Things from reality
String
   length, equals, substring, concat
Color
   Color, red, green, blue, black, white
Dimension
   Dimension, getWidth, getHeight
Useful classes(2/4)

Computer related things
BufferedImage
   setRGB, getRGB, getGraphics
AudioClip
   play, stop, loop
File
   getName, getDirectory, exists, delete
Useful classes(3/4)

Objects that can do something for you
Graphics
   drawLine, fillRect, setColor
StringTokenizer
   nextToken, hasMoreTokens
Useful classes(4/4)

Interaction componenten
  to use                to extend
ScrollBar            Applet
Button               Canvas
TextField            Frame
TextArea
Label
CheckBox
Extending previous work

First try: “cut&paste”
    class Two                       Three
                             class Twee
    {                        {
       int x, y;                int x, y;
                                int z;
        int old ( )             int old ( )
        { return x+y;
                    +1;         { return x+y;
        }                       }
    }                           int extra ( )
                                { return x+y+z;
           problems with        }
        version management    }
Extending previous work
                                         clumsy

Second try: “delegation”
   class Two                      Three
                           class Twee
   {                       {
      int x, y;               Twee t;
                              int z;
       int old ( )            int old ( )
       { return x+y;          { return t.old();
       }                      }
   }                          int extra ( )
                              { return t.x+t.y+z;
                              }
           assymmetrical
                            }
Extending previous work

Third try: “subclasses”
    class Two                     Three
                           class Twee
    {                            extends Two
       int x, y;           {
                              int z;
        int old ( )
        { return x+y;
        }
    }                          int extra ( )
                               { return x+y+z;
                               }
                           }
Subclasses

class Space extends Canvas

Space is a subclass of Canvas
Canvas is the superclass of Space

Each Space-object is also a Canvas-object
A Space-object is a special case of a
 Canvas-object
Inheritance

Objects of a subclass
 inherit variables and methods
 of the superclass
                       Thermo



          inhertited


                                meter
          declared
         by yourself min            max
Superclasses in standard
packages

Applet extends Panel
Panel extends Container



    super-
  superclass

  superclass
 Inherited methods

   Applet inherits add from class Container


 and many
many more...
Class hierarchies
    design:
medium precedes
  motorization                    Transporter


                       Vehicle          Plane               Boat


             MotorVehicle         Bicylce       MotorBoat          SailBoat


       Car            MotorBike                 SteamBoat


 Van                            design:
                            motorbike is more
                             motor than bike
Class hierarchies

                    Transporter


          Vehicle                 Boat



class Vehicle extends Transporter
 class Boat extends Transporter


                    “is a”
Class hierarchy in AWT
                                   Component


 Button       Container      Canvas        Label       TextComponent   Scrollbar


     Panel                Window                   TextArea    TextField


     Applet       Frame        Dialog


                              FileDialog

Button is a Component
Applet is also a Component
 (more precicely, a Container, and even a Panel)
Not every hierarchy is
a class hierarchy

                       “has a”
                                          browser's current
                                             Simulatie


 step     auto        r1                               r2                               r3
Button   Button     Space                            Space                            Space


          d1          d2        d3         d1         d2          d3        d1         d2         d3
         Particle   Particle   Particle   Particle   Particle   Particle   Particle   Particle   Particle
Classes vs. Interfaces

Class:
 Group of methods and declarations
Interface:
 Group of method headers


                  “wish list”
              to be implemented
               by another class
“Interface” in 3 readings

 Hardware:
  connectors are the
  “face” of the computer
 Software:
                      “GUI”
  buttons are the
  “face” of the software
 Programming:
                              class Hallo
  methods are the               implements
  “face” of the program         ActionListener {
Interface hierarchy in AWT

                      Event-
                     Listener


 Action-    Adjustment-    Component-   Mouse-
 Listener    Listener       Listener    Listener
Class hierarchy in AWT
                  EventObject


                  AWTEvent


  ActionEvent   AdjustmentEvent     ComponentEvent


                                InputEvent   FocusEvent


                       KeyEvent       MouseEvent
Everything in one hierarchy

                        Object


 String   Component   EventObject   Image




Methods in class Object :
 toString     redefinable in a subclass
 clone        makes exact copy
TextArea and String

class SymCount extends Applet
                  implements ActionListener
{   TextArea input; TextField output; Button count;

    void actionPerformed ( ActionEvent e )
    { String s; int n;
       s = input.getText ();
       n = s.length ();
       output.setText ( “you typed ” + n + “ symbols” );
    }
String methods

int     length       ()
boolean equals       (String s)
String concat        (String s)
String substring     (int start)
String substring     (int start, int end)
String toUpperCase   ()
String toLowerCase   ()
concat and substring
                              s        t      u      v     w
String s, t, u, v, w;
s = “ham”;
                            ham   burger
t = “burger”;
u = s.concat(t);
        s+t;                          hamburger

v = u.substring(3);                              burger

w = u.substring(3, 7);                                    burg
                                           012345678
        “from and     “up to, but          hamburger
        including”   not including”
Class challenge

Write a method startsWith
 having two String-parameters x and y
 that determines whether
 x is the initial part of y

Write a method contains
 having two String-parameters x and y
 that determines whether
 x occurs anywhere inside y
Method startsWith
                                           part     whole


private static boolean startsWith (String x, String y)
{
     return
      x . equals ( y . substring (0, x.length() )
                 );
}
Methode contains

private static boolean contains (String x, String y)
{
     int t;
     for (t=0; t<y.length(); t++)
         if ( startsWith(x, y . substring(t) ) )
               return true;
     return false;
}
More String-methods

boolean startsWith            (String s)
boolean endsWith              (String s)
int     indexOf               (String s)
 private static boolean contains(String x, String y)
 {
    return y.indexOf(x)>=0 ;
 }
Stand-alone characters

String     substring            (int begin, int end)

 String initial;
 initial = s . substring(0,1);


char       charAt               (int position)
 char first;
 first = s . charAt(0);
Primitive types

int
 whole numbers   -17, -5, 0, 3, 178
double
 real numbers    3.141, 2.0, -1.5E8
boolean
 truth values    false, true
char
 symbols         ‟A‟, ‟B‟, ‟Z‟, ‟a‟, ‟4‟, ‟#‟, „:‟
Class challenge

// write a static method that counts
 // how often a symbol occurs in a String
// example call:

    int n;
    n = Demo . freq( “some text”, ‟e‟ );

// hint: use a for statement
Count symbol frequency
private static int freq(String s, char x)
{
     int count, t;
     count = 0;
     for (t=0; t<s.length(); t++)
         if ( s.charAt(t)==x )
              count++;
     return count;
}
History of char

1970s: 6 bits = 64 symbols
    26 letters, 10 digits, 28 punctuation
1980s: 7 bits = 128 symbols           ASCII
    +26 lowercase, +5 punct., 33 control
1990s: 8 bits = 256 symbols         IBM/DOS
                                     ANSI/ISO
    +letters with diacriticals
2000s: 16 bits = 65536 symbols Unicode
    +Greek, Cyrillic, Japanese, Devangari, ...
  Character coding
     code 0

                                           bs tab lf             cr
code 32                                                esc
          sp   !   "   #   $   %   &   '   (   ) *      +    ,   -    .    /
code 48   0    1   2   3   4   5   6   7   8   9 :      ;    <   =    >    ?
          @    A   B   C   D   E   F   G   H   I J      K    L   M    N    O
code 65   P    Q   R   S   T   U   V   W   X   Y Z      [    \   ]    ^    _
          `    a   b   c   d   e   f   g   h   i j      k    l   m    n    o
code 97   p    q   r   s   t   u   v   w   x   y z      {    |   }    ~   del

                                                                 code 127
char specials

alfabetically ordered
          char c;
          if ( ‟A‟<=c && c<=‟Z‟ ) …
convertable to int
          int n;
          n = c + 32;
and back
          c = (char) n;
Conversions
Conversion to “larger” set
 is always possible
  double d;      int n;          Component x;
  int n;         char c;         Button b;
  d = n;         n = c;          x = b;


Conversion to “smaller” set
 is dangerous
  n = (int) d;   c = (char) n;   b = (Button) x;
Special char values

Literal symbool                     ’A’    ’&’

Special symbol                      ’\n’   ’\t’
The quote symbol                    ’\’’   ’\”’

The backslash symbol                ’\\’

        two symbols in the source,
        representing one character
String versus char
String                 char
class                  primitive type
object-reference       immediate value
zero, one or more…     exactly one symbol
“”    “A”    “hello”           ‟A‟
methods                operators
   equals                  ==
   concat                  <
   substring               +
Counting words

void actionPerformed ( ActionEvent e )
{ String s; int n; int w, r, t;
   s = input.getText ();
   w = 0; r = 0;
   for t=0; t<s.length(); t++ )
   n = (s.length ();
   {       if (s . charAt(t)==„ ‟) w++;
           if (s . charAt(t)==„\n‟) { r++; w++; }
   }

    output.setText ( “you typed ” + n + “ symbols” );
                                    w + “ words”
                    + “on ”    + r + “ lines” );
}
Counting words
void actionPerformed ( ActionEvent e )
{ String s; int n;
   s = input.getText ();         input
   w=0; r=0;
   for (t=0; y<s.length(); t++)           the actual
   { if ( s.charAt(t)==„ ‟) w++;           counting
       if (s.charAt(t)==„\n‟) r++;
   }
   output.setText( (w+r) + “ words on ” +        output
                  + r + “ lines”                    &
                  );                             layout
}
Separate class for doing
the counting
class Counters
{     int r, w;
      Counters()
      { r=0; w=0;
      }
      void check (String s)
      { for (t=0; t<s.length; t++)
            ....r++....w++....
      }
      String toString ( )
      { return (w+r) + “ words on ” + r + “ lines”;
      }
}
Using the new class

void actionPerformed(ActionEvent e)
{
      Counters c;
      c = new Counters();

     c . check ( input.getText() );
     output . setText ( c.toString() );
}
Counting digits
class Counters
{     int t0, t1, t2, t3, t4, t5, t6, t7, t8, t9;
       Counters()
       { t0=0; t1=0; t2=0; t3=0; t4=0;
          t5=0; t6=0; t7=0; t8=0; t9=0;
       }                                             OK, OK,
       void check (String s)                        I got it...
       { for (t=0; t<s.length; t++)
           { if (s.charAt(t)==„0‟) t0++;
              if (s.charAt(t)==„1‟) t1++;
              if (s.charAt(t)==„2‟) t2++;
              if (s.charAt(t)==„3‟) t3++;
              if (s.charAt(t)==„4‟) t4++;
              if (s.charAt(t)==„5‟) t5++;
Arrays

Array: many numbered variables
 declaration of
   the array             table    5   length

                                      0
int [ ] table;                        1
                                      2
table = new int [5];                  3
                                      4

           creation of
           the object
Use of an array

all the variables can be actually used:

table [2] = 37;            table        5    length


x = table [2] + 5;            x    42        0
                                             1

if (table.length<10) ...                37   2
                                             3
table.length = 10;                           4



     but you cannot change
           the length
Use of an array

variable as an index into the array

table   [0]   =   0;   table           5   length
table   [1]   =   0;
                                       0   0
table   [2]   =   0;
                                           1
table   [3]   =   0;                   0

table   [4]   =   0;                   0   2

                                       0   3

for (t=0; t<5; t++)                    0   4

    table [t] = 0;
Array as a parameter
int smallest ( int [ ] table )       table

{
    int result; int t;
                                             5    length
    result =table [0];                            0
                                             12
    for (t=0; t<table.length; t++)                1
                                             95
       if (table [t] < result)                    2
                                             11
           result = table [t];                    3
                                             23
    return result;                           15   4
}
Application:
character counter


 user types some text...


  presses the button...

    and the program
     determines all
  character frequencies
Program structure
public class Text extends Applet
                  implements ActionListener
{ TextArea input, output; Button count;
   public void init ()
   {   input = new TextArea( 5, 30);
       output = new TextArea(28, 20);
       count = new Button(“count characters”);
       output . setEditable (false);
       this.add(input);
       this.add(count);
       this.add(output);
       count.setActionListener (this);
   }
Program structure
public class Text extends Applet
                   implements ActionListener
{ TextArea input, output; Button count;
     public void actionPerformed(ActionEvent e)
     {
         Counters table;
         table = new Counters ( );

         table . check ( input.getText() );

         output . setText ( table.toString() );
     }
 }
                                           class design:
Class Counters                               what is ...
                                          & what does ...
                                           & how?
public class Counters
{
   int [ ] tab;
   int total;
    public Counters ( )         { ... }
    public void check (String s){ ... }
    public String toString ( )  { ... }
    private void check (char c){ ... }
}
Class Counters
public class Counters
{  int [ ] tab; int total;
    public Counters ( )
    {   tab = new int [26];       int t;
        for (t=0; t<26; t++)
            tab [t] = 0;
    }
    public void check (String s)
    {    int t;
         for (t=0; t<s.length(); t++)
              check (s.charAt(t));
    }
}
Class Counters
public class counters
{  int [ ] tab; int total;
    public void check (char c)
    { if (c>=„A‟ && c<=„Z‟)
        {    tab [ c - „A‟ ] ++;
             total++;
        }
        if (c>=„a‟ && c<=„z‟)
        {    tab [ c - „a‟ ] ++;
             total++;
        }
    }
}
Class Counters
public class Counters
{  int [ ] tab; int total;
    public String toString( )
    {
        String result; int t;
        result = “”;
        for (t=0; t<26; t++)
            result += (char) (t+ „A‟) + “:”
                                t
                               (t+ „A‟) + “:”
                             tab[t]
                         + tab[t] + “times\n” ;
        result += “total:” + total;
        return result;
    }
}

				
DOCUMENT INFO