imperative programming nvon neumann’s computer model: computer = + memoryprocessor to store values...

290
Imperative programming Von Neumann’s computer model: compute r = + memory process or to store values to execute instructions

Post on 20-Dec-2015

225 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Imperative programming

Von Neumann’s computer model:

computer=+

memory processor

to store values

to execute instructions

Page 2: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Instructions

Instruction:direction to modify memory

Program:long sequence of instructions,which are executed one by oneby the processor

instructions are stored in memory, too, but don’t modify themselves

Page 3: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Programming languages

Programminglanguage:notation for programs

since 1945:3000 different languages published

Page 4: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

History of programming languages

1945

1950

1955

1960

1965

1970

1975

1980

1985

1990

1995

2000

Assembler

Mach.lang.

Fortran

Algol

Basic

Pascal

Simula

C

C++

Java

Cobol

SQL

Lisp

Prolog

Haskell

FunctionalProgramming

ImperativeProgramming

Databases(SCI251)

Page 5: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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

Page 6: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Problems associated with programming

in olden times:how can memory be utilized efficiently?

now:how can memory be understood in full?

Page 7: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Order out of chaos

person

club

league

federation

county

province

state

country

unionunion

employee

department

division

company

holding

lecturer

chair

department

faculty

university

Page 8: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Memory structure

named memory location

group of variablesbelonging together

variable

object

object group of objects

belonging together

Page 9: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Program structure

direction to change memory

group of instructions belonging together

statement

method

class group of methods

belonging together

Page 10: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Programming paradigms

Imperative

Procedural

Object- oriented

Fortran Basic

Pascal C

C++ Java

Declarative

Functional

Logic

Lisp

Haskell

Prolog

Assembler

Algol

Simula

Excel

Page 11: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Java why?

Imperative and procedural and object oriented

Fun to learn Extensive libraries

also for window programs Cool : programming for the Internet

Page 12: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Machine language

Instructions are specificfor a target processor

Page 13: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Translating 1/4: Assembler

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

assembler

assembler

Page 14: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Higher programming language

Single program can be translated for many different processors

Source code also intelligible for human writer/reader

Page 15: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Translating 2/4: Compiler

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

compiler

compiler

Page 16: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Translating 3/4: Interpreter

A processor sepcific interpreterreads source code and executes it

interpreter

interpreter

Page 17: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Translating 4/4: Compiler+Interpreter

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

compiler

interpreter

interpreter

Page 18: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Implement

Programming cycle

Edit

Compile

Run

Specify

Model

Page 19: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Java program types

Java Appletprogram “lives” on a WWW-page

Java Applicationprogram has window of its own

Javascriptprogram assists in web page construction

JavaScript is not Java!

Page 20: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Java versus JavaScript

Imperative Can be Internet based Object oriented Compiled byte code In fixed rectangle Extensive method

libraries For programmers

Imperative Internet based “Only” procedural Interpreted directly Influences browser Fixed number built-

in methods For web designers

Page 21: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Source code structure

Statements to modify memory

Statements are grouped in methods

Methods are grouped in classes

Page 22: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

which might be calls to yet other methodsso “where am I” tracking might grow complicated!

Statement forms

Assignment -statement:modify memory

Call of another method:first execute statements of that method, then continue were you were

Page 23: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Object orientation

Object:part of memory that belongs together

Object oriented programming:methods involves (mostly) an objectmentioned at the call

Page 24: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Example Java program

one class

...with onemethod

...with onestatement

braces delimitclass and method

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

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

Page 25: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class and method header

public:may be used from outside

name:determined byprogrammer

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

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

Page 26: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Statement: method call

statement:method call

method namealwaysa dot

otherdetails

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

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

object involved

Page 27: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Communication with browserclass is

extension oflibrary class

Applet

... which comesin useful!

browser callspaint method,

providing aGraphics object ...

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

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

Page 28: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class libraries

library classesmay be used...

if they areimported,

mentioning theirpackage

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

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

Page 29: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

we get a parameter

Method header and call

we providethree parameters

methodheadermethod

call

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

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

Page 30: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

WWW-page with Applet

special HTML-tag

<APPLET>

byte code which resultsfrom compiling Hello.java

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

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

Page 31: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Embedding an Appletimport java.awt.Graphics;import java.applet.Applet;

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

Hello.java

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

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

Hello.html

compiler

Hello.class

Page 32: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

SDK: Software Development Kit

Sun’s Java SDK

compiler:javac

bytecode-interpreter:

appletviewer

Page 33: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Integrated Development Environment: JCreator

Page 34: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

JCreator: New File

Page 35: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

JCreator: syntax highlighting editor

Page 36: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

JCreator: Error messages

Page 37: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

JCreator: Run applet

Page 38: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

JCreator: set options

Page 39: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Run applet in Explorer

Page 40: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

JCreator: JDK help

Page 41: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary

Imperative programming:program consists of statements,modifying memory

Object oriented programming:variables belonging togetherare grouped in objects

Page 42: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary

Statement :direction to modify memory

Method :named group of statements

Class :named group of methods

Page 43: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary

Translating higher language (source code)

to machine language (object code)

Assembler Interpreter Compiler Compiler - bytecode - interpreter

Page 44: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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

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

Hello.java

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

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

Hello.html

compiler

Hello.class

Page 45: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

we get a parameter

Summary

we providethree parameters

method-headermethod-

call

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

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

Page 46: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class and method header

method fromclass Graphics

other methodsfrom Graphics

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

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

g.drawLine(10,20,50,60);g.fillRect (70,30,20,20);

Page 47: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Methods from Graphics

drawString drawLine drawRect drawOval fillRect fillOval setColor

hello

x

y

determines color of subsequent drawing

Page 48: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Classes and objects

Class describesobject capability

Object can do andremember things

Class also provides constants

... (Graphics g)

{ g.drawLine(10,20,50,60); g.fillRect (70,30,20,20); g.setColor( Color.blue ); g.fillRect (30,50,20,20);

g.setColor( Color.blue );}

method fromclass of object g

Page 49: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Colors

redgreenyellow

blue

cyan magenta

white

black

Color .

Page 50: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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 );g.fillRect(100,0,100,40);

Composition with blue and red (freely after Piet Mondrian)

Page 51: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Modifying the drawing

Correction of bar width

Correction of picture height

Correction of picture width

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 );g.fillRect(100,0,100,40);

lots of work ...

Page 52: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Variables

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.fillRect(10, 0 ,bar, height);g.fillRect(50, 0, bar, height);g.fillRect(90, 0, bar, height);g.fillRect(0, 40, width, bar);g.fillRect(0, 70, width, bar);

bar = 10;width = 200;height = 100;

int bar, width, height;

use of variables

assignmentstatements:variables get

a value

declaration:announcement

of variablesand their type

Page 53: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Method call

Assignment statement

Statement forms

object . method ( parameters ) ;

variable = value ;

becomes

Page 54: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Declarations

Declaration structure

zero or more

int: whole numbers double: floating point numbers class name : object variables

type variabele , variabele ;

Page 55: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Variables

g.fillRect(x1, 0 ,bar, height);g.fillRect(x2, 0, bar, height);g.fillRect(x3, 0, bar, height);g.fillRect(0, y1, width, bar);g.fillRect(0, y2, width, bar);

x1=10; x2=50; x3=90;y1=40; y2=70;

int x1, x2, x3, y1, y2;

g.setColor( Color.blue);g.fillRect(0, y1+bar, x1, y2-y1-bar );

x1 x2 x3

y1

y2

Page 56: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Expression:program phrase having a value

Use of expressions: Right hand side of assignment

statement

Method parameter

Expressions

x3 = x2+40 ;

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

Page 57: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

expressie

Expression structure

constant

variable

... operator ...

( ... )

5

hoogte

x + y

(y + 1)

+ 1

x -

expressionexpression

Page 58: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Operators

+ addition - subtraction * multiplication / division % remainder after division

division of int values:result is truncated!

14 / 3 == 4 14 == 4*3 + 214 % 3 == 2

Page 59: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Operator precedence

Multiplicationprecedes addition

Equal precedence:left to right

Want it otherwise?place parentheses!

1 + 2 * 3 == 7

and divisionand subtraction

10 - 5 - 2 == 3

(1+2) * 3 == 9

Page 60: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Program

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

public class Mondri extends Applet{ public void paint(Graphics g) { int breedte, hoogte, balk, x1, x2, x3, y1, y2; breedte = 200; x1 = 10; x2 = 50; x3 = 90; hoogte = 100; y1 = 40; y2 = 70; balk = 10; g.setColor(Color.white); g.fillRect(0, 0, breedte, hoogte);

g.setColor(Color.black); g.fillRect(x1, 0, balk, hoogte); g.fillRect(x2, 0, balk, hoogte); g.fillRect(x3, 0, balk, hoogte); g.fillRect(0, y1, breedte, balk); g.fillRect(0, y2, breedte, balk);

g.setColor(Color.blue); g.fillRect(0, y1+balk, x1, y2-(y1+balk) );

g.setColor(Color.red); g.fillRect(x3+balk, 0, breedte-(x3+balk), y1); }}

/* This applet displays a Mondrian like "composition with red and blue”*/

// position of lines

// background

// black bars

// colored fields

with comments

Page 61: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Comments

Intended for human readerignored by compiler

Two notations: from /* to */ from // to line end

Page 62: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Drawing

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);g.drawLine(120,40,150,10);g.drawLine(150,10,180,40);

public void paint(Graphics g){

}

big mess ofcoordinates!

Page 63: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

New methods

Method:named group of statements

method call executesits body

private void drawHouse(…){ … . drawRect (…); … . drawLine (…); … . drawLine (…);}

public void paint(Graphics g){ … . drawHouse (…); … . drawHouse (…); … . drawhouse (…);}

Page 64: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

private void drawHouse(…){ … . drawRect (…); … . drawLine (…); … . drawLine (…);}

public void paint(Graphics g){ … . drawHouse (…); … . drawHouse (…); … . drawHouse (…);}

Parameters

which Graphics objectis involved?

declaration of extra

parameter

private void drawHouse (Graphics gr, …){ gr . drawRect (…); gr . drawLine (…); gr . drawLine (…);}

pass extraparameter

public void paint(Graphics g){ … . drawHouse (g, …); … . drawHouse (g, …); … . drawHouse (g, …);}

Page 65: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public class Houses extends Applet{

}

public void paint(Graphics g){ … . drawHouse (g, …); … . drawHouse (g, …); … . drawHouse (g, …);}

public void paint(Graphics g){ … . drawHouse (g, …); … . drawHouse (g, …); … . drawHouse (g, …);}

The object this

which ??? objectis involved?

private void drawHouse (Graphics gr, …){ gr . drawRect (…); gr . drawLine (…); gr . drawLine (…);}public void paint(Graphics g){ this . drawHouse (g, …); this . drawHouse (g, …); this . drawHouse (g, …);}

which Houses objectis involved?

this: the objectalready involved

with paint

Page 66: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public void paint(Graphics g){ this . drawHouse (g, …); this . drawHouse (g, …); this . drawHouse (g, …);}

More parameters

draw threeslightly different

houses

even moreparameters!

public void paint(Graphics g){ this . drawHouse (g, 20,100, 40); this . drawHouse (g, 70,100, 40); this . drawHouse (g, 120,100, 60);}

Page 67: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Parameters

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

(tx,ty)

(x,y)w

private void drawHouse (Graphics gr, … ){

gr . drawRect (…); gr . drawLine (…); gr . drawLine (…);}

private void drawHouse (Graphics gr, int x, int y, int w){ int tx, ty; tx = x + w/2; ty = y - w - w/2; gr . drawRect (x, y-w, w, w); gr . drawLine (x, y-w, tx, ty); gr . drawLine (tx, ty, x+w, y-w);}

private void drawHouse (Graphics gr, int x, int y, int w){ int tx, ty; tx = x + w; ty = y - w – w/2; gr . drawRect (x, y-w, w, w); gr . drawLine (x, y-w, tx, ty); gr . drawLine (…);}

private void drawHouse (Graphics gr, int x, int y, int w){

gr . drawRect (x, y-w, w, w); gr . drawLine (…); gr . drawLine (…);}

private void drawHouse (Graphics gr, int x, int y, int w){

gr . drawRect (…); gr . drawLine (…); gr . drawLine (…);}

Page 68: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Flexibility

The more parameters, the more flexible the method

(x,y)w

h

roofh

private void drawHouse(Graphics gr, int x, int y, int w, int h, int roofh, Color c, Color roofc, … ) {

and the morecumbersome to call...

Page 69: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Flexibility

Many parameters: hard to program

now easy to extend later

Few parameters: easy to prgram

now might be hard to

extend later

Page 70: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Communication among methods

Parameters :caller passes value to method

Method result :methods returnsvalue to caller

like amathematical

function

Page 71: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Methods with result

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

result type

value of resultin special return statement

Page 72: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Methods with result

first, somestatements

private int succesorsThirdPower (int x){ int s; s = x+1; return s*s*s ;}

Page 73: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Call of a void-methodis a statement

Method calling

g.drawString(“hello”, 10, 10) ;

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

withoutresult

Call of a method with a resultis an expression

Page 74: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Expressions Constant Variable Operator expr. Expr. in parentheses

Call of methodwith a result

Statements Assignment

Call of void method

Return statement

Summary of constructs

x=5;

this.drawHouse (…);

return x*x;

5

xx+1

(x+1)

this.square(5)

Page 75: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary chapter 2

Statement :directions to change memory

Method :named group of statements

Class :named group of methods

Page 76: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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

Page 77: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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

Page 78: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Expression Constant Variable Operator expr. Expression in parenth.

Calling a method with a result

Statements Assignment

Calling a void method

Return statement

Summary chapter 3+4

x=5;

this.drawHouse (…);

return x*x;

5

xx+1

(x+1)

this.square(5)

Page 79: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Methods and objects

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

x = Math . sqrt(2.0) ;

method fromclass Graphics

Graphics objectinvolved

method fromclass Math

no object involved

static method

Page 80: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Parameters

not the parameter of paint !should always be a Graphics-object

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?

Page 81: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

allowed: method of Greeting and Applet

Class extensions inherit methods

yielding a text String

public class Greeting extends Applet{ public void paint(Graphics g) { String person, greeting;

person = this . getParameter(“name”); greeting = “Hello ” + person + “!”; g.drawString(greeting, 50, 20 ); }}

public class Greeting extends Applet{ public void paint(Graphics g) {

this . getParameter(“name”);

}}

public class Greeting extends Applet{ public void paint(Graphics g) { String person;

person = this . getParameter(“name”);

}}

public class Greeting extends Applet{ public void paint(Graphics g) {

}}

public class Greeting extends Applet{ public void paint(Graphics g) {

this . ???

}}

like this one:

Page 82: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Passing parameters to Applets

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

</APPLET>

<PARAM name=name value=Jeroen>

as specifiedwhen calling

getParameter

will be the resultof the call to

getParameter

Page 83: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

String

String object contains text Ways to obtain a String object:

constant calling a method yielding a String

calling an operatoryielding a String

this.getParameter (“name”)

“Hello” + person

“Hello”

not addition,but concatenation

Page 84: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Numbers versus texts

int x; x = 37;

String s; s = “37”;

x = 12 + 5; s = “12” + “5”;

17 “125”

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

conversion methodconcatenation operator

converts second operand to a String

whenever the first is

Page 85: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Applet with int parameters

public void paint (Graphics gr){

}

String text1, text2;

text1 = this.getParameter(“length”);text2 = this.getParameter(“width”);

length = Integer.parseInt(text1);width = Integer.parseInt(text2);gr.drawString(“perimeter: ” + 2*(length+width), 0, 0 );

int length, width;

Page 86: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Passing parameters toan Applet

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

</APPLET>

<PARAM name=length value=12><PARAM name=width value=8>

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

</APPLET>

<PARAM name=length value=7><PARAM name=width value=3>

Page 87: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Primitive versus Objecttypes types

int i; double d;

String s; Color c;

i

d

s

c

i = 5; d = 3.1415926;

s = “hello”; c = Color.blue;

3.1415926

5

object variablescontain references

Page 88: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

How to obtain objects

String constants Constants in a class Result of a method Result of an operator Home made

“hello”

Color.blue

this.getParameter(“a”);

“total: ” + sum

new Color(0,0,0)

constructor method

Page 89: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Constructor method

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

new Color(0,0,0)

calling a constructoris an expression

Color c;c = gr.setColor( );

Page 90: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Colors

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

(0,0,255)

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

(255,255,255)

(0,0,0)

Color(...)

Page 91: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Mixing colors

new Color(255, 0, 0)

new Color(255, 255, 0)

new Color(255, 64, 0) new Color(255, 128, 0) new Color(255, 192, 0)

Page 92: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Creating new objects

Color c;c = new Color(255,128,0);

Button b;b = new Button(“press here”);

ScrollBar s;s = new ScrollBar(...);

objects for interactionwith the user

Page 93: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Methods of Applet

paint

getParameter

init

add repaint

are calledby the browser

may be called from within the program

redefine inyour program!

Page 94: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Applet’s init and paint

init:called by the browserwhen the applet starts first

paint:called by the browsereach time the applet needs painting

just after init , but alsowhen a window re-appears

Page 95: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Applet’s add and repaint

add:to add interaction objects

repaint:to force an extra paint

typically: from init

Page 96: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Example: color mixerScrollBar Button

Page 97: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Using add

public class Mixer extends Applet{

public void init( ) {

} public void paint(Graphics gr) {

}

s = new ScrollBar(...);this.add( s );

.... s . getValue() ....

ScrollBar s; object-variable:is part of

this object

and therefore may be used inevery method!

ScrollBar s ;

Page 98: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Reacting on user actions

Event: action of the user click button slide scrollbar enter text in textfield ...

Event listener: object that reacts upon that

Page 99: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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 notifiedwhen the user adjusts scrollbar s

Page 100: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public class ...{ public void adjustmentValueChanged ( AdjustmentEvent e ) { // statements which will be executed // in response to user actions }}

Notification mechanism

implements AdjustmentListener

promise that adjustmentValueChanged will indeed be defined

Page 101: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public class Mixer extends Applet

{ ScrollBar s;

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

Which event listener to use?

public void adjustmentValueChanged (AdjustmentEvent e){

}

Mixer object isevent listener of

its own scrollbar!

implements AdjustmentListener

this

// here you may use s and this

Page 102: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

ScrollBar

public void init ( ){ s = new ScrollBar(...); this . add( s );

}

public void adjustmentValueChanged (AdjustmentEvent e){ this . repaint( );} public void paint (Graphics gr){

gr . fillRect( 0, 0, 100, 100 );}

int x; x = s . getValue( );gr . setColor( new Color(x, ..., ...) );

s . addAdjustmentListener (this);

Reacting on events

Page 103: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Interaction objectswith event listeners

ScrollBar s;s.addAdjustmentListener(this);

implements AdjustmentListenerpublic void adjustmentValueChanged (AdjustmentEvent e){...}

Button b;b.addActionListener(this);

implements ActionListenerpublic void actionPerformed (ActionEvent e){...}

Page 104: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Complete Color mixer

Page 105: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public class Mixer extends Applet implements ActionListener, AdjustmentListener { Scrollbar red, green, blue; Button black;

public void init ( ) {...} public void paint (Graphics gr) {...}

public void adjustmentValueChanged (...) {...} public void actionPerformed (...) {...}}

class Mixer: outline

object variables

redefiningApplet-methods

fullfilling promisesmade by implements

Page 106: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public void init ( ){ red = new Scrollbar(0,0,1,0,255); green = new Scrollbar(0,0,1,0,255); blue = new Scrollbar(0,0,1,0,255); black = new Button(“Black”); this . add(red); this . add(green); this . add(blue); this . add(black); red . addAdjustmentListener (this); green . addAdjustmentListener (this); blue . addAdjustmentListener (this); black . addActionListener (this);}

Mixer’s method init

creation ofinteraction

objects

building theuser interface

addition ofevent listeners

Page 107: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Mixer’s method paint

local declarations

getscrollbarpositions

draw coloredrectangle

public void paint (Graphics gr){ int rv, gv, bv;

rv = red . getValue(); gv = green . getValue(); bv = blue . getValue();

gr . setColor ( new Color(rv,bv,gv) ); gr . drawRect ( 20,60,260,220 );}

gr . drawString( rw+“ ”+gw+“ ”+bw );

Page 108: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public void adjustmentValueChanged (AdjustmentEvent e){ this . repaint( );}

Mixer’s Event-listenters

reation toScrollBar

reaction toButton

public void actionPerformed (ActionEvent e){ red . setValue(0); green . setValue(0); blue . setValue(0); this . repaint( );}

Page 109: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary Declarationsobject variable

parameter

local variable

public class Mixer ...{ Scrollbar red;

public void paint ( Graphics gr ) { int rv; rv = red . getValue( ); }}

permanently,assigned to in init

for communication,assigned to at call

temporarilyassigned to with an

assignment

Page 110: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Applet init paint getParamet

er add repaint

Summary AWT-classes

Graphics drawString fillRect setColor

Color String

ScrollBar getValue setValue

Button

ActionListener actionPerformed

AdjustmentListener adjustmentValueChanged

Page 111: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary chapter 4

Objects existing: parameter or constant result of method or operator home-made using new

Methods “involve” an object except: static methods

Page 112: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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)

Page 113: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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>

Page 114: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary chapter 6

Applet-methods are inherited byextension classes Intended to call

getParameterrepaint

Intended to re-defineinitpaint

for creation ofinteraction objects

Page 115: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class challange

How to make interaction componentsand how to react on their use?

Write a program showing a Scrollbar,and beneath it a numerical representationof its value

now!approx 5 min.

peeking at ch. 6 is allowed,but try first without that!

Page 116: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public class Interact extends Applet

{

}

Interaction

public void init(){ s = new Scrollbar(0,0,1,0,100); this . add(s);}public void paint(Graphics gr){ gr.drawString( s.getValue()+””, 50,50);}public void adjustmentValueChanged(...){ this . repaint();}

Scrollbar s;

implements AdjustmenListener

s.addAdjustmentListener(this);

Page 117: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

while ( x<1000 ) x = 2*x;

public void paint (Graphics gr){ int x; x = 1;

gr . drawString( “” + x, 10, 10);}

Repeating statements

the body isexecuted over

and over

while thecondition

holds...

X 12481632641282565121024

Page 118: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Repeating multiple statements

int x, t;x=1; t=0;while ( x<1000 ){ x = 2*x; t = t+1;}

return t;}

n

private static int twoLog (int n){

braces pack twostatements into

a compound one

counter countsthe numberof doublings

Page 119: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Repetition with a counter

public void paint (Graphics gr){ int t; t=0; while ( t<10 ) { gr.drawString( “:-)”, 0, 20*t ); t = t+1; }}

counter controlsnumber of iterations

and comes inuseful

Page 120: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class challenge

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

calculating

baseexponent

Page 121: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

while ( t<n ){ t = t+1 ;}

t = 0;

private static double power (double x, int n){

}

Power method

return result;

result = result * x ;

result = 1;int t; double result;

Page 122: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Comparison operators

< less than <= less than or equal > bigger than >= bigger than or equal == equal to != not equal to

x=5 x becomes 5 !x==5 is x equal to 5 ?

Page 123: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Expressions

Expression with numeric value

Expression with text value

Expression with truth value

2 * (length + width)

“Hello ” + person

counter < exponent

type int

type boolean

type String

primitive

object-

primitive

Page 124: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Boolean expressions

Comparing values

Combining other Boolean expressions using logic operators && and || or ! not

x <= y

x<0 && y>0

! (x==0 && y==0) x!=0 || y!=0

George Boole

(1815-1864)

Page 125: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Constants

Constants with numeric value

Constants with text value

Constants with truth value

2

“Hello”

true

-5 137

“@#$%” “123” “”

false

“true”

Page 126: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Using Boolean expressions

As condition of a while statement

As right hand side of an assignment

As method result

while (x<10) ...

boolean b; b = x<10 ;

return x<10 ;

Page 127: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class challenge

Write a method divisible , which determines whether x is divisible by dprivate static boolean divisible (int x, int d){

}

x%d == 0return ; truth valueas a result

Page 128: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class challenge

Write a method smallestDivisor , whichdetermines the smallest divisor of xprivate static int smallestDivisor (int x){

}

int d;d = 2;

while ( ! divisible(x,d) ) d = d+1;

return d ;

try them all,one at a time

Page 129: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Changing variables

Shorthand notations:

x = x * 2 ;

old valuebecomesnew value

x = x * 2 ; x *= 2 ;

x = x + 5 ; x += 5 ;

x = x + 1 ; x += 1 ; x ++ ;

is multiplied by

is incremented with

is incremented

Page 130: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Repetition with a counter

int t ;

t = 0;while ( t<x )

t ++ ;}

{ // do something // useful with t

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

Page 131: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

for-statementinitialisation

int t ;for ( t=0 ; t<x ; t++ )

condition tocontinue

step to next

gr.drawString( “#”, 0, t*10 );

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

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

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

Page 132: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Repeated repetition

Body of a for-statement is a statementwhich may be a for-statement itself!

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

y

+ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + +

++ ++ + ++ + + ++ + + + ++ + + + + ++ + + + + + ++ + + + + + + ++ + + + + + + + +

Page 133: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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 statmentwill never be

executed!

Page 134: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Unintensional infinity

x=1;counter = 0;while (counter<10) x = x*2; counter = counter+1;{

}

forgot thebraces...

Page 135: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Compiler messages

Error messages variabele not declared missing semicolon ...

Warnings unreachable code statement has no effect while-statement doesn’t terminate

this warning istheoreticallyimpossible!

Page 136: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

The Halting-problem is unsolvable

boolean stops (String filename){ ....}

void clever (String filename){ while ( stops(filename) ) x++;}

Ha! What about this?

Not so!This method

solves it:

stops( “Clever.java” )

what is thevalue of:

?

Page 137: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

The Halting-problem is unsolvable

void clever (String filename){ while ( stopt(filename) ) x++;}

stops( “Clever.java” )

Two possibilities: “Clever” does stop

“Clever” doesn’t stop

...so stops returns true

...so clever hangs!

...so stops returns false

...so clever stops immediately!

contradiction!

thus, stops is impossible to write

Page 138: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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 or too generous: some viruses passed

irritating

dangerous

Page 139: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Example: interst rates

TextField -objectenfor user interaction

TextField-objectspossess an

ActionListener

Page 140: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public class Interest extends Applet implements ActionListener{ TextField startT, renteT;

public void init ( ) {...} public void paint (Graphics gr) { ... }

public void actionPerformed (...) { this.repaint(); }}

Outline of class Interest

object-variabels

re-defining Applet-methods

fulfillingimplements promise

Page 141: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public void init ( ){ startT = new TextField(“100”, 8 ); rateT = new TextField(“5”, 4 );

this . add(startT); this . add(rateT);

startT . addActionListener (this); rateT . addActionListener (this);}

Interest ’s method init

creation ofinteraction

components

setup ofuser interface

addition ofevent listeners

Page 142: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public void paint (Graphics g){

}

Interest ’s method paint

startT.getText()rate.getText()

start = Integer.parseInt( );rate = Integer.parseInt( );

for (year=0; year<=10; year++){ gr.drawString( “year:”+year + “amount:”+captial, ... );

}

capital = start;

captial *= (1 + 0.01*rate) ;

int start, rate, year; double capital;

Page 143: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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/yis a better approximation

Page 144: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

private static double sqrt (double x){

}

Sqrt method

double y;y = 1;

return y;

y = (y + x/y) / 2 ;while ( y*y != x )

does it stop?

mathematician:no, equality hold only in limiting case

programmer:yes, precision islimited

computer scientist:no, roundof errorsprohibit reaching astable state

while ( Math.abs (y*y - x) <0.000001 )

safer:

Page 145: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Structure of repetition

Initialisation

Repeated improvement

Use of result

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

captial*=(1+0.01*rate); y=(y+x/y)/2; total+=x;

gr . drawString (“”+captial);

return y;

sb . setValue ( total );

Page 146: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

DrawString or return?

gr.drawString (x, ...)result immediately visible

return x;result is returned to caller,who can decide what to do with it

more flexibleuseful for

for “simple” results

useful for “complicated” layout

Page 147: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Program constructions

Statements Assignment Call void-methode return-statement while- statement for- statement { ... } - grouping

Expressions Constant Variable Call methode Expression with

operators Expression with parenth. new-expression

to do to calculate

Page 148: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Program constructions

Declaration Local variable

for temporary use Object-variable

permanent part of object

Parameterfor passing values to methods

Type Primitive type

int double boolean

Object-type Color, String etc. TextField, Button etc. Applet, Hallo, etc.

states typeof variables

set of possible valuesof an expression

Page 149: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary ch.7

while-statement: repeating statements

while (x<1000) x = 2*x;

body is repeatedlyexecuted

while condition is valid

Page 150: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary ch.7

for-statement: repetition with a counter

int t ;

t = 0;while ( t<x )

t ++ ;}

{ // do something // useful with t

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

Page 151: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary program constructions

Statements Assignment Call void-method return-statement while-statement for-statement { ... } - grouping

Expressies Constant Variable Call method Expression with

operators Expression with parenth. new-expression

can be done can be calculated

Page 152: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary program constructions

Declaration Local variable

for temporary use Object variable

permanently part ofthe object

Parameterto pass values to amethod

Type Primitive type

int double boolean

Object type Color, String etc. TextField, Button etc. Applet, Hello, etc.

indicates variable type

set of possible valuesof a variable

Page 153: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Executing statements conditionally

statement is only executedwhen condition holds

statement is executed over and overwhile condition holds

if (temperature<0) gr.drawString(“It’s freezing!”, 10, 10);

while (temperature<0) temperature += 5;

Page 154: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Two alternatives

statement is only excecutedwhen condition doesn’t hold

if (temperatuur<0) gr.drawString(“It’s freezing!”, 10, 10);else gr.drawString(“It’s thawing.”, 10, 10);

Page 155: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Choice is a statementas any other

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

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

*n

*n

if-statements acts asbody of for-statement

one statementas a body,

so no bracesneeded

Page 156: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Multiple-statement body

braces group two statementsinto one

if (temperatuur<0) gr.drawString(“It’s freezing!”, 10, 10); gr.drawString(“Isnt’ that cold?”, 10, 20);

{

}

Page 157: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

More than two alternatives

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

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

else

if (age<4) tf.setText(“Free”);

else

if-statement as a wholeis body of else-part

if-statement as a wholeis body of else-part

Page 158: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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”);

tf.setText(“Full fare”);else tf.setText(“Senior”);

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

exeption to ruleto indent the body

Page 159: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

private String tariff(int age){

}

More than two alternatives

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

if (age<4) return “Free”;if (age<12) return “Railrunner”;if (age<65) return “Full fare”;return “Senior”;

return-statementends method body

Page 160: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Button b;public void init ( ){ radius = 100; b = new Button(“grow”); this.add(b); b.addActionListener(this);

Drawing circlesclass Cirkel extends Applet{

}

public void paint(Graphics gr){ gr.fillOval(150-radius,150-radius,2*radius,2*radius);}

int radius;public void init ( ){ radius = 100;

}public void actionPerformed(ActionEvent e){ radius += 10; this.repaint();}

implements ActionListener

Page 161: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Drawing circlesclass Cirkel extends Applet{

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);}

implements ActionListener

Page 162: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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 ofButton-object-references)

public void actionPerformed(ActionEvent e){ if ( e.getSource() == small ) radius -= 10; if ( e.getSource() == big ) radius += 10;

this . repaint();}

Page 163: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Secret drawingclass Secret extends Applet{

public void paint (Graphics gr){ 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);

}

boolean open;public void init (){ open = false;

}

if (open){

}

TextField pass;

pass = new TextField(20); this.add(pass); pass.addActionListener(this);}

Page 164: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Secret drawingclass Secret extends Applet implements ActionListener{ boolean open; TextField pass;

public void actionPerformed (ActionEvent e){

open = true; this . repaint();

}

if ( pass.getText() . equals (“geheim”) ){

}

pass . setVisible(false);

Page 165: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

operator == or method equals ?

== tests variable equality

equals tests String-contents equality

5

5

x

y

s

thoi

s

t

hoi

hoi

s

thoi

s

t

hoi

hoi

method for

String-objects

Page 166: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Min./max. thermometerclass Thermo extends Applet

{ ScrollBar meter; Button reset;

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);

int minimum, maximum;

minimum = 0; maximum = 0;

impelements AdjustmentListener, ActionListener

Page 167: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Min./max. thermometerpublic void paint (Graphics gr){ gr.drawString( “hoogste ” + maximum, 50,50); gr.drawString( “laagste ” + minimum, 50,70);}public void adjustmentValueChanged(AdjustmentEvent e){

this.repaint();}

maximum =

minimum =

if (waarde>maximum) waarde;if (waarde<minimum) waarde;

int waarde;waarde = meter.getValue();

Page 168: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Interaction components

ScrollBar sb; sb = new ScrollBar(

hv, value, step, range); sb.addAdjustmentListener(

...);

n = sb.getValue(); sb.setValue(n);

TextField tf; tf = new TextField(

width); tf.addActionListener(...)

;

s = tf.getText(); tf.setText(s); n = Integer.parseInt(s);

Page 169: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Conversion

From String to int

String s; int n;n = Integer.parseInt (s);

From String to double

String s; double d; d = Double.valueOf (s); Double dob; obd = dob.doubleValue ();

Page 170: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Graph-drawing program

graph of theparabola

solutions according toabc-formula

entered values abc

Page 171: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Design of class Parabola

declaration Objectvariables method init method actionPerformed method paint method zeroes method axes method graph method parabola

makes interface

converts a,b,c

“manages” drawing

do the actual

drawing

calculates ax2+bx+c

Page 172: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Parabola: initclass 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);

Page 173: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Parabola: actionPerformed

public void actionPerformed(ActionEvent e){

}

a =b =c =this.repaint ();

abox.getText()bbox.getText()cbox.getText()

Double.parseDouble( ); Double.parseDouble( );Double.parseDouble( );

Page 174: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Parabola: paintpublic void paint (Graphics gr){

}

zeroes

axes

graph

this .

this .

this .

(gr);

(gr);

(gr);

gr . setColor( Color.black );

gr . setColor( Color.red );

gr . setColor( Color.blue );

private void axes (Graphics gr){ gr.drawLine(0, 250, 500, 250); gr.drawLine(250, 0, 250, 500);}

Page 175: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Parabola: zeroespublic void zeroes (Graphics gr){

}

gr.drawString( (-b -root)/denomin + “ and ” +(-b+root)/denomin , 50, 50 );

root = Math.sqrt(discriminant);

discriminant = b*b - 4*a*c;denomin = 2*a;

if (discriminant<0) gr.drawString(“geen nulpunten”);else{

}

-b ± b2-4ac

2a

Page 176: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Parabola: graphpublic void graph (Graphics gr){

}

for ( x=0 ; x<500 ; x++ ){

}

y = this.parabool( x );

gr.drawLine( , , x, y );x-1 oldyoldy = y;

oldy = 0;

if (x>0)

scale = 0.03;

xw = scale * x ; w wy = yw / scale ;

( -250)

(int) (250-( ))

int x, y,oldy; double xw, yw, scale;

Page 177: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary lecture 5

if-statement if-else-statement

compare int with compare String with

x==y

s.equals(t)

Page 178: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary ch. 8

if-statement if-else-statement

compare integers with compare Strings with

x==y

s.equals(t)

Page 179: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Min./max. thermometerclass Thermo extends Applet

{ ScrollBar meter; Button reset;

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);

int minimum, maximum;

minimum = 0; maximum = 0;

implements AdjustmentListener, ActionListener

Page 180: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Min./max. thermometerpublic void paint (Graphics gr){ gr.drawString( “hoogste ” + maximum, 50,50); gr.drawString( “laagste ” + minimum, 50,70);}public void adjustmentValueChanged(AdjustmentEvent e){

this.repaint();}

maximum =

minimum =

if (waarde>maximum) waarde;if (waarde<minimum) waarde;

int waarde;waarde = meter.getValue();

Page 181: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

All aboutobjects and classes,

in one picture...

Page 182: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Program

statements

methods

class

variables

and Memory

objects

classclass

grouped in

grouped in

grouped in

have as type

change

treat

Page 183: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class-definition

Description of methodseach consisting ofstatements

Description of objectsby declaration ofvariables

treat

class Counter ...{

... init(){

}

... actionPerformed(){

}

... paint(...){}

}

Button b;int t;

b = new Button();t = 0;

g.drawString(t...);

t = t+1;this.repaint();

Page 184: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

x

Declaration

Declaration allocates space in memory For a primitive value

For an object reference

int x;

x = 5;

ScrollBar s;s = new ScrollBar(...);

5

s

as describedin class

Scrollbar

Page 185: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Creation of new objects

Objects having a library class as type

Scrollbar s;s = new Scrollbar(...);

type ofdesired object

Objects having ahome-made class as type

Thermo t; t = new Thermo( );

this is doneby the browser

t . init ( );t . paint (...);

Page 186: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Creation of objects

Structure of the objectis described in the class

meter

min max

Thermo

browser’scurrentapplet

inherited

declared in the class

class Thermo

{

}

Scrollbar meter;int min, max;

// methods...

extends Applet

Page 187: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

meter

min max

Thermo

browser’scurrentapplet

Call of init

reset

this

Scrollbar

Button

00

public void init ( ){

}

Button reset;min = 0; max = 0;meter = new ScrollBar(...);reset = new Button(...);

Page 188: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Call of init

meter

min max

Thermo

browser’scurrentapplet

reset

this

Scrollbar

Button

00

}

this . add(meter);this . add(reset);reset . addActionListener(this);meter . addAdjListener(this);

added

adjListener

actListener

0 value

reset = new Button(...);

Page 189: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Situation aftercompletion of init

meter

min max

Thermo

browser’scurrentapplet

Scrollbar

Button

00

added

adjListener

actListener

0 value

Page 190: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Classes and objects

Class definition in libraryObject creation with new

Class definition in programObject creation by browser

Class definition in programObject creation with new

Thermo

Scrollbar

Space

Page 191: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Example: simulation of moving particles in a spaceSimulation -

object

Button -objects

Space -objects

Particle -objects

Page 192: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class Simulationpublic class Simulation extends Applet{

Button step, auto;Space r1, r2, r3;

public void init ( ){ stap = new Button (“step”); auto = new Button (“start”); r1 = new Space(...); r2 = new Space(...); r3 = new Space(...); ...}

}

ClassSpace

yet to be defined!

Page 193: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class Space

private class Space

{

}

Space is an extension of an

existinginteraction objectextends

Canvas

Particle d1, d2, d3;

// methods to be defined

every Space objecthas three Particleobjects of its own

Page 194: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class Particle

private class Particle

{

}

Particle is not extending

anything

int x, y;

// method to be defined

position ofthe Particle

int dx, dy; Color col;

velocity of the Particle

Page 195: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

browser’s currentapplet

Objects

Simulation

r1 r2 r3

stap

auto

d1 d2 d3

Space

d1 d2 d3

Space

x

y

dx

dy

col

Particle

x

y

dx

dy

col

Particle

x

y

dx

dy

col

Particle

x

y

dx

dy

col

Particle

x

y

dx

dy

col

Particle

x

y

dx

dy

col

Particle

d1 d2 d3

Space

Button

Button

x

y

dx

dy

col

Particle

x

y

dx

dy

col

Particle

x

y

dx

dy

col

Particle

inherited form Applet

declared in the class

inherited from Canvas

Page 196: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Construction of a new object

Allocate memory

Call constructor method

new expression does two things:

value is reference to the new object

r1

d1 d2 d3

Space

100 196

which can be stored

r1 = new Space ( ... ) ;

Page 197: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

private Space ( ){

}

Constructor method

private class Space extends Canvas { Particle d1, d2, d3;

}

int width, int height

name is sameto that of the class

no resulttype!

inherited from

Canvas

this . setBackground (Color.gray);d1 = new Particle (...);d2 = new Particle (...);d3 = new Paticle (...);

this . setSize (width,height);

Page 198: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

private class Particle {

}

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 )

{...}

Page 199: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

private class Particle {

}

Methods of 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 );}

Page 200: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

private class Particle {

}

Methods of 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) { ... }

Page 201: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

private class Particle {

}

Methods of class Particle

int x, y, dx, dy; Color col;

public Particle (Color k, ){ col = k; maxx = maxy =}

Space r

r . getSize( ) . width;r . getSize( ) . height;

int maxx, maxy;

Page 202: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary of classes

class Simulation extends Applet impl ActList init actionPerformed

class Space extends Canvas Space paint

class Particle Particle setPos, setVelo, doStep, draw

Page 203: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public class Simulation extends Applet impl ActionListener {

}

Methods of class Simulation

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);

Page 204: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

public class Simulation extends Applet impl ActionListener {

}

Methods of class Simulation

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 ();

Page 205: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

private class Space extends Canvas {

}

Methods of class Space

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); ...}

Page 206: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

private class Space extends Canvas {

}

Method of class Space

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);}

Page 207: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Animation

Animationprogram shows changing picturesautomatically

Easily programmed using library class

Thread

“thread”of events

which occur,simultaneously

with other threads

Page 208: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Programming animations

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

calls run of the object

that was passedto the constructor

Thread animation;animation = new Thread ( this );

and returnsimmediately

(even when run is still running)

Page 209: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Method run

class Simulation extends Applet{

}

implements Runnable

public void run ( ){

}

while (true)this . doStep ( );{

}

Thread . sleep (50);try{ Thread . sleep (50); }catch (Exception e){ }

infinite repetition!

millisecondsmilliseconds

Page 210: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

if (moving){ auto . setLabel (“Start”); moving = false;}else{

}

Starting the animation

public void actionPerformed (ActionEvent e){

}

if (e.getSource ( )==auto){

}else this . doStep ( );

animation = new Thread(this);animation . start ( );auto . setLabel (“Stop”); moving = true;

Page 211: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Method run revisited

class Simulation extends Applet{

}

implements Runnable

public void run ( ){

}

while (true)this . doStep ( );{

}

try{ Thread . sleep (50); }catch (Exception e){ }

oneindige herhaling!

while (moving)

finite repetition.

Page 212: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

if (beweging){ auto . setLabel (“Start”); beweging = false;}else{

}

Starting the animationrevisited

public void actionPerformed (ActionEvent e){

}

if (e.getSource ( )==auto){

}else this . doStep ( );

animatie = new Thread(this);animatie . start ( );auto . setLabel (“Stop”); moving = true;

(animation != null )animation = null;

Page 213: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

The value null

null : reference to nothing

x = null;

x

null is a valid valuefor each object reference type

Page 214: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

and use

What is object?declarations of object variables

Wat can you do with the object?method headers

How is it done?method bodies

Class design

Page 215: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Ways to design classes

Top-downstart with the most complicated classusing classes and methods which areyet to be written

Bottom-upstart with the simplest classcreating a library of methodswhich come in useful writingthe other classes

Page 216: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Summary ch. 9

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

Animation

Thread a;a = new Thread(this);a . start ( );

public void run ( ){ while (true) { this . doStep (); Thread . sleep(50); }}

Page 217: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Useful classes (1/4)

Things from reality String

length, equals, substring, concat Color

Color, red, green, blue, black, white Dimension

Dimension, getWidth, getHeight

Page 218: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Useful classes(2/4)

Computer related things BufferedImage

setRGB, getRGB, getGraphics AudioClip

play, stop, loop File

getName, getDirectory, exists, delete

Page 219: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Useful classes(3/4)

Objects that can do something for you Graphics

drawLine, fillRect, setColor StringTokenizer

nextToken, hasMoreTokens

Page 220: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Useful classes(4/4)

Interaction componentento use

ScrollBar Button TextField TextArea Label CheckBox

to extend Applet Canvas Frame

Page 221: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

problems withversion management

Extending previous work

First try: “cut&paste”class Two{ int x, y;

int old ( ) { return x+y; }}

class Twee{ int x, y;

int old ( ) { return x+y; }

}

int z;

int extra ( ) { return x+y+z; }

Three

+1;

Page 222: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

assymmetrical

clumsy

Extending previous work

Second try: “delegation”class Two{ int x, y;

int old ( ) { return x+y; }}

class Twee{ Twee t;

int old ( ) { return t.old(); }

}

int z;

int extra ( ) { return t.x+t.y+z; }

Three

Page 223: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Extending previous work

Third try: “subclasses”class Two{ int x, y;

int old ( ) { return x+y; }}

class Twee extends Two{

}

int z;

int extra ( ) { return x+y+z; }

Three

Page 224: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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

Page 225: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Inheritance

Objects of a subclassinherit variables and methodsof the superclass

meter

min max

Thermo

inhertited

declaredby yourself

Page 226: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Superclasses in standard packages

Applet extends Panel Panel extends Container

superclass

super-superclass

Page 227: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Inherited methods

Applet inherits add from class Container

and manymany more...

Page 228: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class hierarchies

Van

Car MotorBike

MotorVehicle Bicylce

Vehicle Plane

SteamBoat

MotorBoat SailBoat

Boat

Transporter

design:medium precedes

motorization

design:motorbike is moremotor than bike

Page 229: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class hierarchies

Vehicle Boat

Transporter

class Vehicle extends Transporterclass Boat extends Transporter

“is a”

Page 230: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class hierarchy in AWT

Applet

FileDialog

Frame Dialog

Panel Window TextArea TextField

Button Container Canvas Label TextComponent Scrollbar

Component

Button is a Component Applet is also a Component

(more precicely, a Container, and even a Panel)

Page 231: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Not every hierarchy isa class hierarchy

d1Particle

d2Particle

d3Particle

d1Particle

d2Particle

d3Particle

d1Particle

d2Particle

d3Particle

stepButton

autoButton

r1Space

r2Space

r3Space

browser's currentSimulatie

“has a”

Page 232: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Classes vs. Interfaces

Class:Group of methods and declarations

Interface:Group of method headers

“wish list”to be implemented

by another class

Page 233: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

“Interface” in 3 readings

Hardware:connectors are the“face” of the computer

Software:buttons are the“face” of the software

Programming:methods are the“face” of the program

class Hallo implements ActionListener {

“GUI”

Page 234: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Interface hierarchy in AWT

Action-Listener

Adjustment-Listener

Component-Listener

Mouse-Listener

Event-Listener

Page 235: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class hierarchy in AWT

ActionEvent AdjustmentEvent

KeyEvent MouseEvent

InputEvent FocusEvent

ComponentEvent

AWTEvent

EventObject

Page 236: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Everything in one hierarchy

String Component EventObject Image

Object

Methods in class Object : toString redefinable in a subclass clone makes exact copy

Page 237: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

TextArea and String

class SymCount extends Applet

{

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);}

TextArea input; TextField output; Button count;

implements ActionListener

Page 238: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Useful classes (1/4)

Things from reality String

length, equals, substring, concat Color

Color, red, green, blue, black, white Dimension

Dimension, getWidth, getHeight

Page 239: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Useful classes(2/4)

Computer related things BufferedImage

setRGB, getRGB, getGraphics AudioClip

play, stop, loop File

getName, getDirectory, exists, delete

Page 240: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Useful classes(3/4)

Objects that can do something for you Graphics

drawLine, fillRect, setColor StringTokenizer

nextToken, hasMoreTokens

Page 241: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Useful classes(4/4)

Interaction componentento use

ScrollBar Button TextField TextArea Label CheckBox

to extend Applet Canvas Frame

Page 242: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

problems withversion management

Extending previous work

First try: “cut&paste”class Two{ int x, y;

int old ( ) { return x+y; }}

class Twee{ int x, y;

int old ( ) { return x+y; }

}

int z;

int extra ( ) { return x+y+z; }

Three

+1;

Page 243: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

assymmetrical

clumsy

Extending previous work

Second try: “delegation”class Two{ int x, y;

int old ( ) { return x+y; }}

class Twee{ Twee t;

int old ( ) { return t.old(); }

}

int z;

int extra ( ) { return t.x+t.y+z; }

Three

Page 244: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Extending previous work

Third try: “subclasses”class Two{ int x, y;

int old ( ) { return x+y; }}

class Twee extends Two{

}

int z;

int extra ( ) { return x+y+z; }

Three

Page 245: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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

Page 246: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Inheritance

Objects of a subclassinherit variables and methodsof the superclass

meter

min max

Thermo

inhertited

declaredby yourself

Page 247: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Superclasses in standard packages

Applet extends Panel Panel extends Container

superclass

super-superclass

Page 248: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Inherited methods

Applet inherits add from class Container

and manymany more...

Page 249: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class hierarchies

Van

Car MotorBike

MotorVehicle Bicylce

Vehicle Plane

SteamBoat

MotorBoat SailBoat

Boat

Transporter

design:medium precedes

motorization

design:motorbike is moremotor than bike

Page 250: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class hierarchies

Vehicle Boat

Transporter

class Vehicle extends Transporterclass Boat extends Transporter

“is a”

Page 251: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class hierarchy in AWT

Applet

FileDialog

Frame Dialog

Panel Window TextArea TextField

Button Container Canvas Label TextComponent Scrollbar

Component

Button is a Component Applet is also a Component

(more precicely, a Container, and even a Panel)

Page 252: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Not every hierarchy isa class hierarchy

d1Particle

d2Particle

d3Particle

d1Particle

d2Particle

d3Particle

d1Particle

d2Particle

d3Particle

stepButton

autoButton

r1Space

r2Space

r3Space

browser's currentSimulatie

“has a”

Page 253: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Classes vs. Interfaces

Class:Group of methods and declarations

Interface:Group of method headers

“wish list”to be implemented

by another class

Page 254: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

“Interface” in 3 readings

Hardware:connectors are the“face” of the computer

Software:buttons are the“face” of the software

Programming:methods are the“face” of the program

class Hallo implements ActionListener {

“GUI”

Page 255: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Interface hierarchy in AWT

Action-Listener

Adjustment-Listener

Component-Listener

Mouse-Listener

Event-Listener

Page 256: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class hierarchy in AWT

ActionEvent AdjustmentEvent

KeyEvent MouseEvent

InputEvent FocusEvent

ComponentEvent

AWTEvent

EventObject

Page 257: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Everything in one hierarchy

String Component EventObject Image

Object

Methods in class Object : toString redefinable in a subclass clone makes exact copy

Page 258: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

TextArea and String

class SymCount extends Applet

{

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

TextArea input; TextField output; Button count;

implements ActionListener

Page 259: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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 ( )

Page 260: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

concat and substring

String s, t, u, v, w;

s = “ham”; t = “burger”; u = s.concat(t); v = u.substring(3);

w = u.substring(3, 7);

s t u v w

ham burger

hamburger

burger

burg

hamburger012345678

s + t ;

“from andincluding”

“up to, butnot including”

Page 261: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class challenge

Write a method startsWithhaving two String-parameters x and ythat determines whetherx is the initial part of y

Write a method containshaving two String-parameters x and ythat determines whetherx occurs anywhere inside y

Page 262: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Method startsWith

(String x, String y)

boolean

private static

part whole

{

}

y . substring

(0, x.length() ) x . equals (

)

return

;

startsWith

Page 263: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Methode contains

(String x, String y)

boolean

private static{

}

contains

y . substring(t)

startsWith(x, )if ( ) return true;

for (t=0; t<y.length(); t++)

return false;

int t;

Page 264: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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 ;}

Page 265: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Stand-alone characters

String substring (int begin, int end)

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

charcharAt (int position)

char first;first = s . charAt(0);

Page 266: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Primitive types

intwhole numbers -17, -5, 0, 3, 178

doublereal numbers 3.141, 2.0, -1.5E8

booleantruth values false, true

charsymbols ’A’, ’B’, ’Z’, ’a’, ’4’, ’#’, ‘:’

Page 267: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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

Page 268: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Count symbol frequency

private static int freq(String s, char x){

s.charAt(t)==x

for (t=0; t<s.length(); t++)

if ( ) count++;

int count, t;count = 0;

return count;}

Page 269: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

IBM/DOS

History of char

1970s: 6 bits = 64 symbols26 letters, 10 digits, 28 punctuation

1980s: 7 bits = 128 symbols+26 lowercase, +5 punct., 33 control

1990s: 8 bits = 256 symbols+letters with diacriticals

2000s: 16 bits = 65536 symbols+Greek, Cyrillic, Japanese,

Devangari, ...

ASCII

ANSI/ISO

Unicode

Page 270: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Character coding

bs tab lf cresc

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

code 0

code 127

code 48

code 32

code 65

code 97

Page 271: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

char specials

alfabetically orderedchar c;if ( ’A’<=c && c<=’Z’ ) …

convertable to intint n;n = c + 32;

and backc = (char) n;

Page 272: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Conversions Conversion to “larger” set

is always possible

double d; int n;d = n;

int n; char c;n = c;

Component x; Button b;x = b;

Conversion to “smaller” setis dangerous

n = (int) d;

c = (char) n;

b = (Button) x;

Page 273: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

two symbols in the source,representing one character

Special char values

Literal symbool

Special symbol

The quote symbol

The backslash symbol

’A’

’\n’

’\’’

’\\’

’&’

’\t’

’\”’

Page 274: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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 +

Page 275: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Counting words

void actionPerformed ( ActionEvent e ){ String s; int n; s = input.getText ();

}

n = s.length ();

output.setText ( “you typed ” + n + “ symbols” );output.setText ( “you typed ” + w + “ words” + “on ” + r + “ lines” );

if (s . charAt(t)==‘ ’) w++;

for ( t=0; t<s.length(); t++ )

if (s . charAt(t)==‘\n’) { r++; w++; }{

}

w = 0; r = 0;

int w, r, t;

Page 276: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Counting wordsvoid actionPerformed ( ActionEvent e ){ String s; int n; s = input.getText (); w=0; r=0; for (t=0; y<s.length(); t++) { if ( s.charAt(t)==‘ ’) w++; if (s.charAt(t)==‘\n’) r++; } output.setText( (w+r) + “ words on ” + + r + “ lines” );}

the actualcounting

input

output&

layout

Page 277: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Separate class for doingthe countingclass 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”;}

Page 278: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Using the new class

void actionPerformed(ActionEvent e){

}

Counters c;c = new Counters();c . check ( input.getText() );output . setText ( c.toString() );

Page 279: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Counting digitsclass 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;}void check (String s){ 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++; if (s.charAt(t)==‘6’) t6++; if (s.charAt(t)==‘7’) t7++;

OK, OK,I got it...

Page 280: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Arrays

Array: many numbered variables

table

0

1

2

3

4

length5

int [ ] table;

new int [5];

table =

declaration ofthe array

creation ofthe object

Page 281: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Use of an array

all the variables can be actually used:

table

0

1

2

3

4

length5table [2] = 37;

x = table [2] + 5;

37

x 42

if (table.length<10) ...

table.length = 10;

but you cannot changethe length

Page 282: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Use of an array

variable as an index into the array

table

0

1

2

3

4

length5table [0] = 0;table [1] = 0;table [2] = 0;table [3] = 0;table [4] = 0;

0

0

0

0

0

table [t] = 0;for (t=0; t<5; t++)

Page 283: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Array as a parameter

table

0

1

2

3

4

length5

12

95

11

23

15

int smallest ( int [ ] table ){

}

int result;

return result;

if (table [t] < result)result = table [t];

for (t=0; t<table.length; t++)

int t;

result =table [0];

Page 284: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Application:character counter

user types some text...

presses the button...

and the programdetermines all

character frequencies

Page 285: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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);

}

Page 286: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

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() );

}

Page 287: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class Counters

public class Counters{

int [ ] tab;int total;

public Counters ( ) { ... }public void check (String s){ ... }public String toString ( ) { ... }

private void check (char c){ ... }

}

class design:what is ...

& what does ...& how?

Page 288: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class Counterspublic class Counters{ int [ ] tab; int total;

public Counters ( ){

}

tab = new int [26];

}

for (t=0; t<26; t++) tab [t] = 0;

int t;

public void check (String s){

}check (s.charAt(t));

for (t=0; t<s.length(); t++)int t;

Page 289: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

Class Counterspublic class counters{ int [ ] tab; int total;

public void check (char c){

}

tab [ ] ++;total++;

}

if (c>=‘A’ && c<=‘Z’){

}

c - ‘A’

if (c>=‘a’ && c<=‘z’){ tab [ c - ‘a’ ] ++; total++;}

Page 290: Imperative programming nVon Neumann’s computer model: computer = + memoryprocessor to store values to execute instructions

t + “:” + tab[t] + “times\n” ;

Class Counterspublic class Counters{ int [ ] tab; int total;

public String toString( ){

}}

String result;

return result;

result = “”;

result +=for (t=0; t<26; t++)

int t;

result += “total:” + total;

(t+ ‘A’) + “:” + tab[t] + “times\n” ;

(char) (t+ ‘A’) + “:” + tab[t] + “times\n” ;