welcome to comp1100!courses.cecs.anu.edu.au/courses/old/comp1100.2015/lectures/prev… · class...
TRANSCRIPT
Welcome to COMP1100!
COMP1100: Introduction to Programming and Algorithms
Handouts: (pls. collect from down the front):
COMP1100-2004-01: General Information
COMP1100 Lecture 1: Introduction 2004 JJ J • I II × 1
Course Organisation
Fundamental Programming Concepts COMP1100: Introduction to Programming and
Algorithms is organized into 3 modules:
module lectures tutes/labs assignments1 Fundamental Programming Concepts 1–15 1–8 1–22 Data Representation & Algorithms 16–20 93 Advanced Programming Concepts 21–30 10–13 3
which will address the Major Computing Ideas:
● Imperative (or procedural) programming concepts (modules 1 & 2)
● Object-Oriented concepts (modules 1 & 3)
The course staff are:
Dr Peter Strazdins, Co-ordinator, Lecturer (module 1)Mr John Zigman, Course Tutor, Lecturer (module 2)Prof Tom Gedeon, Lecturer (module 3)
COMP1100 Lecture 1: Introduction 2004 JJ J • I II × 2
Course Information Sources
● web page: http://cs.anu.edu.au/Student/comp1100
■ includes web-based Announcement Board & Discussion Board
● handouts:
■ includes documents for tutes/lab exercises and assignments■ hardcopies distributed at lectures■ softcopies from the course web page
● reading: (more info from COMP1100 web page)
■ Lewis & Lofus, Java Software Solutions (regular text)or:
David D. Riley, The Object of Java (experienced/SE interest text)
Highly recommended:
■ Robertson, Simple Program Design (algorithm development material)
● Auxiliary Material (‘course brick’):
■ Student Computing Environment: User Guide■ Department of Computer Science Handbook
COMP1100 Lecture 1: Introduction 2004 JJ J • I II × 3
Course Activities
● Lectures: (A) 12:00 Mon, (B) 12:00 Tue & (C) 13:00 Thu (all in MCC LT1)
■ 30 lectures, concentrated in the first half of the semester
● Tutorial/Laboratory Sessions:
■ 1 × 2 hr session per week
■ starts in week 1! (Orientation Exercise) (Handout: Tues wk 1 lecture)
◆ need the Student Computing Environment: User Guide (from course ‘brick’)
◆ may however ‘sit-in’ on any session (week 1 only!)
■ please register on-line ASAP for one session via StReaMS
(http://cs.anu.edu.au/streams)
◆ use your university username and PAC to log in
◆ 3 categories: Advanced, CSmajors, & regular
◆ please chose appropriately; see COMP1100 Web Page
COMP1100 Lecture 1: Introduction 2004 JJ J • I II × 4
Proposed Assessment Scheme
● the Continuous Assessment (CA) component consists of a Tute/Lab mark (10%)plus assignments, having the draft schedule:
Assignment weighting due end of:1 0% week 32 30% week 63 30% week 94 30% week 12
● the Exam Component (EX ) consists of a Mid-Semester Exam (35%, week 8),redeemable in the first part of the 3-hour Final Exam
● from these a raw score (which may then be scaled) is calculated:
S =
{
(CA + EX )/2 , if |CA−EX | ≤ 2010 + min(CA,EX ) , otherwise
● motivations: (see Assesment Web Page for more details)
■ tutorial/laboratory attendance is important!■ Mid-Semester Exam to give more experience in exam-taking■ practical and theoretical skills are both important!
COMP1100 Lecture 1: Introduction 2004 JJ J • I II × 5
Course Objectives
(from the Course Description Web Page)
After completion of the course, the student will be:
● able to describe the main concepts of object-oriented programming,
● able to read and comprehend a straightforward Java program,
● able to write a report on the essential aspects of a straightforward Java program,
● able to write, debug and test a moderate-sized Java program, given an informal
program design.
● able to the essentials of straightforward algorithms for searching and sorting.
● proficient in the use of the CSIT Student Computing Environment,
COMP1100 Lecture 1: Introduction 2004 JJ J • I II × 6
Why learn programming? Why learn about algorithms?
● because programming languages are the languages of communication between
people and computers
●
●
COMP1100 Lecture 1: Introduction 2004 JJ J • I II × 7
Why Java?
● COMP1100:
■ is called Introduction to Programming and Algorithms, not Java Programming!■ it emphasises principles, techniques, guidelines to good program design
applicable in any programming language
● having said that, Java:
■ is a modern object-oriented programming language■ standardized, highly-developed libraries (including graphics)■ highly portable and widely supported■ excellent supporting technologies■ high industry relevance; also related to C#, C++ and C
◆ widespread in internet, multimedia, and now even science & engineeringapplications
◆ Java-related technologies are also widespread
however, this means you will need to put in extra effort to learn it:
■ it is big■ it has some awkward features / pitfalls, eg. public static void main(...)
COMP1100 Lecture 1: Introduction 2004 JJ J • I II × 8
Software Engineering Context
● in the “real world”, software systems can be large entities:
lines people timetrivial 100 1 2-5 dayssmall 1,000 1-2 1 month
medium 10,000 2-5 1 yearlarge 100,000 5-20 3 years
very large 1,000,000 100-1000 4-5 yearsextremely large 10,000,000 2000-5000 5-10 years
individual productivity: from 5000 (medium) to 500 (x. large) lines of code / year
● for medium+ systems, software construction requires an organised process
● the standard engineering process has been adapted to the software domain:
■ specification of important characteristics
■ design of all relevant details
■ construction (implementation) of software
The object-oriented approach is claimed to be applicable to all 3 phases.
COMP1100 Lecture 1: Introduction 2004 JJ J • I II × 9
● Software systems are required to be
■ reliable (correct)
■ reusable (in part)
■ modifiable
● software is seductively easy to change. Because it can be changed it is often
required to change!
● the object-oriented approach to software construction (Eiffel, C++, Java, SmallTalk,
Simula 67) is claimed to provide systems that can be safely modified.
■ in particular, it permits a high degree of software re-use
● programmers of small systems will hardly notice the difference
COMP1100 Lecture 1: Introduction 2004 JJ J • I II × 10
How to succeed in COMP1100
Our assumptions
● no particular computing skills
● no particular programming skills
● commitment to involvement in course (particularly Tutes/Labs)
Factors contributing to success in COMP1100
● doing all the work and understanding what you have done
● willingness to reread and think about difficult or new concepts
● seeking help when you need it
● ability to think analytically
● ability to apply concepts to appropriate situations
● ability to generalise facts into concepts
COMP1100 Lecture 1: Introduction 2004 JJ J • I II × 11
Variety of student computing backgrounds
● COMP1100 moves too fast
■ diagnostic quizzes
■ some review lectures
■ office hours for individual help (TBA)
● COMP1100 moves too slow
■ note that we get through the Fundamental Programming Concepts in 6 weeks!
■ lecture attendance can considered optional, if you feel you already understand
the topics covered
◆ check the Lectures page for schedule & corresponding 2003 lectures
◆ please attend the first (introduction) & last lectures (surveys) though
■ ‘streaming’ of Tutes/Labs and texts
◆ note that 2004 is a ‘transition year’ for the course (‘streaming’& use of GUI)
COMP1100 Lecture 1: Introduction 2004 JJ J • I II × 12
An Example Program: Pool.java
import au.edu.anu.cs.TextStreamWriter; // local package for formatted printing
public class Pool {
/* calculate and report the volume of a pool */public static void main(String[] args) {
// define the dimensions of the pool (in meters)double length = 25.0;double width = 10.0;double depth = 1.5;double volume; // (in cubic meters)
// calculate the volume of the poolvolume = length * width * depth;
// report the volume of the poolTextStreamWriter.out.print("Pool volume : ");TextStreamWriter.out.print(volume, 0, 1);TextStreamWriter.out.println();
}}
Handouts: OMP1100-2004-02: Notes for Laboratory Session 01
COMP1100 Lecture 2: Program Execution, Objects and Variables2004 JJ J • I II × 1
Modes of Program Execution
● a computing machine executes commands or instructions
● there are two distinct modes in which it may do this:
command-response: once-off task ;
simple task
current command
USER
machinecommand response
characteristics:
■ interpreted - each instruction is
translated each time it is carried out
■ convenient while program is under
development: whole program need to
be translated if change a line
■ slower for ‘production’ runs, or when
an instr’n is executed many times
stored-program: task performed many
times; complex task
current command
machine
program store
characteristics:
■ compiled - whole program is
translated first before execution
■ more efficient for working programs
since all instr’ns are translated once
COMP1100 Lecture 2: Program Execution, Objects and Variables2004 JJ J • I II × 2
Execution of Java Programs
● Java programs are compiled into a standard format called bytecodes
■ eg. Pool.javajavac
−→Pool.class
● when run, the bytecode (.class) files are normally interpreted (bytecodes are
translated one at a time)
■ eg. the command java Pool loads Pool.class into the Java interpreter java
(a stored program)
■ it looks for the (public) main() method in Pool.java and interprets from
there
■ the output is: Pool volume : 375.0
● however, modern Java interpreters can compile frequently used sections of
bytecodes into fragments of (machine-executable) instructions
■ known as JIT (Just-in-time) compilation
■ permits Java programs to (almost) have the speed of stored program execution
COMP1100 Lecture 2: Program Execution, Objects and Variables2004 JJ J • I II × 3
Objects – a Brief Introduction
● an object in a program represents or models a real-world object of interest to the
application
■ real-world objects can be extremely complex
■ corresponding program objects are simplified: only represent those aspects
relevant to the particular application
● examples:
■ in a university, real-world objects of interest would include students and courses
■ in a computer application to handle enrolment in courses, you would create a
student object to represent each real student
■ a bank would be interested in customers and accounts
■ in an account management application, an account object would be created to
represent each actual account
COMP1100 Lecture 2: Program Execution, Objects and Variables2004 JJ J • I II × 4
Classes – a Brief Introduction
● a class definition provides a template or a ‘mold’ for objects which are similar, which
are characterised by the same features.
■ specifies the attributes of objects belonging to the class
■ also defines what kinds of actions can be performed on the objects
● examples:
■ Each real-life student is a different individual, but for the purposes of the
enrolment application, we need to know the same kinds of things for each
student
■ each bank account is represented in a banking application with similar kinds of
data.
COMP1100 Lecture 2: Program Execution, Objects and Variables2004 JJ J • I II × 5
Objects in Java
● in Java, ‘everything’ is an object
● each object ‘belongs to’, or is an instance, of some class.
● an object is created from the relevant class definition.
● for the next few lectures, we will be using mainly the primitive classes (primitive
data types)
■ eg.: int, char, boolean, double
■ correspond to simple types available in most programming languages
■ objects of these classes correspond to simple variables in other programming
languages
COMP1100 Lecture 2: Program Execution, Objects and Variables2004 JJ J • I II × 6
Summary: Objects and Classes
● class extends the idea of type;
object extends the idea of variable
● an object is an instance of a class (as a variable is an instance of a type)
● the class definition describes both the data structure and the operations that can be
performed on the data
● an object is created (made, instantiated) using the template given in the class
definition
● an object in a program represents real-world objects of interest to the application
● a class describes the relevant features of similar objects
COMP1100 Lecture 2: Program Execution, Objects and Variables2004 JJ J • I II × 7
Variables and Assignment
● in the Pool program:
■ before the calculation of volume:length: 25.0 width: 10.0 depth: 1.5volume: 0.0
■ after:length: 25.0 width: 10.0 depth: 1.5volume: 375.0
● upon variable declaration:
■ storage space is allocated in memory for a value of the appropriate type■ it is ‘labelled’ with the name of the variable■ the variable is initialised
◆ if no value is given, the default value of the type is used (normally zero)
● in an assignment statement, a new value can be given to the variable
■ the expression (to the right of the ‘=’) is evaluated to provide the new value■ as there is room for exactly one value, the old value is lost■ what if the following was inserted: volume = 2.0 * volume; ?
COMP1100 Lecture 2: Program Execution, Objects and Variables2004 JJ J • I II × 8
Ref: L&L pp 34–6, Riley sect. 3.2
● identifiers are labels or names for various things in a program
■ e.g. variables, constants, class names, objects, routines (functions, procedures)
● a valid identifier must start with a letter, and be made up of only letters, digits and
the underscore character (’_’)
● reserved words (eg. public, int) may not be used as identifiers
■ for complete list, see L&L Fig 1.19 (Riley Fig 3.5)
● coding style:
■ class names begin with a capital letter; variables and routines (object attributes)
begin with a lower case
◆ ’_’ should be avoided
◆ all other letters are lower case, except:
◆ multiword identifiers: 1st letter of 2nd, 3rd, . . . words are capitals
■ constants are normally all in uppercase
◆ for multiword identifiers: words are joined by an ’_’
COMP1100 Lecture 3: Identifiers and Expressions 2004 JJ J • I II × 1
Assignment Statements
Ref: L&L sect 2.3, Riley sect. 2.4–2.5
● e.g. volume = length * width * depth;
● the right-hand side is an expression
● the left-hand side is a variable (with associated storage cell)
● read this statement as
■ the value of length times width times depth is assigned to volume”
● these statements are executed:
■ the expression is evaluated, yielding some value x
■ the storage cell of the variable is given the value x
■ assignment statements are not equations
◆ e.g. length = length + 1.0;
● they may also appear upon variable declarations
COMP1100 Lecture 3: Identifiers and Expressions 2004 JJ J • I II × 2
Constants (of Primitive Data Types)
● these include literal constants: numbers or strings appearing in the program text
■ e.g. 25.0, -17, false, ’a’ (char), "the answer is:"
● and include symbolic constants, where we wish to give a name to a value
(having a particular meaning)
■ this is done by adding the final keyword to a variable declaration with an
initializer
■ e.g. in Pool.java, we could have used final double length = 25.0;
■ subsequent assignments, e.g. length = length + 1.0; would be disallowed
● note the coding style to use uppercase letters
● symbolic constants also have an associated storage allocated, as for variables:
■ eg. final double LITRES_PER_CUBIC_METRE = 1000.0;
LITRES_PER_CUBIC_METRE: 1000.0
■ however, its value may not be changed
COMP1100 Lecture 3: Identifiers and Expressions 2004 JJ J • I II × 3
Expressions: floating point type
Ref: L&L sect 2.4–2.5, Riley sect. 5.1–5.2
● given the declarations double x, y;,
the following expressions give a double (floating point) value:
x + y x - y // lowest precedencex * y x / y+x -x // unary sign; highest
● more complex expressions can be constructed using parentheses in the usual way
■ e.g. (x + y) * 3.0, x / (2.0 * y)■ coding style: when in doubt, use parentheses
● with floating point computation the results may not be exact due to limited precisionand rounding errors
■ e.g. given double x = 0;, what would be the result of endlessly repeatingx = x + 1.0; ?
■ the single precision floating point type float can be used instead of double,◆ it shows such problems sooner; its only advantage is storage size is halved
COMP1100 Lecture 3: Identifiers and Expressions 2004 JJ J • I II × 4
Expressions: integer type
● given the declarations int i, j,
the following expressions give an integer (int)) value
+i -i // highest precedence
i * j
i / j i % j // integer division, remainder
i + j i - j // lowest precedence
● e.g. 17 / 3 = 5, 17 % 3 = 2
● the computation is exact providing there is no overflow (the result outside the range
of integer values we can represent)
■ for int, the range is −231 . . .231−1
■ for the primitive type long int, the range is −263 . . .263−1
COMP1100 Lecture 3: Identifiers and Expressions 2004 JJ J • I II × 5
The Pool Example revisitedfinal double LITRES_PER_CUBIC_METRE = 1000.0;// define the dimensions of the pool in metersdouble length = 25.0;double width = 10.0;double depth = 1.5;
// calculate the volume of the pool in cubic metersdouble volume = length * width * depth;
// calculate capacity in litresdouble capacity = LITRES_PER_CUBIC_METRE * volume;
● for the whole program, see the file Pool2.java
● note the difference between a variable declaration and a constant declaration
■ LITRES_PER_CUBIC_METRE could also be declared outside of the main()routine (would need to add a static qualifier)
● the value of a variable can be changed by the program; the value of a constantremains constant(!)
● further work: study the syntax diagrams in the texts pertaining to declarations,literal constants and expressions
COMP1100 Lecture 3: Identifiers and Expressions 2004 JJ J • I II × 6
Boolean Expressions: arising from numerical types
Ref: L&L sects 2.4, 3.4; Riley sect. 7.2–7.3
● boolean (or ‘logical’) values can be either false or true
● Boolean expressions may be formed from comparing values in numeric types
(via the relational operators):
■ given int x, y , the following expressions give Boolean values:
x == y // is equal tox != y // is not equal tox <= y // is less than or equal tox < y // is less thanx >= y // is greater than or equal tox > y // is greater than
■ the computation is exact■ similarly for other comparable types, e.g. double, char (and boolean !)
● given the variable boolean b;, we can record such expressions:
e.g. b = (x > 0);
COMP1100 Lecture 3: Identifiers and Expressions 2004 JJ J • I II × 7
Boolean Expressions: using Boolean operators
● in the context of the (extended) Pool program, we might have:
■ a variable boolean tooLow;
■ comparisons or relational expressions, i.e. chlorineLevel < lowLimit
■ more complex expressions with && (‘and’),|| (‘or’), ! (‘not’), i.e
lowLimit < chlorineLevel && chlorineLevel <= highLimit
● given boolean p, q; , the following are Boolean expressions:
! p // ‘negate’: true if p is false
p && q // ‘and’: true if both p and q are true
p || q // ’or’: true if at least one of p and q is true
p != q // ‘exclusive or’: true if exactly one of p and q is true
● the following table defines the operators
p q && !! p!=q !pT T T T F FT F F T T FF T F T T TF F F F F T
COMP1100 Lecture 3: Identifiers and Expressions 2004 JJ J • I II × 8
Booleans concepts in programs and computers
● the Boolean primitive data type reflects the concept of a binary digit (bit), having
values 0 or 1
● on a digital electronic computer:
■ 0 corresponds to low (or zero) voltage level, 1 to high
■ transistors can be configured to correspond to and, or or not ‘gates’
These form the fundamental units of data and computation
● Booleans form the basis of program control:
■ if statements: whether to do a computation or not
■ loops: repeatedly execute a computation (determines when to stop!)
COMP1100 Lecture 3: Identifiers and Expressions 2004 JJ J • I II × 9
Introduction to Algorithms
Ref: Robertson Ch 1 Handout: COMP1100-2004-03: Lab Session 02
● so what is an algorithm?
■ from the Macquarie dictionary:an effective procedure for solving a particular mathematical problem in afinite number of steps
■ from the Glossary in the back of Simple Program Design:A set of of detailed, unambiguous and ordered instructions developed todescribe the processes necessary to produce the desired output fromgiven input
● is similar to the idea of a recipe (in cooking):
■ given some ingredients (flour, sugar, butter. . . ) what sequence of processingsteps will produce a cake?
■ in the object-oriented paradigm, the description of the ingredients (data) is justas important as that of the steps!
■ this is also what we think of in computing: an algorithm results in atransformation of data in a finite number of steps
COMP1100 Lecture 4: Algorithms and If Statements 2004 JJ J • I II × 1
Algorithm: Expanded Definition
from p5 of Simple Program Design:
An algorithm is like a recipe: it lists the steps involved in accomplishing a task.
It can be defined in programming terms as a set of detailed, unambiguous and
ordered instructions developed to describe the processes necessary to
produce the desired output from a given input. The algorithm is written in
simple English and is not a formal document. However, to be useful, there are
some principles which should be adhered to. An algorithm must
● be lucid, precise and unambiguous,
● give the correct solution in all cases, and
● eventually end
COMP1100 Lecture 4: Algorithms and If Statements 2004 JJ J • I II × 2
Three Basic Control Structures
Ref: Robertson Ch 2
● the structure of an algorithm (or computer program) is composed of three basic
control structures:
■ sequence (multiple statements, executed in sequence)
■ selection (‘conditionals’: e.g. if-else statements)
■ repetition (‘loops’: e.g. while and for statements)
● e.g. the programs Pool.java and Pool2.java had a sequence of commands
consisting of assignment statements and output statements
● any useful programming language (or computing device) must be capable of
implementing these (and this will be sufficient for any computation)
COMP1100 Lecture 4: Algorithms and If Statements 2004 JJ J • I II × 3
Example Problem: preliminaries
● motivating problem: to determine how much chlorine to add to the pool
■ aside: we will not be able to write a program to solve a problem until we figure
out how to solve the problem!
■ the creative aspect of programming is figuring out algorithms:
i.e. ways to solve a problem that are suitable to be used on a computer
● observation: the amount of chlorine required depends on
1. how far the chlorine level is below the desirable level
2. how big the pool is
COMP1100 Lecture 4: Algorithms and If Statements 2004 JJ J • I II × 4
Example Problem: algorithm using selection
Ref: Robertson Ch 3
● so a program solving such a problem must:
1. calculate the volume of the pool
2. get the measured concentration of chlorine in the pool
3. if the concentration is less than the lower limit of acceptable chlorine
concentration then
3.1 calculate the amount of chlorine required to bring it to the upper limit of
acceptable chlorine concentration
3.2 report the amount of chlorine required
● the above constitutes an informal algorithm to solve the problem
● using the previous versions of the Pool programs to expand step 1. we are ready
to construct the corresponding program:
■ the values of the dimensions and the concentration are read from program input
(rather than initialized to constants)
COMP1100 Lecture 4: Algorithms and If Statements 2004 JJ J • I II × 5
If Statement Example: Pool3.java
// acceptable chlorination range in parts per million (ppm)final static double LOW_LIMIT = 1.0;final static double HIGH_LIMIT = 1.5;
/* input pool’s dimensions and chlorine level & calculate chlorine to add */public static void main(String[] args) {
// dimensions of the pool (in meters)double length, width, depth;double volume;double chlorineLevel; // parts per million (ppm) of Cldouble addAmount; // grams of Cl to add
// get the dimensions of the poolTextStreamWriter.out.println("Type in pool dimensions in metres");
TextStreamWriter.out.print(" Length: ");length = TextStreamReader.in.readDouble();
. . . (similarly for width and depth)// calculate volumevolume = length * width * depth;
COMP1100 Lecture 4: Algorithms and If Statements 2004 JJ J • I II × 6
If Statement Example: Pool3.java continuedTextStreamWriter.out.print("Type in chlorine reading (ppm): ");chlorineLevel = TextStreamReader.in.readDouble();
// check chlorine levelif (chlorineLevel < LOW_LIMIT) {
// calculate the amount of chlorine to addaddAmount = volume * (HIGH_LIMIT - chlorineLevel);// report amount to addTextStreamWriter.out.print("Add chlorine : ");TextStreamWriter.out.print(addAmount);TextStreamWriter.out.println(" grams");
} else {TextStreamWriter.out.println("Chlorine level exceeds minimum.");
}}
running the program (java Pool3):
Type in pool dimensions in metresLength: 10Width: 5Depth: 2Type in chlorine reading (ppm): 1.5Chlorine level exceeds minimum.
Type in pool dimensions in metresLength: 10Width: 5Depth: 2Type in chlorine reading (ppm): 0.5Add chlorine : 100.0 grams
COMP1100 Lecture 4: Algorithms and If Statements 2004 JJ J • I II × 7
If Statements: characteristics
Ref: L&L sect 3.2, Riley sect 7.4–7.6
● how if-else statements are executed:
■ the boolean expression (following if) is evaluated
(its value is either true or false)
■ if true, the statements following the next ‘{’ are executed up to the matching ‘}’
■ if false, the statements between ‘else {’ and the matching ‘}’ are executed
(if there was no else, then the program continues with statements following the
‘if (...) {’s matching ‘}’
■ there may be any number of statements between the ‘{. . . }’, including none
● in Java, sets of braces ({. . . }) are used to make a sequence of statements into a
single block statement
● see Robertson Ch4 for simple examples with selection
see text for more examples and syntax diagrams of if statements
COMP1100 Lecture 4: Algorithms and If Statements 2004 JJ J • I II × 8
Loop Statements
Ref: L&L sect 3.5, Riley sect 10.1, Robertson Ch 5
● motivation: repetition is one of the basic control structures
● e.g. want to calculate the sum of integers from 1 to some value n
the obvious way is to add each successive integer to a running sum
● the program will have some integer variables:
■ n : the last number to add■ i: the integer we add each time; 1 the first time, n the last time■ sumI: the running sum
● each time around our loop we will add 1 to i and then add the result to sumI
● so the program must:
1. get the value of n2. initialise sumI to 0 and i to 13. DO WHILE i <= n
3.1 add i to sumI3.2 increment i
COMP1100 Lecture 5: Loop Statements 2004 JJ J • I II × 1
Example of a while loop: SumN.java
int sumI; // sum of integers from 1 to iint n; // last integer to sumint i; // ‘loop index’ variable
TextStreamWriter.out.print("Sum integers to : ");// get the value of nn = TextStreamReader.in.readInt();
// initialization of the loop variablessumI = 0;i = 1;
// after each iteration, sumI = 1 + 2 + ... + (i-1)while (i <= n) {
sumI = sumI + i;i = i + 1;
}
running the program (java SumN):
Sum integers to : 3Sum of 1 to 3 is 6
COMP1100 Lecture 5: Loop Statements 2004 JJ J • I II × 2
Execution of while loops
1. (initialisation statements, before the loop, are carried out)
2. the continuation condition is evaluated
3. if it is false, then that is the end of the loop statement; the program will carry on
with the statement following the end of the loop
4. if it is true, then the loop body, i.e. the statements following the next ‘{’ up to the
matching ‘}’, are executed , following which you go back to step 2.
● ‘trace’ of SumN program (n == 3)
after initialisation: sumI: 0 i: 1after 1st iteration: sumI: 1 i: 2
after second iteration: sumI: 3 i: 3after third iteration: sumI: 6 i: 4
(loop now terminates)
● can write incorrect loops: what if i = i + 1; came before sumI = sumI + i;?
COMP1100 Lecture 5: Loop Statements 2004 JJ J • I II × 3
Infinite loops
● the program must ensure that the continuation condition evaluates to false at
some point, or you will get an infinite loop!
■ in the SumN program, if we changed the continuation condition to (i != n+1)
Then, what if n is negative?
1. sumI will be a negative number
2. sumI will be a positive number
3. sumI will be 0
4. none of the above
■ when running a Java program from Emacs, the Signals → Kill menu will
enable you to stop a program
(from the Unix shell, typing Control-C will stop it)
● on the other hand, a loop body might never be executed
■ noting that the continuation condition is always evaluated before entering the
loop body
● see Robertson for more (correct) examples, and text for syntax diagrams
COMP1100 Lecture 5: Loop Statements 2004 JJ J • I II × 4
The for Loop
Ref: L&L sect 3.8, Riley sect 10.2
● often, counting loops, i.e. loops running for a known number of repetitions, arerequired
■ for convenience, Java provides such a construct
● e.g. we could replace the initialization / while loop in the SumN program by:sumI = 0;
for (i = 1; i <= n; i = i+1) {sumI = sumI + i;
}
● generally, this loop is of the form:
for (init stmt ; cont condn ; incr stmt ) { for loop body }
■ ‘init stmt’ is executed once, before anything else is executed■ ‘cont condn’ is a Boolean expression, the loop’s continuation condition■ ‘for loop body’ followed by ‘incr stmt’ is executed upon every iteration
● the assignment statement i = i + 1 is often abbreviated in Java as ++i
COMP1100 Lecture 5: Loop Statements 2004 JJ J • I II × 5
Kinds of loops
Ref: Riley sect 10.3–10.4
These are characterised by how you decide when to exit a loop:
● counting loops: you know in advance how many times to traverse the loop
● reach some stage in the calculation e.g.
■ the LargeSquare.java example
■ a program determining a square root (to some accuracy) by successive division
● when you run out of data to process,
■ you may be able to use a special value flag or sentinel value) to indicate end of
valid data
◆ e.g. Average1.java example
■ end of input: see the Average2.java example
COMP1100 Lecture 5: Loop Statements 2004 JJ J • I II × 6
Further example: LargeSquare.java
● problem: want to find the smallest perfect square greater than some value n
● method: take the square of successive integers until we find the first square that is
greater than n
● program variables:
■ n: the number the square should be greater than
■ i: the integer we are squaring
■ square: the square of i
● each time around our loop, add 1 to i, take its square and compare the square to n
● algorithm:
1. get the value of n
2. initialise i and square
3. DO WHILE square <= n
3.1 increment i
3.2 set square to i*i
4. report the value of square
COMP1100 Lecture 5: Loop Statements 2004 JJ J • I II × 7
Further example: Average1.java
● problem: find the average of some numbers we will read into the program; we
don’t know ahead of time how many
● method: each number read in should be added to a running sum, and a counter
should be incremented.
■ after all the numbers are read in, the running sum will be the total sum, and the
counter will be the number of values read in
● question: how will we know when we have read the last value?
possible answer: if we know something about the values, we may be able to use a
sentinel value to flag the end of input
■ e.g. rainfall cannot be negative, so a negative value could be used to indicate
end of valid input
COMP1100 Lecture 5: Loop Statements 2004 JJ J • I II × 8
Average1.java example continued
● program variables:
■ count: the number of values
■ sum: the running sum
■ value: a single value
● algorithm:
1. initialise count and sum to zero
2. read first value3. DO WHILE value >= 0.0
3.1 add value to sum3.2 increment count
3.3 read next value4. report average (sum / count)
● running the program (java Average1):
Type in values, one per line; terminate with negative number :1.5 1 2.5 -1Average is 1.67
COMP1100 Lecture 5: Loop Statements 2004 JJ J • I II × 9
Primitive Data Types summarized
if not initialized upon declaration, variables are given a default value;
this can be subsequently changed by assignment statements:
● int: models ‘whole’ numbers (exact, up limited size)
int year; year: 0
year = 2001; year: 2001
● booleans: models true/false logic (exact)
boolean success; success: false
success = true; success: true
● char: models unicode characters (16-bit, exact)
char c; c: ’0’
c = ’h’; c: ’h’
● double (similarly float) : models real number system (inexact!)
double pi; pi: 0.0
pi = 3.141; pi: 3.141
COMP1100 Lecture 6: Introduction to Arrays 2004 JJ J • I II × 1
Motivations for arrays
Ref: L&L sect 6.0, Riley sect 12.1–12.3; Robertson Ch 7
● motivation: sometimes we have a lot of ‘similar’ data
■ most compute-intensive tasks involve such data
■ a computers’ strength is that it can perform a large number of precise
calculations very quickly
● example: process weather data (daily rainfall) for a month
■ find the total rainfall for the month
■ may also want to calculate various other statistics
◆ e.g. the maximum rain in any single day, the number of days with no rain
◆ i.e. we want to still have all the data after we have the total
(don’t want to re-read the data again)
COMP1100 Lecture 6: Introduction to Arrays 2004 JJ J • I II × 2
Processing weather data using only single variables
● outline of declarations, with separate variable for each day’s rainfall:double rain01, rain02, ..., rain31; // 31 separate declarationsdouble total;int count;...
● calculating the total rainfall:total = rain01 + rain02 + rain03 + ... + rain31;
● even worse for calculating the number of days without raincount = 0;if (rain01 == 0) {
count = count + 1;}if (rain02 == 0) {
count = count + 1}...
● but we can’t have ... or ‘etc’ in a program!
● need ability to refer to each day’s rainfall indexed by the day number:
■ so that we can use loops; an array type will do this for us
COMP1100 Lecture 6: Introduction to Arrays 2004 JJ J • I II × 3
Example of using arrays: Rainfall.java
double[] rain; // daily rainfall in mm for one monthint numberOfDays = NUMBER_OF_DAYS; // # days of the month
double total; // total rainfall for the monthint d; // index for day: 0 for 1st day, 1 for 2nd day, ..., 30 for 31st day
rain = new double[numberOfDays];// create storage for an array of numberOfDays double values
for (d = 0; d < numberOfDays; ++d) {// read in rain data to the arrayrain[d] = TextStreamReader.in.readDouble();
}
// calculate the sum of the rainfall for each day of the month.total = 0.0;for (d = 0; d < numberOfDays; ++d) {
total = total + rain[d];}
TextStreamWriter.out.print("Total rainfall = ");TextStreamWriter.out.println(total, 0, 1); // minimum width, one decimal point
COMP1100 Lecture 6: Introduction to Arrays 2004 JJ J • I II × 4
Array Declaration and Storage Allocation
● unlike for primitive types, this occurs in 2 stages
● declaration: double[] rain;
■ storage is allocated to a pointer (essentially, an integer representing a memoryaddress) to an array ‘object’
■ it is ‘labelled’ with the name of the array variable■ it is initialized to null (null address), which ‘points’ to no valid memory storage)
nullrain:
● storage allocation: rain = new double[numberOfDays];
■ the new operator creates storage for an array ‘object’, in this case consisting ofnumberOfDays consecutive storage elements of the type double
■ the assignment statement sets rain to point to this array ‘object’
length: 31
...
0 1rain :
30
0.0 0.0 0.0 0.0
2
double[31]
0.0
29
COMP1100 Lecture 6: Introduction to Arrays 2004 JJ J • I II × 5
Accessing array elements
● sample run of Rainfall.java program (java Rainfall):
6.0 0.0 0.0 ... 0.0 3.3Total rainfall = 9.3
■ above input has exactly 31 numbers (with 29 0.0’s)
■ after for loop to read in the data:
...
length: 31
0 1rain :
30
6.0 0.0 0.0
2 29
double[31]
0.0 3.3
● the array index (an int expression, e.g. d) must always be >= 0 and < the array
length (in this case 31)
■ this can be given by the expression rain.length
◆ in this case, (rain.length == 31) would evaluate to true
● an array element (e.g. rain[d]) is like a double variable, and can be used in the
same way
COMP1100 Lecture 6: Introduction to Arrays 2004 JJ J • I II × 6
Array Concepts
● array ‘objects’ (like (proper) Java objects) must be explicitly created via the new operator
■ its elements are initialized to the respective type’s default value
● template for processing all elements of an array:double[] data;int i;double val;...for (i=0; i < data.length; ++i) {
val = data[i];// process val
}
● characteristics of an array:
■ all the elements in the array have the same type – can be any type
■ the array as a whole has a single name
■ an element in the array can be accessed by giving the array’s name and the
value of the element’s index
◆ the index is of type int
COMP1100 Lecture 6: Introduction to Arrays 2004 JJ J • I II × 7
Characteristics of Objects and Classes
Ref: L&L sect 4.0–4,2, Riley Ch 2–3; Robertson Ch 11.1
● an object in a program represents real-world objects of interest to the application
● a class describes the relevant features of a collection of similar objects
● the class definition describes both the data structure and the operations that can beperformed on the data
■ the data features are referred to as attributes.■ the code features (called methods or routines) define the operations
● an object is an instance of a class (as a variable is an instance of a type)
■ is created (instantiated) using the constructor method (of the same name as the class)
● so far, our examples consisted of a main() routine, containing variabledeclarations and executable code
■ this was put inside an ‘obligatory’ (and trivial) class definition■ more sophisticated programs are written in a different (OO) style
◆ main() is short, and creates a small number of objects★ whose attributes store most the data, & methods contain most of the code
COMP1100 Lecture 7: Objects and Classes 2004 JJ J • I II × 1
Object-Oriented Version of the Pool.java Program: PoolC.javapublic class PoolC {
// constructs a PoolC objectpublic static void main(String[] args) {
PoolC mypool = new PoolC(); //}
// data features (attributes of) PoolC objectsdouble length = 25.0; // dimensions of the pool (in meters)double width = 10.0;double depth = 1.5;double volume; // (in cubic meters)
/* PoolC constructor method: calculate and report the volume of a pool */public PoolC() {
// calculate the volume of the poolvolume = length * width * depth;
// report the volume of the poolTextStreamWriter.out.print("Pool volume : ");TextStreamWriter.out.print(volume, 0, 1);TextStreamWriter.out.println();
}}
COMP1100 Lecture 7: Objects and Classes 2004 JJ J • I II × 2
Object creation in the PoolC.java Program
● the object of type PoolC is created in two steps:
1. at start of execution of PoolC() 2. after the assignment to volume
length
depth
classPoolC
widthdouble
PoolC()
volume
10.0
double
double
double
1.5
0.0
routines
attributes
25.0length
depth
classPoolC
widthdouble
PoolC()
volume
25.0
15.0
double
double
double
1.5
375.0
routines
attributes
COMP1100 Lecture 7: Objects and Classes 2004 JJ J • I II × 3
Object Creation: Further Notes
● note: there is one copy of any static feature per class;
■ thus, the main() method is not included in the previous object diagrams
● the text of the class Pool1C is used as a template to create the object
■ the attribute declaration double length; is elaborated, to produce andouble ‘object’
◆ this creates a storage cell that can hold a double (with value 10.0)■ similarly for the width, depth and volume attribute declarations■ the declaration of the routine Pool1C is stored, copied from the class definition
● in the execution of a routine in an object:
■ the attributes and routines in the object can be directly addressed (e.g. length)■ attributes and routines (of objects) from different classes are addressed using
the dot notation:◆ e.g. TextStreamWriter.out.print()◆ out is an object of class TextStreamWriter◆ print() is a routine (method) of out (declared in the class TextStreamWriter)
This notation lets us navigate from one object to another
COMP1100 Lecture 7: Objects and Classes 2004 JJ J • I II × 4
Class Declarations Without a main() Routine: PoolC1.java
● in all of the classes that are used by an executable Java program (including its own
class), there can be only one static main() method
● normally, the main() method is declared within a separate ‘test program’ class
■ normally, this needs to be stored in a file in the same directory
● e.g. TestPoolC1.java:/* TestPoolC1: test program for the PoolC1 class */public class TestPoolC1 {
// constructs a PoolC1 objectpublic static void main(String[] args) {
PoolC1 mypool = new PoolC1(); //}
}
● note: we must allocate storage for (proper Java) objects via the new operator, as we
did for array ‘objects’
■ c.f. double rain[] = new double[31]:
COMP1100 Lecture 7: Objects and Classes 2004 JJ J • I II × 5
Creating Multiple Objects Using Parameters
● e.g. PoolC2.java allows a pool object’s dimensions to be specified uponconstruction:public class PoolC2 {
// data features (attributes of) PoolC2 objectsdouble length; // dimensions of the pool (in meters)double width;double depth;double volume; // (in cubic meters)
/* PoolC2 constructor method: calculate and report the volume of a pool */public PoolC2(double l, double w, double d) {
// initialize the pool dimensions from the parameterslength = l;width = w;depth = d;// calculate the volume of the poolvolume = length * width * depth;// report the volume of the poolTextStreamWriter.out.print("Pool volume : ");TextStreamWriter.out.print(volume, 0, 1);TextStreamWriter.out.println();
}}
COMP1100 Lecture 7: Objects and Classes 2004 JJ J • I II × 6
Creating Multiple Objects Using Parameters (continued)
● now we can create multiple pool objects, permitting code re-use, e.g.TestPoolC2.java
public static void main(String[] args) {PoolC2 mypool;TextStreamWriter.out.println("my backyard pool: ");mypool = new PoolC2(10.0, 5.0, 2.0);TextStreamWriter.out.println("the swimming center’s pool: ");mypool = new PoolC2(50.0, 10.0, 2.0);
}
■ executing PoolC2(10.0, 5.0, 2.0) first creates storage for PoolC2()’sparameters and initializes them as follows:
l: 10.0 w: 5.0 d: 2.0and then the code inside this routine is executed
■ similarly, for executing PoolC2(50.0, 10.0, 2.0)
● program execution (java TestPoolC2):
my backyard pool:Pool volume : 100.0the swimming center’s pool:Pool volume : 1000.0
COMP1100 Lecture 7: Objects and Classes 2004 JJ J • I II × 7
Summary
● Java provides us with a large collection of pre-written classes, in the form of
standard class libraries
● class libraries need to be explicitly imported
● to use a class in the library we need to know:
■ its name (e.g. TextStreamWriter)
■ its features (e.g. print())
Javadoc is a standard documentation convention which provides this information
● in principle, it is easy to use a library class
● a great deal of computing can be done by using library classes (software re-use)
● we can write our own code in a similar, object-oriented, fashion:
■ shift computation from main() to the class constructors and other methods
■ shift data storage from local variables (in main()) to class data attributes
■ move the main() routine to an external (‘test program’) class
COMP1100 Lecture 7: Objects and Classes 2004 JJ J • I II × 8
Motivations
Ref: L&L sect 4.2, Riley 4.1–4.5; Robertson Ch 8
● program structure – a complex program can be broken down into smaller, relatively
self-contained pieces
■ clearer program structure
■ program can be understood at different levels
■ lower-level details can be dealt with in smaller segments
● the same calculation may need to be done several times, perhaps with different
data
● a calculation may be more generally useful, and can be used in different programs,
if written in a self-contained fashion
● the appropriate decomposition of a software system to appropriate classes (data)
and methods (routines)
■ for dealing with complexity & maximizing software re-use
is one of the key skills in software design
COMP1100 Lecture 8: Methods (Routines) 2004 JJ J • I II × 1
Rainfall example Rainfall.java revisited: Rainfall2.java
public double[] rain; // daily rainfall in mmpublic int numberOfDays; // the number of days of rain data
/* create a Rainfall2 object to record a month’s rainfall data.* Report on the total rainfall, day of max. rain and # of dry days */public static void main(String[] args) {
TextStreamWriter.out.println("Rainfall Statistics (mm) :");TextStreamWriter.out.print("Type in number of days : ");int days = TextStreamReader.in.readInt();
// make a rain fall record for ‘days’ days of dataRainfall2 rainfall = new Rainfall2(days);
rainfall.getRainData();
rainfall.reportTotalRain();
rainfall.reportMaxRain(); // report maximum rain in any one day
// report the number of dry daysTextStreamWriter.out.print("Dry days = ");TextStreamWriter.out.println(rainfall.dryDays());
}
COMP1100 Lecture 8: Methods (Routines) 2004 JJ J • I II × 2
Writing Methods: Rainfall2.java/* construct a Rainfall2 object holding data for n days */public Rainfall2(int n) {
numberOfDays = n; // record the value of n in the this attributerain = new double[numberOfDays]; // create array to hold data
}
/* get the rain fall information from standard input */public void getRainData() {
for (int d = 0; d < numberOfDays; ++d) {// read a rainfall figurerain[d] = TextStreamReader.in.readDouble();
}}
● execution of the call of getRainData() from main():
thread ofexecution
getRainData();
calling component called component
public void getRainData {
}
COMP1100 Lecture 8: Methods (Routines) 2004 JJ J • I II × 3
Writing Methods (continued): Rainfall2.java/* report the total amount of rain fall record for the Rainfall2 object*/public void reportTotalRain() {
double total = 0.0;// sum all the rainfall valuesfor (int d = 0; d < numberOfDays; ++d) {
total = total + rain[d];}TextStreamWriter.out.print("Total rainfall = ");TextStreamWriter.out.println(total, 0, 1);
}
/* report the amount of the maximum rainfall for the Rainfall2 object */public void reportMaxRain() {
double maxRain = 0.0; // assume a dry day for the initial maximumfor (int d = 0; d < numberOfDays; ++d) {
// check day d+1’s rainfall; element 0 is for day 1if (rain[d] > maxRain) {
// record the new peak and the day of the peakmaxRain = rain[d];
}}TextStreamWriter.out.print("Max rainfall in one day = ");TextStreamWriter.out.println(maxRain, 0, 1);
}
COMP1100 Lecture 8: Methods (Routines) 2004 JJ J • I II × 4
Characteristics of Methods
● a method declaration defines a ‘subprogram’ by giving a name to some executable
code (which can carry out some defined operation)
● the method must be called in order for the statements in the routine to be actually
carried out
■ what about the main() routine?
● a method may have a void (a procedure) )or a non-void return value (a function)
■ a call to a procedure appears in a statement on its own
■ a call to a function may be used inside any expression (provided it is of an
appropriate type)
● Rainfall2.java declares, besides the main() procedure, one constructor procedure,
three other procedures, and one function
■ they are all called in main()
■ the local variable d is serves as a loop index
◆ as a convenient shorthand, it can be declared in the ‘init stmt’ in the for
loop, instead of at the start of the method
COMP1100 Lecture 8: Methods (Routines) 2004 JJ J • I II × 5
Writing Functions: Rainfall2.java/* find the total number of dry days recorded in the Rainfall2 object */public int dryDays() {
int dryCount = 0; // total number of dry daysfor (int d = 0; d < numberOfDays; ++d) {
if (rain[d] == 0.0) {++dryCount;
}}// return the total number of dry daysreturn dryCount;
}
● the return statement immediately returns program control to the calling routine
● a function has a type; the value in the return statement must be of the same type
● a function is called by using it in an appropriate expression
■ i.e. wherever the function’s type is appropriate■ the value of the call is determined by the value in the return statement
● e.g. rain[d] = TextStreamReader.in.readDouble();
● generally, functions should not have ‘side effects’,
■ i.e. they should not change the object’s data attributes
COMP1100 Lecture 8: Methods (Routines) 2004 JJ J • I II × 6
Method Parameters
● methods (whether procedures or functions) may have parameters
■ this permits re-use of the executable code, for different data
■ the (formal) parameters declared inside the method are like local variables
except they are initialized by the (actual) parameters of the method call
■ e.g. when we execute the call Rainfall2(days); with
days: 31
this sets the formal parameter n in Rainfall2() to n: 31
when the code in Rainfall2() is executed, this value gets passed to
numberOfdays
● consider the routines to calculate the total, maximum and number of zero elements
in the rain array
■ if we can write these without explicitly referring to Rainfall2’s rain array, we
could use these routines anywhere where we needed such calculations
performed on the array
COMP1100 Lecture 8: Methods (Routines) 2004 JJ J • I II × 7
Method Parameters (continued)
● consider the code sections of where we are reporting the results: the pattern ofoutput is the same, with the label and value differing:
TextStreamWriter.out.print("Total rainfall = ");TextStreamWriter.out.println(total, 0, 1);
● the following routine captures this pattern:printResult(String label, double value) {
TextStreamWriter.out.print(label);TextStreamWriter.out.println(total, 0, 1);
}
● in main(), we could call this in order to tidy up is code structure:printResult("Dry days = ", rainfall.dryDays());
■ what about the type of dryDays()?■ where else could we use this routine?
● running of the program would not be affected:
Type in number of days : 316.0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3.3Total rainfall = 9.3Max rainfall in one day = 6.0Dry days = 29
COMP1100 Lecture 8: Methods (Routines) 2004 JJ J • I II × 8
Review: Boolean Expressions
● importance: used in if, while and for statements
● a literal of type boolean
i.e. true or false
● a variable of type boolean
for example a variable boolean tooLow; for the Pool program
● comparisons or relational expressions
e.g. chlorineLevel < lowLimit
● more complex expressions (with &&, ||, !)
(chlorineLevel > lowLimit) && (chlorineLevel < highLimit)
■ what is its value, given:
chlorineLevel: 1.2 lowLimit: 1.0 highLimit: 1.5
■ after chlorineLevel = 0.0; ? after chlorineLevel = 2.0; ?
COMP1100 Lecture 9: Review: Booleans, Arrays, Classes and Routines2004 JJ J • I II × 1
Review: Arrays
after getRainData() (array created and loaded with data), the image of an array is:
...
length: 31
0 1rain :
30
6.0 0.0 0.0
2 29
double[31]
0.0 3.3
● all the elements in the array have the same type – can be any type
■ e.g. for rain array, the element type is double
● the array as a whole has a single name
● an element is accessed by giving the name & the value of its (int) index,e.g. rain[0]
● to print the value of element 5 (in the 6th storage location!) of the rain array:
TextStreamWriter.out.print(rain[5], 0, 1);
● to divide element 2*i+1 by 10 and store the result in the variable x:
x = rain[2*i+1] / 10.0;
● to set element 9 to 8.5: rain[9] = 8.5;
COMP1100 Lecture 9: Review: Booleans, Arrays, Classes and Routines2004 JJ J • I II × 2
PoolC3.java: Extended Version of the Pool Program
can use an array for the pool dimensions, and avoid using ‘redundant’ data attributes:// acceptable chlorination range in parts per million (ppm)final static double LOW_LIMIT = 1.0;final static double HIGH_LIMIT = 1.5;
// data features (attributes of) PoolC3 objectsString name; // name of the pooldouble dimension[]; // dimensions of the pool (in meters)double chlorineLevel = 0.0; // parts per million (ppm) of Cl
// PoolC3 constructor methodpublic PoolC3(String n, double l, double w, double d) {
name = n;dimension = new double[3]; // must create storage before initializing!dimension[0] = l; // lengthdimension[1] = w; // widthdimension[2] = d; // depth
}
// return the volume of the pool in cubic meterspublic double volume() {
return dimension[0] * dimension[1] * dimension[2];}
COMP1100 Lecture 9: Review: Booleans, Arrays, Classes and Routines2004 JJ J • I II × 3
TestPoolC3.java: Using the PoolC3 Class
public static void main(String[] args) {PoolC3 pool1 = new PoolC3("Backyard Pool", 10.0, 5.0, 2.0);PoolC3 pool2 = new PoolC3("Jamison Pool", 50.0, 10.0, 2.0);
pool1.print();pool1.reportChlorineLevel();pool1.setChlorineLevel(1.2);pool1.reportChlorineLevel();pool1.setChlorineLevel(2.0);pool1.reportChlorineLevel();
pool2.print();}
program output: (java TestPoolC3)
Backyard Pool has volume (cubic meters): 10.0 x 5.0 x 2.0 = 100.0Backyard Pool has chlorine level (in ppm) 0.00: add chlorine: 150.0 gramsBackyard Pool has chlorine level (in ppm) 1.20: is safe for useBackyard Pool has chlorine level (in ppm) 2.00: exceeds max. limit!Jamison Pool has volume (cubic meters): 50.0 x 10.0 x 2.0 = 1000.0
COMP1100 Lecture 9: Review: Booleans, Arrays, Classes and Routines2004 JJ J • I II × 4
PoolC3.java: Printing the Pool’s Spatial Data
// report primary pool informationpublic void print() {
TextStreamWriter.out.print(name);TextStreamWriter.out.print(" has volume (cubic meters): ");for (int i=0; i < 3; ++i) {
TextStreamWriter.out.print(dimension[i], 0, 1);if (i < 2) {
TextStreamWriter.out.print(" x ");}
}TextStreamWriter.out.print(" = ");TextStreamWriter.out.println(volume());
}
output from pool1.print(); (after new PoolC3("Backyard Pool", 10.0, 5.0, 2.0);):
Backyard Pool has volume (cubic meters): 10.0 x 5.0 x 2.0 = 100.0
COMP1100 Lecture 9: Review: Booleans, Arrays, Classes and Routines2004 JJ J • I II × 5
PoolC3.java: Handling of Chlorine Levels
// sets chlorineLevel of the poolpublic void setChlorineLevel(double newLevel) {
chlorineLevel = newLevel;}
// report on the chlorine levelpublic void reportChlorineLevel() {
TextStreamWriter.out.print(name);TextStreamWriter.out.print(" has chlorine level (in ppm) ");TextStreamWriter.out.print(chlorineLevel, 0, 2);if (chlorineLevel < LOW_LIMIT) {
TextStreamWriter.out.print(": add chlorine: ");TextStreamWriter.out.print(volume() * (HIGH_LIMIT - chlorineLevel));TextStreamWriter.out.println(" grams");
} else {if (chlorineLevel > HIGH_LIMIT) {
TextStreamWriter.out.println(": exceeds max. limit!");} else {
TextStreamWriter.out.println(": is safe for use");}
}}
COMP1100 Lecture 9: Review: Booleans, Arrays, Classes and Routines2004 JJ J • I II × 6
PoolC3.java: Object Creation and Class Design
after pool1 = new PoolC3(...);:
length: 3
...........
double[3]
5.0 2.010.0
....’B’ ’a’ ’o’ ’l’’c’
length: 13
name
chlorineLevel
classPoolC
dimensiondouble[]
String
double
0.0
methods
attributes
PoolC3()
volume()
print()
improved class design resulting in:
● simplified data attributes
● the method decomposition permits:
■ clearer structure
■ more flexibility and code re-use
COMP1100 Lecture 9: Review: Booleans, Arrays, Classes and Routines2004 JJ J • I II × 7
Clearer Main Program Structure via Routines: Rainfall3.java
(constructor and getRainData() as for Rainfall2.java)
public class Rainfall3 {public double[] rain; // daily rainfall in mmpublic int numberOfDays; // the number of days of rain data
/* create a Rainfall3 object to record a month’s rainfall data.* Report on the total rainfall, day of max. rain and # of dry days */public static void main(String[] args) {
TextStreamWriter.out.println("Rainfall Statistics (mm) :");TextStreamWriter.out.print("Type in number of days : ");int days = TextStreamReader.in.readInt();
// make a rainfall record for ‘days’ days of dataRainfall3 rainfall = new Rainfall3(days);
rainfall.getRainData();
printResult("Total rainfall = ", sumArray(rainfall.rain));
printResult("Max rainfall in one day = ", maxArray(rainfall.rain));
printResult("Dry days = ", countValues(0.0, rainfall.rain));}
COMP1100 Lecture 9: Review: Booleans, Arrays, Classes and Routines2004 JJ J • I II × 8
Generic double[] Routines in Rainfall3.java
/* return the sum of all elements of a[] */public static double sumArray(double a[]) {
double sumA = 0.0;for (int i=0; i < a.length; ++i) {
sumA = sumA + a[i];}return(sumA);
}
/* return the number of elements in a[] matching value */public static int countValues(double value, double a[]) {
int count = 0;for (int i=0; i < a.length; ++i) {
if (a[i] == value) {count = count + 1;
}}return(count);
}
public static void printResult(String label, double value) {TextStreamWriter.out.print(label);TextStreamWriter.out.println(value, 0, 1);
}
COMP1100 Lecture 9: Review: Booleans, Arrays, Classes and Routines2004 JJ J • I II × 9
Routines
Why use routines:
● program structure – a complex program can be broken down into smaller, relativelyself-contained pieces
■ clearer program structure■ program can be understood at different levels■ lower-level details can be dealt with in smaller segments
● the same calculation may need to be done several times, perhaps with differentdata
● a calculation may be more generally useful, and can be used in different programsif it is written in a self-contained fashion
Rainfall2 demonstrates 1st point;PoolC3 demonstrates 2nd point;Rainfall3 demonstrates 3rd point
● the (static) generic routines can be re-used by many other programs
● should these belong in a separate class?
COMP1100 Lecture 9: Review: Booleans, Arrays, Classes and Routines2004 JJ J • I II × 10
Assignment 2: The Prisoner’s Dilemma
Ref: R. Axelrod, The Evolution of Cooperation (1984); W. Poundstone, Prisoner’s Dilemma (1993)
● scenario: 2 ‘prisoners’ are arrested; authorities offer each a reduced sentence
(years in jail) if s/he ‘grasses’ on the other
● playing the game (0 means ‘grass’, 1 means ‘refuse to grass’):
player A: 0 0 1 1player B: 0 1 0 1score for A: -3 0 -5 -1score for B: -3 -5 0 -1
● for the Iterated Dilemma, total score for each player is the sum of their scores at
each move:
■ a non-zero sum game: objective is to maximize own score, not to ‘beat’ the
opponent’s score
■ best outcome is from persuading the opposing player to cooperate (play 1’s)
■ models real-world situations: WWI Trench Warfare, biological & social
interactions
COMP1100 Lecture 10: Arrays and Strings as Objects 2004 JJ J • I II × 1
COMP1100 Prisoner’s Dilemma Tournament
● we will play everyones strategy in their submitted MyPrisoner.java against
everyone else’s (week 7)
■ hence, this needed to be put in a separate file
■ your strategy can be as simple or complex as you like
◆ but not identical to ALWAYS_GRASS, ALWAYS_REFUSE, RANDOM or
TIT_FOR_TAT
◆ it should not make any assumptions on the array parameters except the
values of elements 0 to i-1 exist and represent the game up to the ith move
● winning criteria: highest accumulated total scores for each match
● open to all COMP1100 students and tutors
● bottle prizes!
COMP1100 Lecture 10: Arrays and Strings as Objects 2004 JJ J • I II × 2
Arrays as ‘Objects’
● arrays are like proper Java objects in many respects
● the declaration int[] moves;[] is elaborated to give: moves: null
■ the associated storage cell associated does not (yet) contain the address of a
(valid) object
■ i.e. moves has not been attached to an object
● the statement moves = new int[10];
1. creates an object of type int[10]
2. attaches moves to the object (‘assigns’ the address of the object to {move)
10
class
attributes
int[10]
rain 0 1 8 9
0 0 0 0
length:
(index) methods
(the indexing operation ([...]) can be thought of as a (pseudo-) method)
COMP1100 Lecture 10: Arrays and Strings as Objects 2004 JJ J • I II × 3
Two-Dimensional Arrays
Ref: L&L 6.3, Riley 12.9
● arrays provide a basic way of structuring a single ‘stream’ of data
● often, data is structured in matrices:
■ recall that an array’s element type can be of any type
■ if that type is an array, then a two-dimensional structure can be modelled
● e.g. a 2×3 matrix (2 rows of length 3) (object after loop)int[][] tab = new int [2][3];int i, j;for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {tab[i][j] = 3*i + j;
}}TextStreamWriter.out.print(tab[1][2]);
length:
length:
int[3]
3
0 1 2
length:tab:
int[2][]
2
0 1
int[3]
3
0 1 2
0
3 54
1 2
■ a double index is needed to access elements (and create storage)
COMP1100 Lecture 10: Arrays and Strings as Objects 2004 JJ J • I II × 4
Strings as Objects
Ref: L&L 2.6, Riley 6.9
● perhaps the most widely used data type is that of a sequence of characters (also:
array of characters, ‘string’).
■ a short string, like "u3123456" or "Bart Simpson", and
■ a long string (many lines) like a Java program or the contents of a text file
● we could use char[] but there are many special things we want to do to strings:
■ two strings can be joined together
■ a string can be split into two strings
■ all occurrences of "ab" can be replaced by "xyz"
● Java provides a library class String
■ provides a concatenation method (concat()) in the form of an operator (+)
■ highly convenient for concise generation of output messages
COMP1100 Lecture 10: Arrays and Strings as Objects 2004 JJ J • I II × 5
The String Class
● while it also contains storage for an ‘array’ of char,
a String object is different from a char[] object:
■ it has a large collection (about 11) of methods, including a length() method
◆ instead of [...], the method charAt(...) is used to access elements
★ e.g. "Homer".charAt(4) returns the character ’r’
■ once created, a String object may not be changed
◆ however, it is easy to create a ‘mutation’ of an existing String object
Strings are proper objects in Java
● e.g. String str = "Hello friend"; creates the following object:
length()
charAt()
concat()
.....
.....
...
0
classString
attributes’l’ ’l’ ’o’ ’n’
1 11
methods
str:
’h’ ’e’ ’e’ ’d’
COMP1100 Lecture 10: Arrays and Strings as Objects 2004 JJ J • I II × 6
String Concatenation
● so far, forming messages (from string literals and variables) has been fairly
cumbersome
● the concat() method can be used to concatenate (join) 2 strings
■ Java also provides this method in operator form
◆ e.g. ’Bart Simpson" is the same as "Bart " + "Simpson"
◆ numeric types can be used (they are implicitly converted to String)
◆ e.g. "Bart" + 5 (the 5 in an int here) produces the same string as
"Bart5" or "Bart" + "5"
● special characters may be inserted in string literals using ‘escape sequences’:
■ e.g. "\n", "\"" and "\\" are all single character strings
■ they contain the newline, double quote and backslash characters, respectively
● see template PlayDilmma.java for more examples on the use of + to form output
messages
■ exercise: simplify the code for the Rainfall and Pool examples in this way.
Are there any difficulties?
COMP1100 Lecture 10: Arrays and Strings as Objects 2004 JJ J • I II × 7
String Manipulation Example: CheckString.java
● part of code (see whole program for more examples):String s1 = "a string";String s2 = new String(s1); // creates a copyString s3 = s1.concat(" longer");String s4 = new String("What happens here?");
TextStreamWriter.out.println("s1: *" + s1 + "*");TextStreamWriter.out.println("s2: *" + s2 + "*");TextStreamWriter.out.println("s3: *" + s3 + "*");TextStreamWriter.out.println("s4: *" + s4 + "*\n");
TextStreamWriter.out.println("s3, of length " + s3.length() + ", must be longer than s1\n" );
● note that s3.length() is of type int● corresponding output:
s1: *a string*s2: *a string*s3: *a string longer*s4: *What happens here?*
s3, of length 15, must be longer than s1
COMP1100 Lecture 10: Arrays and Strings as Objects 2004 JJ J • I II × 8
Classes For Primitive Types
● Java provides an number of special classes, known as primitive types
■ e.g. boolean, char, int , float, and double
● these are provided as part of the libraries that come with an Java system
● for efficiency purposes, ‘objects’ of these types are processed differently:
■ their values are directly accessed, rather accessed by a reference
■ storage for the value is created when the declaration is elaborated
■ the dot notation is not needed to access the basic feature, ı.e. the value
COMP1100 Lecture 11: Working Classes and Objects 2004 JJ J • I II × 1
Creation of an Object of a Simple Reference Classpublic class Dummy {
int i;String str;Dummy(String s) { // constructor
str = new String(s);}...
an object before 1st line of an object after call to Dummy("abcdefg") completes:Dummy("abcdefg") is executed:
class
methods
attributes
Dummy
null
0
int
Dummy()
i:
s:r:
class
methods
Dummy
attributes
0
int
Dummy()
i:
str:
’b’ ’c’ ’d’ ’f’
String
’a’ ’e’ ’g’
COMP1100 Lecture 11: Working Classes and Objects 2004 JJ J • I II × 2
Programmer-Written Classes
Characteristics:
● program system consists of one or more classes
● Java -> Compile is executed on class containing main()
■ other classes are automatically found and compiled
● the Java compiler knows where to look for library classes
● it will also find other programmer-written classes in the same directory
■ these classes will be reference classes■ i.e. they have a constructor method, used to manufacture ‘proper’ Java objects
Object creation:
● e.g. (from inside main()): Dummy d; d = new Dummy(); d.i = 10;
● no object is created when the declaration is elaborated
■ storage only for the reference to the object is allocated
● an object is created when the new operator is executed
● the dot notation is needed to access all features
COMP1100 Lecture 11: Working Classes and Objects 2004 JJ J • I II × 3
Common Characteristics of Reference Classes: the Object Class
Ref: L&L sect 5.0, 7.2, Riley sect 2.4, 4.6, 9.5-9.6
● all reference classes implicitly ‘inherit’ some useful methods from the Java Object
class
■ boolean equals(Object obj): returns whether this object points to the
same storage as obj
◆ equivalent to (‘this object’ == obj)
■ String toString(): returns a string representation of this object
■ Object clone(): creates and returns a copy of this object
● the Object class forms the base of the Java class hierarchy
● these implicit methods may be overridden in a class if a method of the same name
is given in the classes’ definition
■ typically, equals() is redefined to mean that the two objects’ contents are
equal (e.g. this is done in the String class)
■ e.g. in CheckString.java, the expression (s1 == s2) would be false, but
(s1.equals(s2)) would be true
COMP1100 Lecture 11: Working Classes and Objects 2004 JJ J • I II × 4
Overriding Object Methods in a Simple Class
● if we add the following to the Dummyclass:
boolean equals(Dummy d) {return (i == d.i) &&
str.equals(d.str);}Object clone() {
Dummy d = new Dummy(str);d.i = i;return d;
}
● and use the class (e.g. from insidemain()):
Dummy d1 = new dummy("D1");Dummy d2 = new dummy("D2");d2.i = 10;
● clearly, neither (d1 == d2) nor
d1.equals(d2) will be true at this
point
● at this point, the objects look like:
str:
d1:
str:
i: 0
’D’
String
’1’
Dummy
Dummy
’D’
Stringd2:
’2’
i: 10
COMP1100 Lecture 11: Working Classes and Objects 2004 JJ J • I II × 5
Object Assignment and Cloning in a Simple Class
● if we now execute d2 = d1;
str:
d1:
str:
i: 0
’D’
String
’1’
Dummy
Dummy
’D’
Stringd2:
’2’
i: 10
● now (d1 == d2) and
d1.equals(d2) will be true
● and after:d2 = d1.clone();
str:
i: 0
d1:
str:
i: 0
’1’’D’
String
’1’’D’
String
Dummy
Dummy
’D’
Stringd2:
’2’
object)(newly created
● now (d1 == d2) will be false, but
d1.equals(d2) will be true
● what if Dummy() did str = s;
instead of str = new String(s);
?
COMP1100 Lecture 11: Working Classes and Objects 2004 JJ J • I II × 6
Overriding Object Methods in PoolC3.java// override methods ‘inherited’ from the Object class
// return true if the pools names, dimensions & Cl levels are the samepublic boolean equals(PoolC3 p) {
return name.equals(p.name) && // names have identical contentsdimension[0] == p.dimension[0] &&dimension[1] == p.dimension[1] &&dimension[2] == p.dimension[2] &&chlorineLevel == p.chlorineLevel;
}
// return a string containing the pool’s data attributespublic String toString() {
return name + " (" + dimension[0] + " x " + dimension[1] +" x " + dimension[2] + " m3, Cl=" + chlorineLevel + " ppm)" ;
}
// return and create a new object, identical in data attributes to this onepublic Object clone() {
PoolC3 p = new PoolC3 (name, dimension[0], dimension[1], dimension[2]);p.chlorineLevel = chlorineLevel; // equalize other attributesreturn p;
}
COMP1100 Lecture 11: Working Classes and Objects 2004 JJ J • I II × 7
Testing Overridden Object Methods: TestObjPooC3.java
PoolC3 pool1 = new PoolC3("Backyard Pool", 10.0, 5.0, 2.0);PoolC3 pool2 = new PoolC3("Jamison Pool", 50.0, 10.0, 2.0);PoolC3 pool3 = pool1; // both point to same objectPoolC3 pool4 = (PoolC3) pool2.clone();
TextStreamWriter.out.println("pool1 is: " + pool1.toString() + ";\n" +"pool2 is: " + pool2 + "\n" // implict conv. to pool2.toString()
);TextStreamWriter.out.println(
"does (pool1==pool3)? " + (pool1==pool3) + "; " +"does (pool2==pool4)? " + (pool2==pool4) + "\n"
);TextStreamWriter.out.println(
"does pool1.equals(pool3)? " + pool1.equals(pool3) + "; " +"does pool2.equals(pool4)? " + pool2.equals(pool4) + "\n"
);pool4.setChlorineLevel(2.0);TextStreamWriter.out.println(
"now pool4 is: " + pool4 + ";\n" +"does pool2.equals(pool4)? " + pool2.equals(pool4)
);
COMP1100 Lecture 11: Working Classes and Objects 2004 JJ J • I II × 8
Running java TestPoolC3
pool1 is: Backyard Pool (10.0 x 5.0 x 2.0 m3, Cl=0.0 ppm);pool2 is: Jamison Pool (50.0 x 10.0 x 2.0 m3, Cl=0.0 ppm)
does (pool1==pool3)? true; does (pool2==pool4)? false
does pool1.equals(pool3)? true; does pool2.equals(pool4)? true
now pool4 is: Jamison Pool (50.0 x 10.0 x 2.0 m3, Cl=2.0 ppm);does pool2.equals(pool4)? false
Questions:
● does pool1.name.equals(pool3.name)?
● does (pool1.name == pool3.name)?
● what if we use pool2 and pool4 instead?
COMP1100 Lecture 11: Working Classes and Objects 2004 JJ J • I II × 9
Assignment 2: Getting Started with PlayDilemma.java
1. understand the problem domain (The Prisoner’s Dilemma) (run PlayDilemma.sol)
2. study/ modify&run / complete key examples:
● Rainfall2.java● labs: table of squares/cubes (wk 4) ; AssignMarks.java (wk 5)
3. the (for) loop in main(): convert the descriptive comments into algorithms
● debugging: useful to print out i, game.movesH[i], game.movesC[i]
4. implementing display(): see other examples that print out arrays
5. implementing getMoveC(): for each strategy, use anif (...) {...} else if (...) {...} else {...}
● note that template currently implements ALWAYS_GRASS
6. implementing printResult():
● again, have loop accumulating a sum (don’t have to use SCORE_MOVE[][])
7. implementing MyPrisoner.getMove(): e.g. a trivial variant of a TIT_FOR_TAT willdo (well)!
8. coding style: use the constants (GRASS etc) in your code instead of 0 etc
COMP1100 Lecture 13: Arrays of Objects and Libraries 2004 JJ J • I II × 1
Arrays of Regular (Reference) Objects
Ref: L&L sect 6.1, Riley sect 12.6–12.7
● recall from the Two-Dim. Arrays lecture: an array’s element type can be of any type
■ this can include reference types, e.g. String● e.g. ReverseSentence.java (just after main()):
TextStreamWriter.out.print("Type in number of words in a sentence: ");int numWords = TextStreamReader.in.readInt();int i;String[] words = new String[numWords]; // create array of Strings object
TextStreamWriter.out.print("Type sentence of " + numWords + " words: ");for (i = 0; i < numWords; i = i+1) {
// read next ‘word’ (sequence of non-space characters) into word[i]words[i] = TextStreamReader.in.readStringObject();
}TextStreamWriter.out.print("The reversed sentence is: ");for (i = numWords-1; i >= 0; i = i-1) {
TextStreamWriter.out.print(words[i] + " ");}TextStreamWriter.out.println();
COMP1100 Lecture 13: Arrays of Objects and Libraries 2004 JJ J • I II × 2
Arrays of Regular Objects: Creation
● runn ing the program (java ReverseSentence):
Type in number of words in a sentence: 3Type sentence of 3 words: Short is SweetThe reversed sentence is: Sweet is Short
● corresponding object diagrams for words array
before 1st loop: after 1st loop:
length:words:
String[3]
3
0 1 2
null null null
length:
String
’t’’r’’o’’h’’S’words:
String[3]
3
0 1
String
’t’’e’’e’’w’’S’
String
’i’ ’s’
2
COMP1100 Lecture 13: Arrays of Objects and Libraries 2004 JJ J • I II × 3
Review: ‘Normal’ and ‘Static’ Features of (Reference) Classes
● in a reference class (i.e. one which manufactures objects):
■ there is essentially a copy in memory of each ‘normal’ feature (data attribute ormethod) per object
◆ e.g. TestPoolC3.java: pool1 = new PoolC3(...);pool1.print()
length: 3
...........
double[3]
5.0 2.010.0
....’B’ ’a’ ’o’ ’l’’c’
length: 13
name
chlorineLevel
classPoolC
dimensiondouble[]
String
double
0.0
methods
attributes
PoolC3()
volume()
print()
◆ hence an object must be created before that feature can be accessed
● however, if a feature is declared static, there is only 1 copy of that feature perclass
■ no object of that class need be created to access that feature■ the feature belongs to the class itself
COMP1100 Lecture 13: Arrays of Objects and Libraries 2004 JJ J • I II × 4
Library Classes and the static Qualifier
Ref: L&L sects 2.8, 5.1; Riley sect 15.3–15.4
● e.g. the Java Math class consists purely of static constants and methods(functions)public class Math { // library
static final double PI = 3.142.... ; // a constantstatic double cos (double num) { // a function
...}...
}
The library can be used by a client class as follows:double y = Math.cos( Math.PI / 4.0 ); // cosine of 45 degrees
● from an external (client) class, these features are accessed via
‘ClassName.FeatureName’ (instead of ‘ObjectName.FeatureName’)
● when should a feature be declared static?
■ it is normally sensible to declare constants as static■ methods that do not access non-static features should also be made static■ why is the main program routine declared as public static void main(...) ?
COMP1100 Lecture 13: Arrays of Objects and Libraries 2004 JJ J • I II × 5
Class Development using a Library: the DArray.java library
● recall from the Rainfall3.java program, there were generic double[] routines
● these can be put (unmodified) into a DArray.java ‘library’ style of class
● Rainfall4.java is now much simplified; it uses these as follows;TextStreamWriter.out.println(
"Total rainfall = " + DArray.sumArray(rainfall.rain));TextStreamWriter.out.println(
"Max rainfall in one day = " + DArray.maxArray(rainfall.rain));TextStreamWriter.out.println(
"Dry days = " + DArray.countValues(0.0, rainfall.rain));
(the program’s behaviour is unchanged)
● the static qualifier also permits a procedural style of programming in Java
■ this is applicable in many situations (‘Horses for Courses’)
■ it has been importnat to the widespread acceptance of Java
COMP1100 Lecture 13: Arrays of Objects and Libraries 2004 JJ J • I II × 6
Scope of Identifiers
Ref: L&L sect 4.2, Riley sect 4.3-4.4
● an identifier is the name of something in a program:
■ e.g. an attribute, or a local variable, a formal parameter, or routine
● the scope of an identifier is the part of the program where the identifier has
meaning,
■ in other words, where the identifier can be used
● an identifier can only be used within the scope of its declaration
● an identifier must unambiguously identify the thing it is naming
■ i.e. you can’t use the same identifier for two different things within the same
scope
● the compiler knows about scope and will produce an error message if:
■ you try to use an identifier outside of its in scope (or it it is not declared at all)
■ you try to reuse an identifier that is already in use in the current scope
COMP1100 Lecture 14: Files and Scope of Identifiers 2004 JJ J • I II × 1
The Scope of Local Variables
● the identifiers naming local variables have meaning only within the routine in which
they are declared
● what happens if you use the same identifier, say i, in two different routines?
● there will be no ambiguity, since their scopes does not overlap
■ effectively, they will be two different variables
● example: Rainfall2.java
■ days and rainfall only have scope within main()
◆ note: the scope begins from the point after which they are declared!
◆ coding style: generally preferable to declare locals at the top of the routine
■ the scope of total, declared in reportTotalRain(), is within the ‘body’ of
that routine
◆ i.e. within the ... of public void reportTotalRain() { ... }
■ the scope of d, declared in reportTotalRain(), is within the for loop within
that routine
◆ d, declared in reportMaxRain() is effectively a different variable
COMP1100 Lecture 14: Files and Scope of Identifiers 2004 JJ J • I II × 2
Scope of Features of a Class (Attributes and Methods)
● the identifiers naming attributes and methods have a scope which is the whole
class of which they are features
■ e.g. in Rainfall2.java, consider the rain and numberOfDays attributes
◆ these can be used directly in any non-static methods within the same class
(eg. getRainData())
■ similarly, in PlayDilemma.java, we can access the (constant) data attributes
such as GRASS and SCORE_MATRIX directly from within main() or any other
method (e.g. getMoveC())
◆ we can also access the attribute movesH directly from within the display()
● thus any local variables of routines within a class cannot have the same names as
any of the features of the class
● from outside the class, i.e. from a client class, the features of the supplier class
must be referred to using the dot notation
■ for non-static features: objectName.featureName, and for static features:
className.featureName
COMP1100 Lecture 14: Files and Scope of Identifiers 2004 JJ J • I II × 3
Accessing Features of a Class within Static Methods)
● however, we cannot directly access non-static features of a class in the same
way from within any static methods of that class
■ this is because static methods have no associated object of their class when
they are called
● e.g. inside the main() method of Rainfall2.java, we can only access
numberOfDays by first creating a Rainfall2 object (e.g. rainfall) and
accessing it through that (e.g. rainfall.numberOfDays)
■ similarly, we had to access the dryDays() method as rainfall.dryDays()
● similarly within the main() routine of PlayDilemma.java, we had to create a
PlayDilemma object game
■ we can then access the display() method through game.display(i)
■ we can then access the movesH attribute through game.movesH[i]
COMP1100 Lecture 14: Files and Scope of Identifiers 2004 JJ J • I II × 4
Scope of Formal Parameters
● for a routine which has parameters, the declaration of the routine specifies the
number and type of the parameters
■ these are termed formal parameters
● e.g. in Rainfall3.java, value and a are the formal parameters
for the routine int countValues(double value, double[] a) { ... }
■ they can be used inside countValues() just like local variables
■ when the call countValues(0.0, rainfall.rain), is made:
◆ the values of the actual parameters (0.0 and the array object reference
rainfall.rain) get assigned to value and a respectively
◆ i.e. value: 0.0
...
length: 31
0 1 30
6.0 0.0 0.0
2 29
double[31]
0.0 3.3rainfall.rain :
a :
● identifiers naming formal parameters of a routine have the same scope as its local
variables
COMP1100 Lecture 14: Files and Scope of Identifiers 2004 JJ J • I II × 5
Formal Parameters – Concepts
● formal parameters are ‘place-holders’ like x in a formula like y = x2−2x + 7
or r in the formula for the area of a circle area = πr2
● when you call a routine which has parameters, you must supply a value of the
correct type to substitute for each formal parameter
■ just as, when you actually want a value calculated from a formula, you have to
provide an actual value for x or r
● the actual parameter can be a general expression which can be evaluated to a
value of the correct type at the time the routine is called
■ a constant, e.g. 7 for an int parameter, or "Baker" for a String parameter
■ a variable of appropriate type, i or str, assuming the variables were
appropriately declared
■ a more general expression, e.g. 2*i + 1 for an int parameter or
words[i] + " " (from ReverseSentence.java) for a String parameter
COMP1100 Lecture 14: Files and Scope of Identifiers 2004 JJ J • I II × 6
Names of Classes
● the scope of the identifiers used as class names is the program system
● e.g. in the TestPoolC3.java and PoolC3.java program system, the identifier PoolC3
is recognized as a class name
● since it uses the same identifier, constructor methods have the same scope
■ in TestPoolC3.java, we could use pool1 = new PoolC3(...);
■ however, to access other methods of PoolC3, we have to use the dot notation
on an already created PoolC3 object
◆ e.g. pool1.print();
COMP1100 Lecture 14: Files and Scope of Identifiers 2004 JJ J • I II × 7
Files and I/O
Ref: L&L sect 8.1–8.3; Riley sects 13.1, 13.4–6
● ultimately, for computer programs to be useful, they must operate on data withsome degree of permanence
■ in a computer system, such data is normally stored in files
● in the Unix operating system, we may re-direct the standard input and standardoutput (text streams) to files
■ in the labs of week 5: java AssignMarks < assign.dat
● however, in many circumstances, we need to read and write to specific files
■ thus, we can still use standard input and output for other purposes
● the TextStreamReader and TextStreamWriter classes has been (recently!)extended to access such files as text streams. It hides many details:
■ problems of handling exceptional conditions such as the requested file notexisting, or its data is not properly formatted
■ the conversion of character sequences, (e.g. " 567") into data of theappropriate type (e.g. the integer 567)
COMP1100 Lecture 14: Files and Scope of Identifiers 2004 JJ J • I II × 8
Example: the CopyFile.java Program
public class CopyFile {// read in an input & output file name; copy input file to the output filepublic static void main(String[] args) {
TextStreamWriter.out.print("Type in name of file to copy: ");String inFileN = TextStreamReader.in.readStringObject();TextStreamWriter.out.print("Type in name of the copied file: ");String outFileN = TextStreamReader.in.readStringObject();
TextStreamReader inFile = new TextStreamReader(inFileN);TextStreamWriter outFile = new TextStreamWriter(outFileN);String line;
line = inFile.readLine(); // reads in 1st line of inFilewhile (line != null) { // we havent got to the end of inFile yet
outFile.println(line); // copy last line to outFileline = inFile.readLine(); // read in next line of inFile
}}
}
COMP1100 Lecture 14: Files and Scope of Identifiers 2004 JJ J • I II × 9
CopyFile.java Program Continued
● running the program from the command line:
partch> cat simplefilethis is a2-line file.partch> java CopyFileType in name of file to copy: simplefileType in name of he copied file: copyofsimplefilepartch> cat copyofsimplefilethis is a2-line file.partch>
● note: the in object is declared in the TextStreamReader class as
static TextStreamReader in;
■ it is implicitly initialized to connect to the standard input text stream
■ note that we access inFile differently
COMP1100 Lecture 14: Files and Scope of Identifiers 2004 JJ J • I II × 10
Game Theory, The Prisoner’s Dilemma and the Fall of Rationality
● Game Theory: the mathematical study of situations of conflict/competition
■ zero-sum games: (the minimax principle, John von Neumann, 1928)
◆ concept of the (perfect) ‘rational player’: will always make the best move to
maximize their score
◆ ⇒ there is a ‘rational’ way to solve any ‘zero-sum’ situation of conflict
■ non-zero-sum games: (equilibrium points, John Nash, 1948)
◆ concept of ‘rational play’: an outcome where both players did as well as they
would if they knew their opponent’s move beforehand
■ the RAND experiments (1950-): early version of the P.D. & other games (with
analysis of Cold War scenarios)
■ applications to economics, military science (tactical & strategic), sport, social &
political science, psychology
● adapting MyPrisoner.java to play other games: simply change the score matrix:
PrisonersDilemma
(
−3 0−5 −1
)
⇒ChickenDilemma
(
−5 0−3 −1
)
■ is there any meaningful definition of ‘rational playing’ for these games?
COMP1100 Lecture 15: Review 2004 JJ J • I II × 1
Review of Concepts: Methods and Parameters
● motivations: clearer program structure, code re-use (same calculations, different
data)
● a method (= routine) declaration defines a ‘subprogram by giving a name to a some
programming code (which can carry out some defined operation
● it may be a procedure or a function (have a void or a non-void type for its return
value)
● the method must be called in order for the statements in the method to be actually
carried out
■ when the call is finished, program control returns to the point just after the call
● it is called because the calling program that called it needs some calculation /
service / action to be carried out (which the method can provide)
■ typically the method will be acting on some data of interest to the caller
■ it may act directly on the attributes of the associated object (for other
information, parameters are required)
COMP1100 Lecture 15: Review 2004 JJ J • I II × 2
Development of a Simple Supplier Class: Position.java
● this class can be considered an ‘object factory’: supplies services to create objects,
modify them in a restricted way, and extract information from them
■ it contains no main() routine
◆ its clients may be other such classes or a ‘main-program’ type of class● the constructor initializes the attributes of the object:
/* simple Position class, based on (x,y) co-ordinates */public class Position {
private double x;private double y;
// sets (x, y) attributes of object to (x0, y0)public Position(double x0, double y0) {
x = x0;y = y0;
}
■ coding style: make data attributes private (so that a client can’t arbitrarily modify
them)
■ ‘function-style’ methods can be provided to allow read-only access (e.g.
getX())
COMP1100 Lecture 15: Review 2004 JJ J • I II × 3
Position.java: Methods for Object Update/Information
● provide (procedure-style) methods to update (in a restricted manner) objects// move object d units north (direction of +ve y-axis)public void MoveN(double d) {
y = y + d;}
// move object d units east (direction of +ve x-axis)public void MoveE(double d) {
x = x + d;}
● provide (function-style) methods to extract information:// string value of Position objectpublic String toString() {
return "(" + x + ", " + y + ")";}
// object’s distance from originpublic double distOrig() {
return Math.sqrt(x*x + y*y);}
COMP1100 Lecture 15: Review 2004 JJ J • I II × 4
DemoPosition.java: a Client of the Position ClassPosition p = new Position(0.0, 0.0);int i;p.MoveE(8.0);for (i=0; i<3; i++) {
TextStreamWriter.out.println("i=" + i + ", p=" + p);p.MoveN(2.0);
}TextStreamWriter.out.println("finally, p=" + p + ", " +
p.distOrig() + " units from the origin");
● running the program (java DemoPosition):
i=0, p=(8.0, 0.0)i=1, p=(8.0, 2.0)i=2, p=(8.0, 4.0)finally, p=(8.0, 6.0), 10.0 units from the origin
● variables at the end of the program:
p:
x:
y:
Position
8.0
6.0
i: 3
COMP1100 Lecture 15: Review 2004 JJ J • I II × 5
Review of Concepts: Objects and Classes
● a class describes the relevant features for a collection of objects
● the class definition describes both the data attributes of these objects, and the
operations that can be performed on them
■ it also provides a ‘template’ for object creation
■ (normally) a constructor method is also provided to complete this
● the primitive types are special kinds of classes; other classes are create ‘proper’
objects and are called reference classes
● class extends the idea of a type; object extends the idea of a variable
COMP1100 Lecture 15: Review 2004 JJ J • I II × 6
Course Reading You Should have Done by Now
Covering the more essential topics:
● Introductory Concepts:
L&L Ch 1; Riley Ch 1
● Objects, Classes and Primitive Types:
L&L sect 2.0-2.9; Riley sects 2.1–2.6, 5.1–5.8
● Control Structures:
L&L sects 3.0–3.2, 3.4–3.7, 3.8–3.9; Riley sects 7.1–7.7, 10.1–10.5
● Arrays:
L&L sects 6.0–6.1, 6.3; Riley sects 12.1–12.7, 12.9
● Classes and Methods:
L&L sects 4.0–4.2, 4.4–4.5; Riley sect 4.1–4.5
Running / modifying / adding extra print statements to the Text’s examples; may be
useful to consolidate your understanding, and develop your intuitions.
COMP1100 Lecture 15: Review 2004 JJ J • I II × 7
COMP1100: Road-map for the Rest of the Semester
1. Fundamental Programming Concepts (in a way, the hardest bit; takes time to master!)
● ‘Catch-up sessions’ (4 × 1 hr, in labs) from week 6 onwards
■ see Peter & John’s consultation pages
● Assignment 2 (have a go, even an incomplete/non-working solution will be worth something!)
● Labs 06–08: reinforce procedures / functions & class design
● Mid-Semester Quiz (week 8, redeemable)
■ aim to consolidate your understanding by then!
● Assignment 3: a small three-class system, with 2-D arrays
2. Data Representation & Algorithms
● lects week 6–7; lab 09 (more theoretical)
3. Advanced Programming Concepts
● lects weeks 8–13; labs 10–13; Assignment 4
● some review of material from module 1
● some topics ‘theoretical’
Note: 2003 pass rate was 73% (67%, adding in the late WDs)
COMP1100 Lecture 15: Review 2004 JJ J • I II × 8
Number Systems
L&L Ch 1. page 8 and App B, Riley App A. page 590.
● Humans, in general, use a ten digit based (i.e. decimal) number system. Each digit
has a value of 0 to 9, an artifact of our physiology rather than any deeper rationale.
● Computers use a two digit based (i.e. binary) number system. Each digit having a
value of 0 or 1 (on or off). There are several reasons for this choice:
■ A binary digit (or bit for short) can represent exactly two values and thus a
one-to-one and onto mapping of the possible values of a bit and the logical
values true and false can be readily be defined.
■ The electronics used to store and manipulate single bits of information is
simpler and more reliable than those used to encode more than two values.
COMP1100 Lecture 16: Binary Numbers 2004 JJ J • I II × 1
Base 2 and Base 10
L&L page 682.
A binary number, like a decimal number, is composed of a sequence of digits. A number
represented by a sequence of binary digits can be translated into our familiar decimal
representation of integers in the following way:
Base 2 (binary) Base 10 (decimal)0 01 1
10 211 3
100 4
Understanding how the decimal system of numbers work also allows you to understand
number systems with different bases.
COMP1100 Lecture 16: Binary Numbers 2004 JJ J • I II × 2
Binary to Decimal
The key with any number system is to add up the contributions of each digit. For a
decimal number the contributions are in powers of ten and for binary numbers the
contributions are in powers of two. For example:
26 25 24 23 22 21 20
... ... ... ... ... ... ...
1 0 1 1 0 0 1... ... ... ... ... ... ...1×26 0×25 1×24 1×23 0×22 0×21 1×20
64 0 16 8 0 0 1
Thus,
10110012 = 6410 + 1610 + 810 + 110
= 8910
we see that number represented by the binary encoding 1011001 is equivalent to the
decimal encoding of 89.
COMP1100 Lecture 16: Binary Numbers 2004 JJ J • I II × 3
Decimal to Binary
L&L page 684.
To convert a number, v, represented in a larger base, n, to a smaller base, k, thecontributions of each of the digits in the smaller base must be calculated. This is doneby calculating the contribution of the least significant digit (k0) first, then the next leastsignificant digit (k1) and so on until the original base n representation is converted tobase k. The contribution of the least significant digit is the remainder of the division of vby k. For example converting 8910 to base two is achieved by:
89÷2 = 44 remainder 1 LSB44÷2 = 22 remainder 022÷2 = 11 remainder 011÷2 = 5 remainder 15÷2 = 2 remainder 12÷2 = 1 remainder 01÷2 = 0 remainder 1 MSB
Thus,
8910 = 10110012
COMP1100 Lecture 16: Binary Numbers 2004 JJ J • I II × 4
Addition and Subtraction
The addition or subtraction of numbers in any base is carried out using the same
approach as that for decimal numbers. For example, the addition of 8910 and 710 using
a binary representation yields:
8910 10110012 +710 1112
carry 1010 01111102
9610 11000002
The subtraction of 710 from 8910 yields:
8910 10110012 −710 1112
carry 0010 00011002
8210 10100102
COMP1100 Lecture 16: Binary Numbers 2004 JJ J • I II × 5
Multiplication and Division
The multiplication and division of base two numbers can be performed in the sameway as that of decimal numbers, unlike decimal you do not need to know you times tables.
The evaluation of v× u can be performed by calculating
the impact each digit of u has on the result. Each digit
of u is multiplied by v and the result shifted left by the
power of that digit. For example (in decimal) 2 × 23 =
2× 2× 101 + 2× 3× 100. Multiplication follows the same
pattern in any base, including binary.
100112 ×1102
1001102 +1001100200110002 carry
11100102
Long division is easier in binary than decimal, since for
each power the dividend will only divide into the quotient
zero or one times. The process of long division is identical,
starting with the largest power (left most position) dividing
the quotient by the dividend and calculating the remainder.
The remainder becomes the new quotient and the process
repeated.
100112
1102 1110011211000002
10011211002
11121102
remainder 12
COMP1100 Lecture 16: Binary Numbers 2004 JJ J • I II × 6
Finite Representation
A computer may interpret and manipulate a set of bits as a numerical value. The
representation of a number in a computer uses a fixed number of bits, even though there
are usually a few hardware dependent sized representations used in a computer. In any
finite representation the range of values that can be represented is limited.
If we consider the representation of non-negative (i.e. unsigned) number using n bits,
then the minimum value is represented by n zeroes (0×2n−1 + . . .+ 0×21 + 0×20 = 0)
and the maximum value is represented by n ones
(1×2n−1 + . . .+ 1×21 + 1×20 = 2n−1).
Bits Min Max4 0 158 0 255
16 0 6553532 0 429496729564 0 18446744073709551615
COMP1100 Lecture 16: Binary Numbers 2004 JJ J • I II × 7
Representation of Signed Numbers
In order to represent signed numbers the computer must also encode the sign of the
number in the available bits. At first glance a simple method would be to use a bit to
indicate whether the number was positive or negative. If the representation of a number
used 4 bits, then the numbers 510 and −210 could be represented by:
+510 = 01012−210 = 10102
Adding 01012 and 10102 using standard binary addition would yield 11112 (−710)
where as the correct answer would be 00112. As such this encoding requires the
computer to known that the numbers are signed and alter its behaviour according to the
signs of the numbers.
COMP1100 Lecture 16: Binary Numbers 2004 JJ J • I II × 8
Two’s Complement Representation
The two’s complement representation of signed numbers enables values to be added(or subtracted) using common add and subtract mechanisms, reducing hardwarecomplexity.
The two’s complement representation of signed positive numbers remains the same,e.g. a four bit representation of +510 is 01012.
A negative number, −v, is represented using the two’s complement encoding bycomplementing the bits for the encoding of v and adding 1. Thus, the two’s complementrepresentation of the value −210 using 4 bits is:
v = 00102
v̄ = 11012
v̄ + 1 = 11102
So the addition of −210 = 11102 to +510 = 01012 using standard addition yields thecorrect result of 00112.
Key to the two’s complement number representation is the equivalence of addition. Thiscan be seen by the wrap around effect of addition the value 1 to −1.
COMP1100 Lecture 16: Binary Numbers 2004 JJ J • I II × 9
Two’s Complement Range
Each two’s complement number may represent a range of values. The minimum value
that can be represented is a one bit (negative sign) followed by all zeros. While the
maximum value is a zero bit (positive sign) followed by all ones. Thus,
Bits Min2 Max2 Min10 Max102 10 01 −2 13 100 011 −4 34 1000 0111 −8 78 10000000 01111111 −128 127
The range of a two’s complement number represented using n bits is from −(2n−1)
to 2n−1−1.
COMP1100 Lecture 16: Binary Numbers 2004 JJ J • I II × 10
Java Primitive Integer Types
The Java specification defines several primitive types. Five of those primitive types are
variants of a fixed size representation of integer values:
Type Category Bits Minimum Maximumbyte signed 8 −128 127char unsigned 16 0 65535short signed 16 −32768 32767int signed 32 −2147483648 2147483647long signed 64 −9223372036854775808 9223372036854775807
COMP1100 Lecture 16: Binary Numbers 2004 JJ J • I II × 11
Binary Fractions
● Same approach for the representation of a number in binary or in decimal.
● A “binary point” delimits whole and fractional parts.
● Fractional binary numbers can be translated into decimal in the following ways:
Base 2 (binary) Base 10 (decimal)0.001 0.125
0.01 0.250.1 0.51.0 1.0
10.0 2.0● The contribution each digit underpins both representations.
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 1
Binary to Decimal
● Conversion of a binary representation of a whole number to a decimalrepresentation by adding the contribution of each digit (see Lec. 16 slide 2).
● Conversion of fractional component is approached in the same way.
● The contribution of each digit is based on the power associated with each digit. Forexample,
23 22 21 20 . 2−1 2−2
... ... ... ... ... ... ...
1 0 1 1 . 0 1... ... ... ... ... ... ...1×23 0×22 1×21 1×20 . 0×2−1 1×2−2
8 0 2 1 . 0 .25
Thus,
1011.012 = 810 + 210 + 110 + 0.2510
= 11.2510
we see that number represented by the binary encoding 1011.01 is equivalent tothe decimal encoding of 11.25.
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 2
Decimal to Binary
● Conversion of whole number represented in a larger base, n, to a representation
using a smaller base, k, by repeatedly dividing the whole part of the number by k.
● Conversion of the fractional part, f , mirrors that of the whole part as follows:
■ Most significant digit d′ (power of k−1) is the result of d′. f ′ = f × k.
■ Next most significant digit d′′ (power of k−2) is the result of d′′. f ′′ = f ′× k.
■ And so on.
● For example converting 0.687510 to base two is achieved by:
0.6875×2 = 0.375 overflow 1 MSB0.375×2 = 0.75 overflow 00.75×2 = 0.5 overflow 1
0.5×2 = 0 overflow 1 LSB
Thus,
0.687510 = 0.10112
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 3
Floating Point Numbers
● Large range of values can be represented with a finite representation.
● Computers use a binary form of exponential representation.
● The form of decimal “scientific notation” can also be used for the binary
representation of numbers. For example:
1. Decimal 1999 = 1.999×103.
2. Binary 1010.11 = 1.01011×1011 (note that both the power and the exponent
are represented by binary numbers and in decimal would be written 23)
3. Binary 0.01 = 1.0×10−10.
● By convention the binary point “floats” until the mantissa has a “normalized” form.
■ A normalized form usually has one digit to the left of the binary point.
● In a computer word, a fixed size set of bits, separate storage is assigned to
represent the exponent and the mantissa.
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 4
Exact Representation
● Most numbers that can be represented using a fixed number of decimal digits can
not be represented accurately using a fixed number of digits in binary.
● For example, 0.110, in binary produces a recurring binary number:
0.1×2 = 0.2 overflow 0 MSB0.2×2 = 0.4 overflow 00.4×2 = 0.8 overflow 00.8×2 = 0.6 overflow 10.6×2 = 0.2 overflow 10.2×2 = 0.4 overflow 0 repeated
● A finite representation of a recurring value is alway inaccurate.
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 5
IEEE 754 Single Precision
● IEEE 754 single precision format specifies the format for encoding a floating point
number using 32 bits.
■ Sign bit (s) for the sign of the mantissa, 0 for positive and 1 for negative.
■ Mantissa (m) represented in 23 bits. Since the mantissa is normalized there is
a leading one which does not need to be recorded. The result is a precision
of 2−24 ≈ 10−7.
■ Exponent (e) stored in 8 bits with excess-127 notation, i.e. 127 is added to the
actual exponent value resulting in the exponent being recorded as an unsigned
number.
e e e e e e e e m m m m m m m m m m m m m m m m m m m ms m m m
03031 2223
exponentsign mantissa
■ There are special numbers for representing +∞, −∞ and NaN (Not-a-Number).
● IEEE 754 double precision uses a single sign bit, a 52 bit mantissa and an 11 bit
exponent.
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 6
IEEE 754 Single Precision Example
Conversion from a non-integer decimal number, 5.6875, to an IEEE 754 single precision
floating point number combines several of the steps:
1. Convert the non-fractional part, 510 = 1012.
2. Convert the fractional part, 0.687510 = 0.10112.
3. Normalize the result (all values in binary), 101.1011 = 1.011011×1010.
4. Convert to IEEE 754 format:
a. Sign 0 (positive)
b. Mantissa 1.011011 remove leading one 011011.
c. Exponent (add 127) 102 + 12710 = 102 + 11111112 = 100000012.
d. Combine parts 01000000101101100000000000000000.
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 7
Scale of Exact Numbers
● The set of exact numbers representable by the mantissa is scaled by the exponent.
● For example a two digit precision decimal representation with exponent can
represent the following numbers exactly:
1.0 1.1 1.2 1.3 . . . 9.91.0×100 1.1×100 1.2×100 1.3×100 . . . 9.9×100
10 11 12 13 . . . 991.0×101 1.1×101 1.2×101 1.3×101 . . . 9.9×101
110 110 120 130 . . . 9901.0×102 1.1×102 1.2×102 1.3×102 . . . 9.9×102
● A two digit precision decimal number could not represent 1.35 exactly.
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 8
Java Floating Point Primitive Types
● Java uses the IEEE 754 representation of floating point numbers.
● Java defines two primitive types float and double.
● A single precision IEEE 754 variable can be declared by,float x;
● A double precision IEEE 754 variable can be declared by,double y;
● Both float and double numbers have a similar appearance in Java. Constantscan be represented by conventional decimal notation or by an exponential “e”scientific notation:
x = -0.54f; // float literalx = 1.3572e10f; // float literaly = 4.298332e+7d; // double literaly = 1.2832929e-5; // double literal (implicit)y = 2.4; // double literal (implicit)
● Decimal precision of a float is 7 digits.
● Decimal precision of a double is 16 digits.
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 9
Primitive Type Conversion
L&L Ch 2 page 84, Riley Ch 5 page 141.
● Numeric computation may mix
primitive types.
● A narrower type can be implicit
widened (converted) to a wider
type.
● A wider type must be explicitly nar-
rowed (converted) to a narrower
type.
int
long
float
double
short
byte
char
wideningnarrowing
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 10
Primitive Type Conversion
The following code fragment illustrates the implicit widening and explicit narrowing ofprimitive types,
double valueDouble = 1.3237;int valueInt = 10;int resultInt;double resultDouble;
resultDouble = valueDouble * valueInt;TextStreamWriter.out.println("double * [int to double] = " + resultDouble);
resultInt = (int)(valueDouble * valueInt);TextStreamWriter.out.println("(double * [int to double]) to int = " + resultInt);
resultInt = valueInt * (int)valueDouble;TextStreamWriter.out.println("int * (double to int) = " + resultInt);
The output of the program fragment is,
double * [int to double] = 13.237
(double * [int to double]) to int = 13
int * (double to int) = 10
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 11
Conversion from Floating Point to Integer
● An float can be converted to an int in two ways:
1. an explicit cast, (int)x, which truncates (ignores) the fractional component
of x, and
2. the use of the math library function, Math.round(x), which returns the nearest
integer.
x (int)x Math.round(x)
1.9f 1 21.2f 1 1-1.2f -1 -1-1.9f -1 -2
● An identical pair of approaches is available for the conversion from double to long.
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 12
Errors in Floating Point Arithmetic
● A floating point quantity, x, can have a positive error, written δx.
● The quantity represented by x is x±δx. δx is the absolute error in x.
● The relative error in x is given by δxx .
● Errors propagate in computations (even exact arithmetic). For example:
t = 42.0±0.5y = 40.0±0.0t − y = 2.0±0.5
The last statement appears less accurate than the first, even though the absolute
error is the same.
● New errors are often introduced in floating computations due to rounding or results
to machine numbers.
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 13
Propagation of Errors
● Error propagation in exact arithmetic.
■ For addition and subtraction add absolute errors. The subtraction of two
similarly sized quantities can be especially dangerous because the relative
error can increase dramatically.
■ For multiplication and division add relative errors.
● Error introduction in floating point arithmetic.
■ Multiplication and division may result in many more digits to the right of the
binary point. Some of these get lost when rounding to machine numbers.
■ Addition of two very differently sized numbers can lose digits from the smaller
number.
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 14
Poorly Behaved Numerical Algorithm
float a, b, c;
// stable, no rounding errorb = 0.25f;// unstable, rounding error// b = 0.1f;
a = b;
for(int i = 0; i < 100; ++ i) {c = 4*b - 3*a;TextStreamWriter.out.println(c, 0, 2);a = b;b = c;
}
This algorithm, behaved as expected when b = 0.25, outputting the following line 100
times,
0.25
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 15
Since the decimal value 0.1 can not be represented exactly in binary this introduces arounding error into the calculation,
c = 4*b - 3*aThe result is a diverging value of c,
0.100.100.10.....0.100.090.080.03-0.11-0.54-1.82-5.67-17.22.....-3511532871848821000000000000000000000.00-10534598615546462000000000000000000000.00-31603797114289987000000000000000000000.00-94811391342869960000000000000000000000.00-?-??
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 16
Appendix A: IEEE 754 Double Precision
● IEEE 754 uses 64 bits.
● The increased size of the mantissa increases the precision.
● IEEE 754 double precision number uses the same basic layout as IEEE 754.
■ Sign bit (s) for the sign of the mantissa, 0 for positive and 1 for negative.
■ Mantissa (m) represented in 52 bits. Since the mantissa is normalized there is
a leading one which does not need to be recorded. The result is a precision
of 2−53 ≈ 10−16.
■ Exponent (e) stored in 11 bits with excess-1023 notation, i.e. 1023 is added to
the actual exponent value resulting in the exponent being recorded as an
unsigned number.
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 17
Appendix B: Special Numbers
● Java has constants defined for IEEE 754 special numbers, −∞, +∞ and NaN.
● Java also has constants defined for the minimum and maximum values that can be
represented with a float and double.
● These constants are defined separately for float and double,
−∞ Float.NEGATIVE_INFINITY Double.NEGATIVE_INFINITY+∞ Float.POSITIVE_INFINITY Double.POSITIVE_INFINITYNaN Float.NaN Double.NaNminimum Float.MIN_VALUE Double.MIN_VALUEmaximum Float.MAX_VALUE Double.MAX_VALUE
● For example,
■ float x = FLOAT.MIN_VALUE;
■ double y = Double.MAX_VALUE;
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 18
Appendix C: Math Package
L&L Ch 2 page 98, Riley Ch 5 page 145.
● Java includes a class (Math) of commonly used math functions.
● Many of the common math functions we expect are defined in the Math class.
● This includes (among others) the following:Method ResultMath.abs(x) calculate |x|Math.round(x) nearest integer to xMath.floor(x) calculate bxc, i.e. highest integer no greater than xMath.ceil(x) calculate dxe, i.e. lowest integer no less than xMath.cos(x) calculate cos(x), i.e. cosineMath.sin(x) calculate sin(x), i.e. sineMath.acos(x) calculate arccos(x), i.e. arc cosineMath.sqrt(x) calculate
√x
Math.pow(x,y) calculate xy
● A description of those can be found in the Java API documentation, see
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html
COMP1100 Lecture 17: Floating Point Numbers 2004 JJ J • I II × 19
Algorithms
● so what is an algorithm?
■ from the Macquarie dictionary:
an effective procedure for solving a particular mathematical problem in a
finite number of steps
■ from the Glossary in the back of Simple Program Design:
A set of of detailed, unambiguous and ordered instructions developed to
describe the processes necessary to produce the desired output from
given input
● is similar to the idea of a recipe (in cooking):
■ given some ingredients (flour, sugar, butter. . . ) what sequence of processing
steps will produce a cake?
■ in the object-oriented paradigm, the description of the ingredients (data) is just
as important as that of the steps!
■ this is also what we think of in computing: an algorithm results in a
transformation of data in a finite number of steps
COMP1100 Lecture 18: Algorithms—Searching 2004 JJ J • I II × 1
Lewis & Loftus page 131 and Riley page .
● from Robertson p5 of Simple Program Design:
An algorithm is like a recipe: it lists the steps involved in accomplishing a
task. It can be defined in programming terms as a set of detailed,
unambiguous and ordered instructions developed to describe the
processes necessary to produce the desired output from a given input.
● an algorithm is often described in pseudocode—a structured form of natural
language that is easily translated to a programming language.
● an algorithm must:
■ be lucid, precise and unambiguous,
■ give the correct solution for all input over which it operates, and
■ eventually terminate.
COMP1100 Lecture 18: Algorithms—Searching 2004 JJ J • I II × 2
Searching
● a common task is to find a particular item in a collection of items.
● there are several standard searching algorithms.
● the approach taken is in part dependent upon the structures used to maintain and
represent a collection.
● the form of data structure organization is characterized by two extremes:
■ sequential—the items form a chain. In order to access an item the chain must
be traverse until the item of interest is obtained, e.g.:
◆ linked list.
■ direct—the items form some structure which where any item can be accessed
immediately, e.g.:
◆ an array.
COMP1100 Lecture 18: Algorithms—Searching 2004 JJ J • I II × 3
Searching Unordered Arrays
● check each element in turn until a match or all elements have been exhausted.
● slightly more formally:
1. start index i at the lower bound (0) of the array2. while there are more elements to check
a. if element at index i matches then return index ib. else advance index i to next item
3. end loop4. no match found so return −1
● for an array of doubles in Java:
public static int linearSearch(double value, double[] a) {for(int i = 0; i < a.length; ++ i) {
if (a[i] == value) {return i;
}}return -1;
}
COMP1100 Lecture 18: Algorithms—Searching 2004 JJ J • I II × 4
Searching Ordered Arrays
● an ordering gives us more information to work with and help reduce search times.
● a simple optimization to the unordered search would be to stop when we reach an
element that is greater than the one we are interested in.
■ this is still linear (i.e. proportional to n).
■ it can reduce the amount of time spent searching when the element is not in the
array.
● the Java code of the previous slide would be modified:
public static int linearOrderedSearch(double value, double[] a) {
for(int i = 0; i < a.length && a[i] <= value; ++ i) {
if (a[i] == value) {
return i;
}
}
return -1;
}
COMP1100 Lecture 18: Algorithms—Searching 2004 JJ J • I II × 5
Binary Search on Ordered Arrays
● we can do better that linear time for search of ordered arrays since:
■ an ordering provides additional information.
■ direct access enables any element to be checked at the same cost.
● a binary search divides an array into two parts, and given the ordering of elements
it is simple to determine which is the only have that could contain a match. The
remainder of the array is divided and the process repeated until the element is
found to there are no elements that can be checked.
● the time it takes a binary search to run is proportional to log2 n instead of n.
1 4 5 6 8 9 10 15 20 21 23 34 50
lower upperchk
COMP1100 Lecture 18: Algorithms—Searching 2004 JJ J • I II × 6
Binary Search
COMP1100 Lecture 18: Algorithms—Searching 2004 JJ J • I II × 7
public static int binarySearch(double value, double[] a) {int low = 0;int high = a.length;
for(; low < high;) {int index = low + (high - low) / 2;
if (a[index] < value) {low = index + 1;
} else if (a[index] == value) {return index;
} else {high = index;
}}
return -1;}
Note: for(; cond;) is equivalent to while(cond)
Example Trace
● binary search for value 8
a[6] = 10 low=0 high=13
a[3] = 6 low=0 high=6
a[5] = 9 low=4 high=6
a[4] = 8 low=4 high=5
● binary search for value 50
a[6] = 10 low=0 high=13
a[10] = 23 low=7 high=13
a[12] = 50 low=11 high=13
● binary search for value −1
a[6] = 10 low=0 high=13
a[3] = 6 low=0 high=6
a[1] = 4 low=0 high=3
a[0] = 1 low=0 high=1
COMP1100 Lecture 18: Algorithms—Searching 2004 JJ J • I II × 8
16 32 6448
16
48
64
32
figure showing comparision between n and logn
COMP1100 Lecture 18: Algorithms—Searching 2004 JJ J • I II × 9
Examples
● for small values of n the search time may not be significant.
● for large values of n the search algorithm may become a dominant cost of a
programs execution.
● for example, a telephone book of 100,000 entries:
■ using a linear search an average of 50,000 comparisons would be needed to
find an entry.
■ using a binary search at most 17 or 18 comparisons (log2(100000) ≈ 17) would
be needed to find an entry (see slide 6).
● the ATO may have many 100’s of millions of records.
■ searching 100,000,000 records using a binary search would take no more
than 28 comparisons.
■ searching 100,000,000 records using a linear search would take an average
of 50,000,000.
COMP1100 Lecture 18: Algorithms—Searching 2004 JJ J • I II × 10
Sorting
Lewis & Loftus page 339 and Riley page 458
● searching in an ordered set of data structures reduces lookup times
● counter part to searching is sorting
■ if allot of lookups are going to be performed, then the cost sorting (once) may
be comparatively small
● there are many sorting algorithms with varying time costs
● Selection Sort and Insertion Sort are two straightforward sorting algorithms
■ suitable for arrays that are not too large
■ easy to understand
■ these algorithms are n2, i.e. they take up to kn2 steps
◆ as the number of items to sort (n) increases the time to sort them goes by n2
◆ double the number of items and the time goes up by a factor of 4
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 1
Selection Sort
● the idea is to select the correct value to put in each position of the array
■ the values are to be sorted from smallest to largest
■ the first item must be the smallest value for the whole array
1. find the smallest item in the whole array
2. exchange the smallest item with item in position 0
■ the second item must then be the smallest value of the remaining (unsorted)
items
1. find the smallest item in the remaining n−1 items
2. exchange the item in position 1 with the smallest item
■ similarly for each of the remaining items
● what control structure forms the basis of processing the array?
● for example
2.0 5.0 4.0 3.0 1.0
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 2
● The Selection Sort algorithm can be expressed slightly more formally using
pseudocode as
1. start at the first element in array a, i = 0
2. while i < a. length−1 of array
a. find position of smallest value in the range from i to a. length−1
b. swap the item at position and the item at i
● why do we not process the why do not process the last item, i.e. from a. length−1
to a. length−1?
■ an array of a single item is always sorted
● what different would it make if condition of the while loop was i < a. length?
■ it would not affect correctness
■ it would not change the outcome, but wastes effort
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 3
● a Java equivalent of the pseudocode is
public void sort(double[] array) {
for(int i = 0; i < array.length - 1; ++ i) {
int smallI = indexOfMinValue(array, i, array.length);
swap(array, i, smallI);
}
}
● given that initially array = {2.0,5.0,4.0,3.0,1.0}
● the array after each iteration is
initially 2.0 5.0 4.0 3.0 1.0i = 0 1.0 5.0 4.0 3.0 2.0i = 1 1.0 2.0 4.0 3.0 5.0i = 2 1.0 2.0 3.0 4.0 5.0i = 3 1.0 2.0 3.0 4.0 5.0
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 4
● the sort method for uses a indexOfMinValue to find the index of the minimum
value in part of the array
● the Rainfall3.java example of lecture 13 uses a method for finding the maximum
value in an array
● what changes would we make to this method would we make for it to be used for
indexOfMinValue?
● the indexOfMinValue method could be writtenprivate static int indexOfMinValue(double[] array, int lo, int hi) {
int jMinVal = lo;double minVal = array[lo];
for(int j = lo + 1; j < hi; ++ j) {if (array[j] < minVal) {
minVal = array[j];jMinVal = j;
}}
return jMinVal;}
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 5
● why is the time taken to sort an array using Selection Sort is proportional to n2?
■ finding the position of the smallest value in the array requires n−1 comparisons
■ finding the position of the next smallest value in the array requires n−2
■ and so on
● thus the time taken is proportional to
(n−1) + (n−2) + (n−3) + . . .+ 2 + 1 = n(n−1)/2
● as such the time is bound by the curve n2
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 6
Insertion Sort
● the idea is to insert each new item into the correct position of an already sortedarray
■ an array is divided into sorted and unsorted parts◆ an array of one element is always sorted
■ items are taken from the unsorted part and inserted into the sort part, shrinkingthe unsorted part and expanding the sorted part.
● initially the first item forms the sorted part
● the first item from the unsorted part is taken and inserted into the correct position ofthe sorted part of the array
● the second item, i.e. first item from the unsorted part, is either inserted before orafter the first item, and shrinking the unsorted part and expanding the sorted part.
● this is repeated until the unsorted part is reduced to zero size
● as with Selection Sort the primary control structure is Repetition.
● for example
2.0 5.0 4.0 3.0 1.0
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 7
● given that initially array = {2.0,5.0,4.0,3.0,1.0}
● the array after each iteration is
initially 2.0 5.0 4.0 3.0 1.0i = 1 2.0 5.0 4.0 3.0 1.0i = 2 2.0 4.0 5.0 3.0 1.0i = 3 2.0 3.0 4.0 5.0 1.0i = 4 1.0 2.0 3.0 4.0 5.0
● slighly more formally:
1. start with the second item of array a, i.e. i = 1
2. while i < a. length (upper to the last item of the array a)
a. insert the item from position i into the sorted part of the array (0 to i−1)
b. move to next unsorted item, i.e. increment i
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 8
● a Java implementation of an Insertion Sort
public void sort(double[] array) {
for(int i = 1; i < array.length; ++ i) {
insert(array, i);
}
}
● now consider the smaller problem of inserting a new item into an already sorted list
■ find correct position j for new items
■ insert item into the sorted array at position j
● this is an appropriate breakdown for data structures such as linked lists
● for an array the approach must be a variation on this theme
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 9
● method for taking element and inserting
public void insert(double[] array, int i) {
int j;
double temp = array[i];
for(j = i; 0 < j && temp < array[j - 1]; -- j) {
array[j] = array[j - 1];
}
array[j] = temp;
}
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 10
● single method implementation
public void sort(double[] array) {
int i;
for(i = 1; i < array.length; ++ i) {
int j;
double temp = array[i];
for(j = i; 0 < j && temp < array[j - 1]; --j) {
array[j] = array[j - 1];
}
array[j] = temp;
}
}
● using the on of the sort classes TestSort.java
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 11
● why is the time taken to sort an array using Insertion Sort proportional to n2?
■ item from position 1 requires 1 comparison
■ worst case item from position 2 requires 2 comparisons
■ worst case insertion of the item from position i requires i−1 comparisons
● thus the worst case time taken is proportional to
1 + 2 + . . .+ (n−3) + (n−2) + (n−1) = n(n−1)/2
● as such the time is bound by the curve n2
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 12
Bubble Sort
● bubble sort operates by allowing large values to “bubble up” to the top of the array
● it terminates when a complete run through the array does not have any “bubbling”
of values
● bubble sortpublic void sort(double[] array) {
int i, top;boolean interchange;
for(top = array.length, interchange = true; interchange; -- top) {for(i = 1, interchange = false; i < top; ++ i) {
if (array[i-1] > array[i]) {swap(array, i-1, i);interchange = true;
}}
}}
COMP1100 Lecture 19: Algorithms—Searching 2004 JJ J • I II × 13
Properties and Costs
● an algorithm must provide a correct solution to a problem for a given context,
furthermore it must also be
■ lucid
■ precise
■ unambiguous
● simple, easy to understand algorithms may satisfy the above requirements for
clarity, however they
■ often overlook the subtlies of the context
■ are often less efficient than those that require more thought
● efficiency consideration can involve both
■ the time cost of an algorithm
■ the space requirements of an algorithm
● we only consider the time costs of an algorithm
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 1
Algorithmic Time
● the problem size is specified as n, for example n may describe the number of
■ elements in an array
■ items in a list
■ elements in a matrix
■ terms in an polynomial
● the execution time roughly measures the number of operations performed by an
algorithm as a function of the problem size
● timing comparison between algorithms are concerned with the asymptotic limit of
large problem sizes (i.e. large values of n)—big O notation
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 2
Example Big O Time
● frequently the n-dependence of an algorithm’s time fits one of the following
(multiplied by a constant)
■ O(log2(n))—binary search
■ O(n)—linear search
■ O(n log2(n))—quick sort
■ O(n2)—insertion sort, selection sort
■ O(n3)
■ O(2n)
● these “complexity functions” are listed from least costly to most costly
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 3
Time Complexity Functions
1
10
100
1000
10000
100000
1e+06
10 20 30 40 50 60 70 80 90 100
log(x)x
x*log(x)x**2x**32**x
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 4
● performance of computers keeps improving according to Moore’s law, doubling
approximately every 18 months.
■ in order to double a problem size of an n2 complexity algorithm would require
computers to advance three years
■ in order to double a problem size of an n3 complexity algorithm would require
computers to advance four and a half years
● a more efficient algorithm may follow a lower curve on in the previous graph
● a reducing the cost curve presents a substantiate leap in problem size that can be
addressed
● furthermore an efficient algorithm can also take advantage of better hardware,
enabling a faster increase in problem size due to hardware improvements
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 5
Timing Algorithms
● the evaluation of an algorithm through practical experimentation is important:
■ it helps verify that the algorithm is applicable to particular context
■ enables the comparison of similar complexity algorithms that address the same
problem in a common context
● there are a few options for timing code
■ timing from within the application
◆ System.currentTimeMillis() (wall clock time)
■ timing the entire application using time command
◆ time java TestSort
◆ real—the elapse time for execution
◆ user—the time spent execution the application code
◆ sys—the time performing system functions called from the application code
◆ problem—java has long startup time performing many initially costly
operations which can hide the cost of a small problem size
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 6
Testing Algorithms
● the correctness of a formally or informally expressed algorithm can be argued and
its correctness justified
● proving the correctness of an implementation is often vary difficult and in large
systems impractical
● testing provides a higher degree of confidence that the behaviour of the algorithm is
correct
● testing is a compulsory part of software development
● for example, a simple test program TestSort.java might performs the following
1. create an array and initialize it with n numbers
2. print out the array
3. call the sort method of the Selection Sort routine
4. print out the sorted array
● a reasonable comprehensive set of test data encompassing extreme and
non-extreme conditions should be used
● diagnostic writes for debugging of loop indexes and conditions
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 7
Quick Sort
● quick sort approach to sorting an array is to divide and conquer
● quick sort selects a pivot value
● moves all the values less than the pivot below the pivot and all the values higher
than the pivot above the pivot
● it then sorts each half using the same divide and conquer approach
● once the division has reach the point of only considering single data elements then
the sort is complete
● under most conditions quick sort lives up to its name having a complexity of
O(n log2 n)
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 8
● the divide and conquer approach of quick sort can be expressed more clearly as
1. if lo < hi
a. save item at position lo as pivot
b. start with i = lo and j = hi
c. while i 6= j
i. do until j = i or item at position j < pivot
A. decrement j
ii. put item at position j into position i
iii. do until j = i or item at position pivot < j
A. increment j
iv. put item at position i into position j
d. put pivot into position i
e. quick sort data from lo to i−1
f. quick sort data from i + 1 to hi
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 9
Timing Sorting
● test a large range of problem sizes
■ observe the variation in execution times corresponding to the change in
problem size
● test with large problem sizes
● test with a range of data orderings
■ reverse sorted array with its elements sorted in reverse order, sometimes yields
the worst case complexity
■ randomized array with elements set up using a pseudo-random-number
generator Random yielding average complexity
■ sorted elements in order, often yields the best case complexity
● each test will initialize an array of data and time the execution of the sort method on
that data
■ such an initialization can be done in a loop
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 10
Example Quick Sort of an Array
● quick sort of an array of randomly arranged
items array = {7.0,1.0,8.0,10.0,3.0,4.0,14.0,9.0,2.0,16.0} (pivot is red,
consider elements in green)
7.0 1.0 8.0 10.0 3.0 4.0 14.0 9.0 2.0 16.02.0 1.0 4.0 3.0 7.0 10.0 14.0 9.0 8.0 16.01.0 2.0 4.0 3.0 7.0 10.0 14.0 9.0 8.0 16.01.0 2.0 3.0 4.0 7.0 10.0 14.0 9.0 8.0 16.01.0 2.0 3.0 4.0 7.0 8.0 9.0 10.0 14.0 16.01.0 2.0 3.0 4.0 7.0 8.0 9.0 10.0 14.0 16.0
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 11
Timing Tests
● a test program, TimeSort.java, for producing (rough) timings of the sort methods:
SelectionSort.java, InsertionSort.java, BubbleSort.java, HeapSort.java and
QuickSort.java
● the timing results (all in milliseconds) are the elapse times of for the execution of
the sort method, this is suseptible to other activity on the machine
● three different ordering were used
■ random—each run an array is populated with n random numbers was used and
each sort routine was run on exactly the same ordering
■ ascending—values were placed in the array are rom 0 to n−1
■ descending—the values placed in the array are from n−1 0
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 12
Timing Test Results
Randomn insert(ms) select(ms) bubble(ms) heap(ms) quick(ms)
2048 7 7 42 0 14096 40 38 114 2 08192 222 137 454 3 2
16384 446 592 1856 5 332768 1835 2333 7385 11 865536 7229 9389 29617 25 17
Ascendingn insert(ms) select(ms) bubble(ms) heap(ms) quick(ms)
2048 8 9 41 1 04096 42 35 115 1 08192 124 147 453 3 1
16384 459 568 1848 5 432768 1797 2345 7454 14 765536 7872 9405 29880 24 18
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 13
Descendingn insert(ms) select(ms) bubble(ms) heap(ms) quick(ms)
2048 7 7 41 0 14096 40 37 116 1 18192 125 146 454 2 2
16384 456 570 1833 5 332768 1791 2366 7375 13 865536 7233 9855 29780 25 17
Time taken
0
1000
2000
3000
4000
5000
6000
7000
8000
0 20 40 60 80 100
xx*log(x)
x**2
COMP1100 Lecture 20: Efficiency of Algorithms 2004 JJ J • I II × 14
COMP11 Lecture 21: 2004 !"• #$ 1
Advanced Programming Concepts
! Professor Tom Gedeon
" (I am also Head of Department)
" Lecturer in COMP1100
! Contact:
" [email protected] / [email protected]
" 6125 1052 (unless urgent make an appointment via Dept Office)
! Lectures: Nos. 21-30
" Structured Programming
" Representation and Abstract Classes
" Contracts and Assertions
" Inheritance
! Tutes/labs: Nos. 10-13
! Assignments: No. 3
COMP11 Lecture 21: 2004 !"• #$ 2
Structured programming
! Purpose
" Develop reliable software
" Readability
" For humans, not computers
" Teach good programming techniques
! Top-down programming
! Successive refinement
! “GOTO-less” programming
COMP11 Lecture 21: 2004 !"• #$ 3
Programming with GOTOs
! Early programming languages reflected machine language
! Statements were numbered
! Transfers of control were explicit
! Flowcharts were common as:
" Documentation tool
" Design tool
" Programmers, students each had their plastic template with a
multitude of standard shapes.
" Even today, Powerpoint (Microsoft presentation software) includes
in its ‘autoshapes’ a set of Flowchart shapes
COMP11 Lecture 21: 2004 !"• #$ 4
Typical Flowchart Template
! See also Lewis&Loftus, eg figs 3.1, 3.9
COMP11 Lecture 21: 2004 !"• #$ 5
Typical Flowchart
! This is a bit
less hard to
understand
than many
flowcharts!
! What does
the program
calculate?
COMP11 Lecture 21: 2004 !"• #$ 6
Dijkstra’s Letter
! Goto Statement Considered Harmful
" Edsger W. Dijkstra
Comm. ACM, March 1968
! Spaghetti code / Wallpaper / Complexity far from linear
! Discipline called for
! The most cited item in the computing literature?
! Language designers responded
! Pascal had limited GOTOs (early ’70's)
" One could use them to escape from loops
! Feature gone by time of Modula-2
! ... but there was still BASIC
! Result was Structured Programming Discipline
COMP11 Lecture 21: 2004 !"• #$ 7
Structured Programming
! A structured program is one in which the structure of a problem
solution is made clearly visible in the structure of the program.
! The following constructs are deemed natural:
" Compounding (BEGIN, END, semicolons)
" IF ... THEN ... ELSE ...
" WHILE ... DO ...
! Use them as an aid to analysis and design
! There are equivalent forms of conditionals and loops
" Eg Java’s if, switch, and while, do, for statements
COMP11 Lecture 21: 2004 !"• #$ 8
41o
An Example
! Given limits for what temperatures are comfortable, produce a comfort
rating for several temperatures.
" The process is to figure out what to do overall
" Then break the problem down into sub-problems
" Break down any remaining complicated parts until all are ‘simple’
• (Example from Wayne F. Bialas,
www.acsu.buffalo.edu/~bialas).
COMP11 Lecture 21: 2004 !"• #$ 9
Obtain comfort limits in Celsius.Obtain comfort limits in Celsius.
Obtain the number of readings to evaluate.Obtain the number of readings to evaluate.
Successive Refinement
COMP11 Lecture 21: 2004 !"• #$ 10
Obtain comfort limits in Celsius.Obtain comfort limits in Celsius.
Obtain the number of readings to evaluate.Obtain the number of readings to evaluate.
Process the readings.Process the readings.
Successive Refinement
COMP11 Lecture 21: 2004 !"• #$ 11
Obtain comfort limits in Celsius.Obtain comfort limits in Celsius.
Obtain the number of readings to evaluate.Obtain the number of readings to evaluate.
Process the readings.Process the readings.
StopStop
Successive Refinement
COMP11 Lecture 21: 2004 !"• #$ 12
Obtain comfort limits in Celsius.Obtain comfort limits in Celsius.
Obtain the number of readings to evaluate.Obtain the number of readings to evaluate.
Process the readings.Process the readings.
StopStop
Some steps can
be further
refined
Some steps can
be further
refined
Successive Refinement
COMP11 Lecture 21: 2004 !"• #$ 13
Obtain comfort limits in Celsius.Obtain comfort limits in Celsius.
Obtain the number of readings to evaluate.Obtain the number of readings to evaluate.
While there are still readings to process do
Ask for a new reading
Make the announcement
While there are still readings to process do
Ask for a new reading
Make the announcement
StopStop
Successive Refinement
COMP11 Lecture 21: 2004 !"• #$ 14
Obtain comfort limits in Celsius.Obtain comfort limits in Celsius.
Obtain the number of readings to evaluate.Obtain the number of readings to evaluate.
While there are still readings to process do
Ask for a new reading
Make the announcement
While there are still readings to process do
Ask for a new reading
Make the announcement
StopStop
This step needs
more
refinement.
This step needs
more
refinement.
Successive Refinement
COMP11 Lecture 21: 2004 !"• #$ 15
Obtain comfort limits in Celsius.Obtain comfort limits in Celsius.
Obtain the number of readings to evaluate.Obtain the number of readings to evaluate.
While there are still readings to process do
Ask for a new reading
If within the comfort limits
Announce that it’s comfortable
else
Announce that it’s uncomfortable
While there are still readings to process do
Ask for a new reading
If within the comfort limits
Announce that it’s comfortable
else
Announce that it’s uncomfortable
StopStop
Successive Refinement
COMP11 Lecture 21: 2004 !"• #$ 16
Obtain comfort limits in Celsius.Obtain comfort limits in Celsius.
Obtain the number of readings to evaluate.Obtain the number of readings to evaluate.
While there are still readings to process do
Ask for a new reading
If within the comfort limits
Announce that it’s comfortable
else
Announce that it’s uncomfortable
While there are still readings to process do
Ask for a new reading
If within the comfort limits
Announce that it’s comfortable
else
Announce that it’s uncomfortable
StopStop
Successive Refinement
These can
serve as
comments in
your program
These can
serve as
comments in
your program
COMP11 Lecture 22: 2004 • 1
Loops and Methods Loops
Patterns while, for, do Translating between different loop types Iterators
Methods Why? Protection Global vs local
Taxonomies
COMP11 Lecture 22: 2004 • 2
Don't document the program; program the document. “... program structure should be such as to anticipate its adaptations
and modifications. Our program should not only reflect (by structure)our understanding of it, but it should also be clear from its structurewhat sort of adaptations can be catered for smoothly.Thank goodnessthe two requirements go hand in hand.”
» Djikstra
COMP11 Lecture 22: 2004 • 3
Structured Programming A structured program is one in which the structure of a problem
solution is made clearly visible in the structure of the program. The following constructs are deemed natural:
Compounding (BEGIN, END, semicolons) IF ... THEN ... ELSE ... WHILE ... DO ...
Use them as an aid to analysis and design There are equivalent forms of conditionals and loops
Eg Java’s if, switch, and while, do, for statements
(This was slide 7 in lecture 21)
COMP11 Lecture 22: 2004 • 4
Patterns of Loops Normal While Loop
While not at end-of-file process next input itemwhile ( Expression ) Statement
Repeat-until loop Continue iterating until error is negligible
do Statement while ( Expression ); Count controlled loops:
Do something 50 times Do something for each day of the week Do something with each array elementfor ( For Init ; Expression ; For Update ) Statement
COMP11 Lecture 22: 2004 • 5
An example for statement
int i, sum;for (i=1,sum=0; i<=3; ++i){
sum += i;System.out.println(sum);
}
int i, sum;forfor (i=1,sum=0; i<=3; ++i){
sum += i;System.out.println(sum);
}
COMP11 Lecture 22: 2004 • 6
The for statement using while
int i, sum;i=1, sum=0;while (i<=3){
sum += i;System.out.println(sum);++i;
}
int i, sum;i=1, sum=0;whilewhile (i<=3){
sum += i;System.out.println(sum);++i;
}
COMP11 Lecture 22: 2004 • 7
int i, sum;for (i=1,sum=0; i<=3; ++i){
sum += i;System.out.println(sum);
}
int i, sum;forfor (i=1,sum=0; i<=3; ++i){
sum += i;System.out.println(sum);
}
The for statement again
ADVANTAGEAll control information
is at the top.
ADVANTAGEADVANTAGEAll control informationAll control information
is at the top.is at the top.
COMP11 Lecture 22: 2004 • 8
An example do statement (is really use of do for the same example) (uses our knowledge that loop executed at least once)
int i, sum;i=1, sum=0;do { sum += i;
System.out.println(sum);++i;
} while (i<=3);
int i, sum;i=1, sum=0;dodo { sum += i;
System.out.println(sum);++i;
} whilewhile (i<=3);
COMP11 Lecture 22: 2004 • 9
The do statement using while Initial set of flag to true postpones real test to end of loop
int i, sum; boolean flag;i=1, sum=0; flag=true;while (flag) {
sum += i;System.out.println(sum);++i; flag = (i<=3)
}
int i, sum; boolean flag;i=1, sum=0; flag=true;whilewhile (flag) (flag) {
sum += i;System.out.println(sum);++i; flag = (i<=3)
}
COMP11 Lecture 22: 2004 • 10
An example while statement (is really the while loop version of the for loop)
int i, sum;i=1, sum=0;while (i<=3){
sum += i;System.out.println(sum);++i;
}
int i, sum;i=1, sum=0;whilewhile (i<=3){
sum += i;System.out.println(sum);++i;
}
COMP11 Lecture 22: 2004 • 11
The while statement using do (we will ignore the fact that we know it will execute body at least once)
int i, sum;i=1, sum=0;if (i<=3){ do { sum += i;
System.out.println(sum);++i;
} while (i<=3);}
int i, sum;i=1, sum=0;ifif (i<=3){ dodo { sum += i;
System.out.println(sum);++i;
} whilewhile (i<=3);}
COMP11 Lecture 22: 2004 • 12
The while statement using for The continue terminates the loop - is effectively a short GOTO!
int i, sum;i=1, sum=0;for (j=1; true; ++j){
if (i<=3){sum += i;System.out.println(sum);++i;
}; else continue;;
}
int i, sum;i=1, sum=0;forfor (j=1; true; ++j){
ifif (i<=3){sum += i;System.out.println(sum);++i;
}; elseelse continue;;
}
COMP11 Lecture 22: 2004 • 13
Comparing loop statements while and do loops essentially the same
(can convert to each other) while is more natural / useful Zero or more times versus 1 or more Are general loop statements
for loops clearer if ‘count controlled’ Not as general as while and do Some forms (use of continue) same as a GOTO (ie bad)
Choose a while loop when you don’t know how many iterations arerequired; consider a for loop when you do know the number,especially when you want to count through the iterations.
Collection classes have Iterator objects that simplify iteration over thewhole collection.
COMP11 Lecture 22: 2004 • 14
Iterators Many programming languages have the equivalent of while and do
loops, but Java also provides a valuable device called an iterator(defined in the java.util package) to facilitate iteration over collections.
Using an iterator saves us from the trouble of working out which is thenext item in the collection – instead, we just ask “are there any more?”,and if so, “next please!”.
Iterators combine particularly well with while loops (better than with doloops, which require more complex treatment to deal with emptycollections). First we create the iterator object (here “iter”) for our collection
using its constructor. To ask “are there more objects in the collection?”, we call the
hasNext() method of the iterator. To get hold of the next object in the collection, we call the next()
method of the iterator.
COMP11 Lecture 22: 2004 • 15
General form of iterator use (in pseudo-code)
Iterator iter = myCollection.iterator();while(iter.hasNext()) { call iter.next() to get the next object do something with that object}
java.util.Iterator Returns an Iterator object
public void listNotes(){ Iterator iter = notes.iterator(); while(iter.hasNext()) { System.out.println(iter.next()); }}
Java example of iterator use
COMP11 Lecture 22: 2004 • 16
why methods? well-structured programs use functions to break a complicated task
into more basic subroutines.
Big,complicated
taskSmall, simple task
Small, simple task
Small, simple task
COMP11 Lecture 22: 2004 • 17
why methods? older languages, such as FORTRAN and Pascal, use functions simply
to divide a complicated task into several simpler tasks. object-oriented languages, such as C++ and Java, use methods to
give objects the capability to perform tasks
ObjectObjectObject == DataDataData ++ MethodsMethodsMethods
COMP11 Lecture 22: 2004 • 18
protection one of the purposes of OOP is to minimize the chance that one
section of your program will improperly change objects intended forother sections.
objects in Java can be given one of five levels of access Public - accessible to all methods in all packages Protected - accessed within the declaring class, any subclass, or
class in the same package as the declaring class Default - accessed within the declaring class and any class or
subclass in the same package Private Protected - accessed within the declaring class or subclass Private - accessed only by the same class
COMP11 Lecture 22: 2004 • 19
global objects global objects are accessible by all sections of your program on an
equal basis. any variable declared outside of all methods are global within the
class.local objects
local objects are accessible only by the method in which they reside. any variable declared within a method are local to that method unless
explictly made public.
COMP11 Lecture 22: 2004 • 20
global vs. local
class anexample { static int a = 11; public static void main(String[] args) { int b = 22; System.out.println("1: "+a+b); change(); System.out.println("3: "+a+b); } static void change() { int b; a = 33; b = 44; System.out.println("2: "+a+b); }}
class anexample { static int a = 11; public static void main(String[] args) { int b = 22; System.out.println("1: "+a+b); change(); System.out.println("3: "+a+b); } static void change() { int b; a = 33; b = 44; System.out.println("2: "+a+b); }}
COMP11 Lecture 22: 2004 • 21
class anexample { static int a = 11; public static void main(String[] args) { int b = 22; System.out.println("1: "+a+b); change(); System.out.println("3: "+a+b); } static void change() { int b; a = 33; b = 44; System.out.println("2: "+a+b); }}
class anexample { static int a = 11; public static void main(String[] args) { int b = 22; System.out.println("1: "+a+b); change(); System.out.println("3: "+a+b); } static void change() { int b; a = 33; b = 44; System.out.println("2: "+a+b); }}
global vs. local
1:11 222:33 443:33 22
1:11 222:33 443:33 22
COMP11 Lecture 22: 2004 • 22
Two taxonomies for person
COMP11 Lecture 22: 2004 • 23
Not a taxonomy
Taxonomies are strictly hierarchical
COMP11 Lecture 22: 2004 • 24
Top-down Design Ask yourself, Is the problem at hand:
Sequential? Conditional? Iterative?
If it is, then use Compound statement if or switch Loop construct
But the choice is not always clear. To be continued … examples next lecture
COMP11 Lecture 23: 2004 • 1
Top-down Design Ask yourself, Is the problem at hand:
Sequential? Conditional? Iterative?
If it is, then use Compound statement if or switch Loop construct
But the choice is not always clear. Continued from last lecture
Prime number generation
COMP11 Lecture 23: 2004 • 2
Example - Prime Numbers Initial Problem Statement:
List the prime numbers less then 100.
First Step to Solution:For each integer between 2 and 99 inclusive,if it is a prime then print it.
This refinement of the problem simply comes from viewing theproblem as an iterative one.
We can recognise one of the loop patterns. Need to introduce a variable for the iteration.
COMP11 Lecture 23: 2004 • 3
Step 2 - Partial Coding Here is how it looks now:
for (j = 2; j <= 99; ++j) If j is prime then print it.
Step 3 - Sequential Breakup We can observe the problem can be broken into two tasks
for (j = 2; j <= 99; ++j) { Look for factors of j between 2 and j-1. If j has no such factors then print it.}
We need a variable to communicate between the tasks. Call it factors.It will indicate the number of factors already found.
COMP11 Lecture 23: 2004 • 4
Step 4 - Notice Iterative Naturefor (j = 2; j <= 99; ++j) { factors = 0; For each integer, k, between 2 and j-1, If k divides j then increase number of factors found. if (factors = 0)
Print value of j.}
The first sub-problem is iterative The second is conditional The third is simple
COMP11 Lecture 23: 2004 • 5
Step 5 - Express loopfor (j = 2; j <= 99; ++j) { factors = 0; for (k = 2; j <= j - 1; ++k)
If k divides j then increase number of factors found. if (factors = 0)
Print value of j.}
Now express the rest in Java
COMP11 Lecture 23: 2004 • 6
Step 6 - Final Versionfor (j = 2; j <= 99; ++j) { factors = 0; for (k = 2; k <= j - 1; ++k) {
if (j % k = 0) factors = factors + 1;
} if (factors = 0) {
TextStreamWriter.out.print(j);TextStreamWriter.out.println();
}}
COMP11 Lecture 23: 2004 • 7
Example 2 - Sorting Initial Problem Statement:
Sort an array A[1..n] (into ascending order).
Sorting Illustrated: A 5-element array is here sorted (into ascending order).
Note that numbers do not disappear; they just change position.
COMP11 Lecture 23: 2004 • 8
Step 1 - Asking the Question Prior experience with sorting indicates the algorithm will be iterative. First Step to Solution:
For each integer, j, between 1 and n, inclusive,make sure A[1..j] is sorted.
This refinement of the problem comes from viewing the problem asan iterative one and have an idea about what happens at each stage.
Note that A[1..1] is already sorted.
COMP11 Lecture 23: 2004 • 9
Step 2 - Partial Coding We recognise one of the loop patterns. Need to document the loop with assertions
assert A[1..1] is sorted.for (j = 2; j <= n; ++j) { assert A[1..j-1] is sorted. Insert A[j] into the right place. assert A[1..j] is sorted.}
COMP11 Lecture 23: 2004 • 10
Step 3 - Sequential Breakupassert A[1..1] is sorted.for (j = 2; j <= n; ++j) { assert A[1..j-1] is sorted. 1. Remember A[j] as X 2. Find first index i such that X ≤ A[i] 3. Move A[i..j-1] along one place to A[i+1..j] 4. Put X into A[i] assert A[1..j] is sorted.}
COMP11 Lecture 23: 2004 • 11
Step 4 - Recognise Iterationassert A[1..1] is sorted.for (j = 2; j <= n; ++j) { assert A[1..j-1] is sorted. X = A[j]; Test all indices, I, (from 1) until X ≤ A[i] For each index, k between i+1 and j, move A[k-1] to A[k] A[i] = X; assert A[1..j] is sorted.}
COMP11 Lecture 23: 2004 • 12
Step 4 - Some details Interesting point is that in the loop to move the section of array
elements ‘up one place’ the variable k is counted down from j to i+1inclusive. The reason can be seen by looking at the diagram below.
Suppose we want to move the integers in the section A[4..7] up oneplace:
It is clear we need to move A[7] before A[6] before A[5] before A[4];otherwise something will get overwritten and lost.
COMP11 Lecture 23: 2004 • 13
Step 5 - Final Versionassert A[1..1] is sorted.for (j = 2; j <= n; ++j) { assert A[1..j-1] is sorted. X = A[j]; i = 1; while (X > A[i])
++i; for (k = j; k = i; k--} {
A[k] = A[k - 1] } A[i] = X; assert A[1..j] is sorted.}
COMP11 Lecture 24: 2004 • 1
Top-down Design II Ask yourself, Is the problem at hand:
Sequential? Conditional? Iterative?
If it is, then use Compound statement if or switch Loop construct
But the choice is not always clear. Continued from last lecture where we did Insertion sort (demo) More sorting
Selection sort Bubble sort
COMP11 Lecture 24: 2004 • 2
Example 3 - Sorting again Initial Problem Statement:
Sort an array A[1..n] (into descending order).
Sorting Illustrated: A 5-element array is here sorted (into descending order).
Note that numbers do not disappear; they just change position. This is almost identical to slide 7 of lecture 3.
COMP11 Lecture 24: 2004 • 3
Step 1 - Asking the Question Prior experience with sorting indicates the algorithm will be iterative. First Step to Solution:
For each integer, i, between 1 and n, inclusive,make sure A[i] holds the i’th largest number. Was: A[1..j] is sorted.
This refinement of the problem comes from viewing the problem asan iterative one and have an idea about what happens at each stage.
Note that A[1] already has 1st largest. Was: A[1..1] is already sorted.
There is a subtle but significant difference in the two choices made inExamples 2 and 3.
COMP11 Lecture 24: 2004 • 4
Why / how will this work? On the 1st iteration, A[1] will be set to the largest number.
After that, the 2nd largest number will be (somewhere) in A[2..n]. On the 2nd iteration, A[2] will be set to the 2nd largest number.
After that, the 3rd largest number will be (somewhere) in A[3..n]. etc.
On the last iteration, the array element can be swapped with itself, ornothing needs to be done.
COMP11 Lecture 24: 2004 • 5
Step 2 - Partial Coding We recognise one of the loop patterns. Need to document the loop with assertions
for (i = 1; i < n; ++i) { assert For every j from 1 to i-1, A[j] holds the j’th largest number. Insert A[j] into the right place. assert For every j from 1 to i-1, A[j] holds the j’th largest number.}
assert A[1..1] is sorted.for (j = 2; j <= n; ++j) { assert A[1..j-1] is sorted. Insert A[j] into the right place. assert A[1..j] is sorted.}
Was:
COMP11 Lecture 24: 2004 • 6
Step 3 - Sequential Breakupfor (i = 1; i < n; ++i) { assert For every j from 1 to i-1, A[j] holds the j’th largest number. Find the largest number in A[i..n] Swap it with A[i] assert For every j from 1 to i, A[j] holds the j’th largest number.}
assert A[1..1] is sorted.for (j = 2; j <= n; ++j) { assert A[1..j-1] is sorted. 1. Remember A[j] as X 2. Find first index i such that X ≤ A[i] 3. Move A[i..j-1] along one place to A[i+1..j] 4. Put X into A[i] assert A[1..j] is sorted.}
Was:
COMP11 Lecture 24: 2004 • 7
Step 4 - Recognise Iterationfor (i = 1; i < n; ++i) { assert For every j from 1 to i-1, A[j] holds the j’th largest number. Check each element in A[i..n] If its bigger than previously seen save its location swaptemp = A[loc]; A[loc] = A[i]; A[i] = swaptemp; assert For every j from 1 to i, A[j] holds the j’th largest number.}
COMP11 Lecture 24: 2004 • 8
Step 5 - Final Versionfor (i = 1; i < n; ++i) { assert For every j from 1 to i-1, A[j] holds the j’th largest number. largest = 0; for (k = i; k < n; ++k) {
if (A[k] > largest) { largest = A[k]; loc = k}
} swaptemp = A[k]; A[k] = A[i]; A[i] = swaptemp; assert For every j from 1 to i, A[j] holds the j’th largest number.}
This is Selection sort (demo)
COMP11 Lecture 24: 2004 • 9
Example 4 - Bubble sort Initial Problem Statement:
Sort an array A[1..n] (into ascending order).
Step 1 - Asking the Question Prior experience … “its easy to sort 2 items” Prior experience (2): we need to make progress towards the goal First Step to Solution:
Keep swapping adjacent elementsUntil no more swaps occur
COMP11 Lecture 24: 2004 • 10
Step 2 - Partial Coding We recognise one of the loop patterns.
do Swap adjacent elementswhile (swaps taking place);
Step 3 - Sequential Breakupdo For all elements Compare adjacent elements Swap them if in wrong orderwhile (swaps taking place);
COMP11 Lecture 24: 2004 • 11
Step 4 - Recognise Iteration / Finish Need to document the loop with assertions (from earlier - you do it!)
do swaps = 0; for (i = 1; i < n; ++i) { // For all elements
if (A[i] > A[i + 1] { // Compare adjacent elements swap(A[i]. A[i + 1]) // Swap them if in wrong order
} // end if } // end for iwhile (swaps > 0);
As indicated earlier, this is Bubblesort (demo)
COMP11 Lecture 24: 2004 • 12
Alternative Expressions of BubbleSortfor (i=1; i < n; i++) {
for (j=1; j < n-i; j++)if (A[j+1] < A[j]) { /* compare the two neighbors */
swap(A[j],A[j+1]); /* swap a[j] and a[j+1] */}
}
for(top = array.length, interchange = true; interchange; -- top) {for(i = 1, interchange = false; i < top; ++ i) {
if (array[i-1] > array[i]) {swap(array, i-1, i); interchange = true;
}}
}assert
2004 • 1
Assertions Comments
Good, bad and ugly etc slides from U Alberta D Szafron (here)
Assertions preconditions postconditions class in anu.jar (here)
Design by contract slides from DePaul J Wang (here)
Programming with Assertions in Java by Sun http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html
©Duane Szafron 1999
2
Good Comments and Bad CommentsGood Comments and Bad Comments
A good comment is one that is cherished by aprogrammer for the clarity it brings.
public class Ratio{ /* an object for storing a fraction like 2/3 */
code based on Bailey pg. 8
• A neutral comment is one that neither helps nor hinders the programmer.
protected int numerator; // numerator of ratio
• A bad comment is one that confuses or inhibits the programmer.
public class Ratio{ /* this class is tricky: talk to Bob , it was his
brainwave.*/
©Duane Szafron 1999
3
The Purpose of CommentsThe Purpose of Comments
A comment should describe what a program segmentshould do and under what circumstances it should doit (when).
Comments should be created as soon as a designeror programmer knows the functionality of thesegment being designed or implemented, not after!
A comment allows a programmer to check for thedesired functionality as the code is being written.
©Duane Szafron 1999
4
Sample Comment - Sample Comment - What and WhenWhat and When
public class Ratio{ /* an object for storing a fraction like 2/3 */
public Ratio(int top, int bottom)/*
Initialize the receiver to be the fractionwhose numerator is the top and whosedenominator is the bottom.The bottom cannot be zero.
*/
what
when
code based on Bailey pg. 8
©Duane Szafron 1999
5
good name, nocomment required
Comment Granularity - Comment Granularity - variablesvariables
poor name, comment required
Should every variable declaration be commented?
– If the name of a variable makes its purpose clear, it does notneed a comment.
– If the name does not make it clear, consider a better namerather than a comment.
– The name “follows” a variable to all of its uses, the commentdoes not.
protected int n; // numerator of ratio protected int numerator;
code based on Bailey pg. 8
©Duane Szafron 1999
6
Comment Granularity Comment Granularity - code lines 2- code lines 2
Should every line of code be commented?
– If the names of variables and names of methods makethe purpose clear, it does not need a comment.
for (int i = 0; i < c; i++) l[++e] = s.l[s.s++];
for (int index = 0; index < count; index++)this.list[++this.end] =
source.list[source.start++];
©Duane Szafron 1999
7
Comment Granularity Comment Granularity - code lines 3- code lines 3
– If a line is still complex enough to need a comment,consider splitting it into multiple lines.
for (int index = 0; index < count; index++)this.list[++this.end] =
source.list[source.start++];
for (int index = 0; index < count; index++) {this.end++;this.list[this.end] = source.list[source.start];this.start++;
}
©Duane Szafron 1999
8
Comment Granularity Comment Granularity - classes and methods- classes and methods
Should every class be commented?
– Yes!
Should every method be commented?
– Yes!
©Duane Szafron 1999
9
The Language for CommentsThe Language for Comments
Natural language is not very precise at describingprogram functionality.
Natural language is also verbose.
Mathematics is more precise, but not always aseasy to understand.
In this course, we will use a semi-formal notationcalled preconditions and postconditions for ourmethod comments.
©Duane Szafron 1999
10
PreconditionsPreconditions
A precondition tells when (under what circumstances) amethod can be called:
code based on Bailey pg. 8
public Ratio(int top, int bottom)/*
Initialize the receiver to be the fractionwhose numerator is the top and whosedenominator is the bottom.The bottom cannot be zero.pre: bottom != 0
*/
©Duane Szafron 1999
11
PostconditionsPostconditions
A postcondition tells what a method must do:
code based on Bailey pg. 8
public Ratio(int top, int bottom)/*
Initialize the receiver to be the fractionwhose numerator is the top and whosedenominator is the bottom.pre: bottom != 0post: constructs a ratio equivalent to top/bottom
*/
2004 • 12
2004 • 13
©Duane Szafron 1999
14
AssertionsAssertions
An assertion is a statement about the state of yourprogram that must be true.
Preconditions and postconditions can be expressedas assertions.
Some assertions may be represented as booleanexpressions that can actually be evaluated when theprogram is run.
©Duane Szafron 1999
What is DBC?
Classes of a system communicate withone another on the basis of preciselydefined benefits and obligations.
[Bertrand Meyer, CACM, Vol. 36, No 9, 1992]
©Duane Szafron 1999
What is DBC? (cont.)
Preconditions of methods A boolean expression which is assumed true when the method
gets called
Postconditions of methods A boolean expression which the caller can assume to be true
when the method returns
Class invariants consistency conditions of objects must hold for all instances
©Duane Szafron 1999
Preconditions, Postconditions andClass Invariants
@pre @post @invariant
/** * @invariant gpa >= 0 */class Student {protected _gpa;
/** * GPA always >=0 * @pre gpa >= 0 */void setGPA (double gpa){…}
/** * GPA always >=0 * @post return >= 0 */double getGPA(){…}}
©Duane Szafron 1999
put (x: ELEMENT; key: STRING) is -- Insert x so that it will be retrievable through key.
require count <= capacity not key.empty
do ... Some insertion algorithm ...
ensurehas (x) item (key) = x count = old count + 1
end
Preconditions, Postconditions andClass Invariants (cont.)
e.g., inserting a certain element into a dictionary (a table where each element is identified by a certain character string used as key) of bounded capacity.
http://archive.eifel.com/doc/manuals/technology/contract/pafe.html
©Duane Szafron 1999
The Notion of Contract
Obligations(Must ensure precondition)
Make sure table is not fulland key is a non-emptystring.
(Must ensure postcondition)
Record given element intable, associated withgiven key.
Benefits(May benefit from postcondition)
Get updated table where thegiven element now appears,associated with the givenkey.
(May assume precondition)
No need to do anything if tableis full, or key is emptystring.
Client
Supplier
http://archive.eifel.com/doc/manuals/technology/contract/pafe.html
©Duane Szafron 1999
The Notion of Contract (cont.)
Obligations
Satisfy preconditions
Satisfy postconditions
Benefits
No need to check outputvalues
Result guaranteed tocomply to postcondition
No need to check inputvalues
Input guaranteed to complyto precondition
Client
Supplier
http://archive.eifel.com/doc/manuals/technology/contract/pafe.html
©Duane Szafron 1999
Benefits of Design by Contract
Better understanding of software construction Systematic approach to building bug-free oo systems Effective framework for debugging, testing and quality
assurance Method for documenting software components Better control of the inheritance mechanism Technique for dealing with abnormal cases, effective
exception handling
©Duane Szafron 1999
Current Existing Tools
Formal documentationinformal, implicit vs. formal, explicit
Runtime validationtranslate the contract into runtime assertions
most common
Static analysisuse model checking, theorem prover to analyze at compile time
©Duane Szafron 1999
Current Existing Tools (cont.)
JDK1.4: assert Eiffel
http://archive.eiffel.com
iContractby Reto Kramer, Cambridge Technology Partners
JASShttp://semantik.informatik.uni-oldenburg.de/~jass/
JMSAssertby man machine systems
http://www.mmsindia.com/JMSAssert.html
Jtest and Jcontractby parasofthttp://www.parasoft.com
©Duane Szafron 1999
What are These Tools For?
Most are runtime validation and formaldocumentation
programmer-provided assertions intosource code, using a preprocessor
At runtime, check if these assertionsare violated—possibly, throwexceptions
©Duane Szafron 1999
What are These Tools For? (cont.)
Requirement: programmer needs to writeassertions (preconditions, postconditions,class invariants) in certain documentationformat.
Run the preprocessors (possibly with options)to get the instrumented program.
Result: avoidance of any runtime exceptionsdue to violation of assertions (but still throwother exceptions).
©Duane Szafron 1999
Comparison Between These Tools
Has interfaceto integratewith staticerror checker
YesTool withmultiplefeatures
Specifiedcontract
My Tool
NoYesTool withmultiplefeatures
Specifiedcontract
iContract
NoYesLow levelfeature
Low, notspecific
JDK1.4
StaticAnalysis
RuntimeCheck
UsabilityExpressiveness
©Duane Szafron 1999
Comparison Between These Tools(cont.)
How expressive? How to deal with class hierarchies? Other design issues Implementation issues Additional features
COMP1100 Lecture 26: 2004 • 1
Simulation There is (apparent) randomness in the real world For example:
1. queues, traffic, social systems 2. weather, physical systems 3. economic systems
We need to model such systems. Why?
To test strategies, policies, or designs in these areas
COMP1100 Lecture 26: 2004 • 2
The Monte Carlo Method In Monte Carlo simulations
Identify points of apparently random behaviour Simulate system many times;
Each such simulation is a scenario in whichwe use some device with the same (apparent)random behaviour.
Use of coins, dice, cards, random numbers; Collect statistics about the system. The Monte Carlo simulation technique predates computers.
COMP1100 Lecture 26: 2004 • 3
Monte Carlo Examples Test the design of a system you have for managing the queues at the
checkouts in a supermarket. Simulate several strategies for succeeding in the stock market. What is the chance that a multi-flight trip will be successful given that
each component may be delayed? Simulate the spread of a virus.
Introducing Chance Opting for random decisions Breaking deadlocks Cricket, lotteries Games of chance, Cards and dice Generating random data
COMP1100 Lecture 26: 2004 • 4
Random Number Generators Sequence of numbers < r1, r2, r3, r4, … > May be reals or integers Range and distribution Algebraic basis, deterministic computation Pseudo-randomness How to get really random numbers
COMP1100 Lecture 26: 2004 • 5
An Example Random Number Generator Based on a sequence of 8 digit numbers < r1, r2, r3, r4, … >
rj+1 is found by squaring rj and taking the middle 8 digits of theresult.
The number after 34126975 in the sequence is 65042265, being the middle digits of 1164650422650625.
The next number is 49623633 (middle digits of 4230496236330225)
Normally don't want 8 digit integers; so this generator would normallyscale to give the sequence: 0.34126975, 0.65042265, 0.49623633, 0.50495211, 0.76633393,
0.67692269, 0.24328236 etc. Problems? How about with zero?
COMP1100 Lecture 26: 2004 • 6
Pseudo-Randomness Is pseudo-randomness a bad thing?
Repeatability is very important!
Seeds enable variability and repeatability Use of the system clock Cycle length ‘Warming up’
Rich literature, statistically based
COMP1100 Lecture 26: 2004 • 7
Testing Randomness Suppose the generator employs some mathematical function, F so
that rj+1 = F(rj)
If generated numbers are between 0 and 1 then their mean shouldtend to 0.5
and the fraction in the range 0.3 .. 0.4 should tend to be one tenth.
For any integer, j, we should find rj , rj+1 and rj+2 should be increasingjust as frequently as decreasing.
It should pass the ‘poker test’.
We shouldn't be able to predict simple properties of rj+1 from theapproximate values of rj and rj-1.
COMP1100 Lecture 26: 2004 • 8
A Typical Classpublic class Die { private int top; private int sides; // top face, number of sides
/* A Die has numFaces sides and the top face is random */ public Die(int numFaces) { sides = numFaces; roll(); }
public void roll() { setTop(randInt(1,getSides())); } /* top new val */
public int randInt(int low, int high) { /* = random int in low..high */ return (int) (Math.random()*(high-low+1))+low; }
public int getTop() { return top; } /* = Get top face */ public int getSides() { return sides; } /* = Get no. of sides */ public void setTop(int face) { top= face; } /* Set top to rand val */}
COMP1100 Lecture 26: 2004 • 9
Testing Class Diepublic class TestDie {
public static void main (String[] args) {final int ROLLS = 10000; int total;Die die1 = new Die(6); Die die2 = new Die(6); // 2 six sided dicefor (int j = 0; j < ROLLS; j++) {
die1.roll; die2.roll;total = die1.getTop + die2.getTop;storeResults(total); // details omitted}
displayResults;}
}
COMP1100 Lecture 26: 2004 • 10
Results of TestDie Actual ExpectedOutcome Details Count Count Outcome
2 (1+1) 243 278 23 (1+2, 2+1) 583 556 34 (1+3, 2+2, 3+1) 812 883 45 (1+4, 2+3, 3+2, 4+1) 1162 1111 56 (1+5, 2+4, 3+3, 4+2, 5+1) 1378 1389 67 (1+6, 2+5, 3+4, 4+3, 5+2, 6+1) 1691 1667 78 (2+6, 3+5, 4+4, 5+3, 6+2) 1373 1389 89 (3+6, 4+5, 5+4, 6+3) 1079 1111 9
10 (4+6, 5+5, 6+4) 835 883 1011 (5+6, 6+5) 561 556 1112 (6+6) 283 278 12
COMP1100 Lecture 26: 2004 • 11
Linear Congruential Generators In most applications random numbers are produced by a linear
congruential generator. They are based on a recurrence relationship
rj+1 = (a rj + b) % m m is called the modulus and will be a large integer such as 232. There are good and bad choices for a and b so you would not
write your own random number generator without consulting theliterature.
COMP1100 Lecture 26: 2004 • 12
References Here are some URLs that will give you access to tutorial material on
Monte Carlo techniques and renadom number generation. http://www.maths.abdn.ac.uk/~igc/testing/tch/mx4002/notes/node78.html http://www.taygeta.com/xml/random.xml
Anyone who considers arithmetical methods of producingrandom digits is, of course, in a state of sin.John von Neumann (1951)
http://csep1.phy.ornl.gov/CSEP/RN/NODE6.htmlAnyone who has not seen the above quotation in at least 100
places is probably not very old. D. V. Pryor (1993) http://www.cs.sunysb.edu/~skiena/jaialai/excerpts/node7.html
Roulette wheels generate random numbers (mostly) http://www.fis.unipr.it/mc/pasquali/mc.htm
COMP1100 Lecture 26: 2004 • 13
Assertions (continued) Comments
Good, bad and ugly etc slides from U Alberta D Szafron (here)
Assertions preconditions postconditions class in anu.jar (here)
Design by contract slides from DePaul J Wang (here)
Programming with Assertions in Java by Sun http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html
Continued from Lecture 25.
COMP1100 Lecture 26: 2004 • 14
When not to use assertions Do not use assertions for argument checking in public methods.
Argument checking is typically part of the published specifications Erroneous arguments should result in an appropriate runtime
exception (such as IllegalArgumentException,IndexOutOfBoundsException, or NullPointerException).An assertion failure will not throw an appropriate exception.
Do not use assertions to do any work that your application requires forcorrect operation.
assert names.remove(null); // Broken! - contains an action
boolean nullsRemoved = names.remove(null); // Fixed …assert nullsRemoved; // Works whether or not asserts enabled
COMP1100 Lecture 26: 2004 • 15
Internal invariants Before assertions - use of comments to indicate assumptions about a
program's behavior. E.g. if (i % 3 = 0) { ... } else if (i % 3 = 1) { ... } else { // We know (i % 3 = 2) ... }
Instead should use an assertion if (i % 3 = 0) { ...
Also good for switch default } else if (i % 3 = 1) { ... } else { assert (i % 3 = 2) ... }
COMP1100 Lecture 26: 2004 • 16
Flow of control invariants Before assertions - use of comments to indicate assumptions about a
program's behavior. E.g. void foo() { for (...) { if (...) return; } // Execution should never reach this point!!! }
Instead should use an assertion void foo() { for (...) { if (...) return; } assert false; // Never reach here }
COMP1100 Lecture 26: 2004 • 17
Other assertions preconditions
lock-status preconditions
postconditions saved data to check postcondition
void foo(int [] array) { // Manipulate array ... // At this point, array will contain exactly the ints that it did // prior to manipulation, in the same order. }
class invariants
COMP1100 Lecture 26: 2004 • 18
Saved data postconditions void foo(final int[] array) { // Inner class that saves state & the final consistency check class DataCopy { private int [] arrayCopy; DataCopy() { arrayCopy = (int[]) array.clone(); } boolean isSame() { return Arrays.equals(array, arrayCopy); } } DataCopy copy = null; // Always succeeds; has side effect of saving a copy of array assert ((copy = new DataCopy()) != null); ... // Manipulate array // Ensure array has same ints in same order as before. assert copy.isSame(); }
COMP1100 Lecture 26: 2004 • 19
Class Invariants A class invariants is a type of internal invariant that applies to every
instance of a class at all times, except when an instance is intransition from one consistent state to another.
A class invariant can specify the relationships among multipleattributes, and should be true before and after any method completes.
For complex invariants: combine the expressions that check required constraints into a
single internal method that can be called by assertions
COMP11 Lecture 27: 2004 • 1
Inheritance In this lecture we discuss inheritance:
from Chapter 7 of Lewis and Loftus
and applets: from Chapter 2 of Lewis and Loftus
both of which will be useful for Assignment 4
Chapter 7: InheritanceChapter 7: Inheritance
Presentation slides for
Java Software SolutionsFoundations of Program Design
Third Edition
by John Lewis and William Loftus
Java Software Solutions is published by Addison-Wesley
Presentation slides are copyright 200s by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.
3
InheritanceInheritance Another fundamental object-oriented technique isinheritance, used to organize and create reusable classes
Chapter 7 focuses on:
・ deriving new classes from existing classes・ creating class hierarchies・ the protected modifier・ polymorphism via inheritance・ inheritance hierarchies for interfaces・ inheritance used in graphical user interfaces
4
InheritanceInheritance Inheritance allows a software developer to derive a newclass from an existing one
The existing class is called the parent class, orsuperclass, or base class
The derived class is called the child class or subclass.
As the name implies, the child inherits characteristics ofthe parent
That is, the child class inherits the methods and datadefined for the parent class
InheritanceInheritance To tailor a derived class, the programmer can add newvariables or methods, or can modify the inherited ones
Software reuse is at the heart of inheritance
By using existing software components to create newones, we capitalize on all the effort that went into thedesign, implementation, and testing of the existingsoftware
6
InheritanceInheritance Inheritance relationships often are shown graphically in aUML class diagram, with an arrow with an open arrowheadpointing to the parent class
Inheritance should create an is-a relationship, meaningthe child is a more specific version of the parent
Vehicle
Car
7
Deriving SubclassesDeriving Subclasses In Java, we use the reserved word extends to establishan inheritance relationship
See Book.java (page 385) See Dictionary.java (page 386) See Words.java (page 384)
class Car extends Vehicle{ // class contents}
8
The protected ModifierThe protected Modifier Visibility modifiers determine which class members areinherited and which are not
Variables and methods declared with public visibility areinherited; those with private visibility are not
But public variables violate the principle ofencapsulation
There is a third visibility modifier that helps in inheritancesituations: protected
9
The protected ModifierThe protected Modifier The protected modifier allows a member of a base classto be inherited into a child
Protected visibility provides more encapsulation thanpublic visibility does
However, protected visibility is not as tightly encapsulatedas private visibility
The details of each modifier are given in Appendix F
Protected variables and methods can be shown with a #symbol preceding them in UML diagrams
UML Diagram for WordsUML Diagram for Words
Book
# pages : int
+ pageMessage() : void
Dictionary
- definitions : int
+ definitionMessage() : void
Words
+ main (args : String[]) :void
11
The super ReferenceThe super Reference Constructors are not inherited, even though they havepublic visibility
Yet we often want to use the parent's constructor to setup the "parent's part" of the object
The super reference can be used to refer to the parentclass, and often is used to invoke the parent'sconstructor
See Book2.java (page 389) See Dictionary2.java (page 390) See Words2.java (page 388)
The super ReferenceThe super Reference A child’s constructor is responsible for calling theparent’s constructor
The first line of a child’s constructor should use thesuper reference to call the parent’s constructor
The super reference can also be used to reference othervariables and methods defined in the parent’s class
Multiple InheritanceMultiple Inheritance Java supports single inheritance, meaning that a derivedclass can have only one parent class
Multiple inheritance allows a class to be derived from twoor more classes, inheriting the members of all parents
Collisions, such as the same variable name in twoparents, have to be resolved
Java does not support multiple inheritance
In most cases, the use of interfaces gives us aspects ofmultiple inheritance without the overhead
14
Overriding MethodsOverriding Methods A child class can override the definition of an inheritedmethod in favor of its own
The new method must have the same signature as theparent's method, but can have a different body
The type of the object executing the method determineswhich version of the method is invoked
See Thought.java (page 393) See Advice.java (page 394) See Messages.java (page 392)
OverridingOverriding A parent method can be invoked explicitly using thesuper reference
If a method is declared with the final modifier, it cannotbe overridden
The concept of overriding can be applied to data and iscalled shadowing variables
Shadowing variables should be avoided because it tendsto cause unnecessarily confusing code
16
Overloading vs. OverridingOverloading vs. Overriding Don't confuse the concepts of overloading and overriding
Overloading deals with multiple methods with the samename in the same class, but with different signatures
Overriding deals with two methods, one in a parent classand one in a child class, that have the same signature
Overloading lets you define a similar operation indifferent ways for different data
Overriding lets you define a similar operation in differentways for different object types
17
Class HierarchiesClass Hierarchies A child class of one parent can be the parent of anotherchild, forming a class hierarchy
Business
KMart Macys
ServiceBusiness
Kinkos
RetailBusiness
18
Class HierarchiesClass Hierarchies Two children of the same parent are called siblings
Common features should be put as high in the hierarchyas is reasonable
An inherited member is passed continually down the line
Therefore, a child class inherits from all its ancestorclasses
There is no single class hierarchy that is appropriate forall situations
19
The Object ClassThe Object Class A class called Object is defined in the java.langpackage of the Java standard class library
All classes are derived from the Object class
If a class is not explicitly defined to be the child of anexisting class, it is assumed to be the child of the Objectclass
Therefore, the Object class is the ultimate root of allclass hierarchies
The Object ClassThe Object Class The Object class contains a few useful methods, whichare inherited by all classes
For example, the toString method is defined in theObject class
Every time we have defined toString, we have actuallybeen overriding an existing definition
The toString method in the Object class is defined toreturn a string that contains the name of the object’sclass together along with some other information
The Object ClassThe Object Class All objects are guaranteed to have a toString methodvia inheritance
Thus the println method can call toString for anyobject that is passed to it
See Student.java (page 399) See GradStudent.java (page 400) See Academia.java (page 398)
The Object ClassThe Object Class The equals method of the Object class returns true iftwo references are aliases
We can override equals in any class to define equality insome more appropriate way
The String class (as we've seen) defines the equalsmethod to return true if two String objects contain thesame characters
Therefore the String class has overridden the equalsmethod inherited from Object in favor of its own version
Inheritance and GUIsInheritance and GUIs An applet is an excellent example of inheritance
Recall that when we define an applet, we extend theApplet class or the JApplet class
The Applet and JApplet classes already handle all thedetails about applet creation and execution, including:
・ interaction with a Web browser
・ accepting applet parameters through HTML
・ enforcing security restrictions
Inheritance and GUIsInheritance and GUIs Our applet classes only have to deal with issues thatspecifically relate to what our particular applet will do
When we define the paint method of an applet, forinstance, we are actually overriding a method defined inthe Component class, which is ultimately inherited intothe Applet or JApplet class
SummarySummary Chapter 7 has focused on:
・ deriving new classes from existing classes・ creating class hierarchies・ the protected modifier・ polymorphism via inheritance・ inheritance hierarchies for interfaces・ inheritance used in graphical user interfaces
AppletsApplets A Java application is a stand-alone program with a mainmethod (like the ones we've seen so far)
A Java applet is a program that is intended totransported over the Web and executed using a webbrowser
An applet also can be executed using the appletviewertool of the Java Software Development Kit
An applet doesn't have a main method
Instead, there are several special methods that servespecific purposes
AppletsApplets The paint method, for instance, is executedautomatically and is used to draw the applet’s contents
The paint method accepts a parameter that is an objectof the Graphics class
A Graphics object defines a graphics context on whichwe can draw shapes and text
The Graphics class has several methods for drawingshapes
AppletsApplets The class that defines an applet extends the Appletclass
This makes use of inheritance, which is explored in moredetail in Chapter 7
See Einstein.java (page 109)
An applet is embedded into an HTML file using a tag thatreferences the bytecode file of the applet class
The bytecode version of the program is transportedacross the web and executed by a Java interpreter that ispart of the browser
The HTML applet TagThe HTML applet Tag
<html>
<head> <title>The Einstein Applet</title> </head>
<body> <applet code="Einstein.class" width=350 height=175> </applet> </body>
</html>
Drawing ShapesDrawing Shapes Let's explore some of the methods of the Graphics classthat draw shapes in more detail
A shape can be filled or unfilled, depending on whichmethod is invoked
The method parameters specify coordinates and sizes
Recall from Chapter 1 that the Java coordinate systemhas the origin in the top left corner
Shapes with curves, like an oval, are usually drawn byspecifying the shape’s bounding rectangle
An arc can be thought of as a section of an oval
Drawing a LineDrawing a Line
X
Y
10
20
150
45
page.drawLine (10, 20, 150, 45);
page.drawLine (150, 45, 10, 20);or
Drawing a RectangleDrawing a Rectangle
X
Y
page.drawRect (50, 20, 100, 40);
50
20
100
40
Drawing an OvalDrawing an Oval
X
Y
page.drawOval (175, 20, 50, 80);
175
20
50
80
boundingrectangle
The Color ClassThe Color Class A color is defined in a Java program using an objectcreated from the Color class
The Color class also contains several static predefinedcolors, including:
Object
Color.blackColor.blueColor.cyanColor.orangeColor.whiteColor.yellow
RGB Value
0, 0, 00, 0, 2550, 255, 255255, 200, 0255, 255, 255255, 255, 0
The Color ClassThe Color Class Every drawing surface has a background color
Every graphics context has a current foreground color
Both can be set explicitly
See Snowman.java (page115)
SummarySummary Chapter 2 has focused on:
・ predefined objects・ primitive data・ the declaration and use of variables・ expressions and operator precedence・ creating and using objects・ class libraries・ Java applets・ drawing shapes
COMP1100 Lecture 26: 2004 • 1
Assignment 4: Obscured Images Aim of the assignment
demonstrate ability to use stepwise refinement in developingalgorithms
to further develop your programming skills Technical task - Complete the code for an applet
Change colour of squares at ‘random’ partially affected by a hidden image which you partly reveal traverse the whole area within a reasonable time
Assessment Report 15/30
mostly on description of top down design process technical understanding of inheritance, protection
Programming 15/30
COMP1100 Lecture 26: 2004 • 2
Assignment 4: continued Files to submit
reporta4.txt Walker.java PictureApplet.java (optional, if modified)
Other files supplied The assignment specification: Ass4.ps Picture.java HiddenImage.java Sample html files
Cross.htmlSmileyFace.html
COMP1100 Lecture 26: 2004 • 3
Top-down Design III - Merge Sort Initial Problem Statement:
Sort an array A[1..n] (into ascending order).
Prior experience Sorting cards again
it is simpler to sort fewer cards it is simple to combine two already sorted sequences
First Step to Solution:Sort left half of arraySort right half of arrayCombine sorted halves
COMP1100 Lecture 26: 2004 • 4
How will this work Find middle of array
pivot = (low + high) / 2;
Sort left half (somehow) Sort right half (somehow)
Merge sorted halvesTake smallest element from eitherKeep doing this until no more left
COMP1100 Lecture 26: 2004 • 5
Step 2 - Partial Coding We recognise one of the loop patterns. (Need to document the loop with assertions.)
Sort(A, low, pivot);Sort(A, pivot + 1, high);for (i = 0; i < length; i++) { If lowest Left item > lowest Right item
keep Right item Else keep Left item}
COMP1100 Lecture 26: 2004 • 6
Step 3 - Expand Conditions Make sure all conditions are considered
Sort(A, low, pivot);Sort(A, pivot + 1, high);for (i = 0; i < length; i++) { If still have elements in right half then
If still have elements in left half then If lowest Left item > lowest Right item Copy Right item Else Copy Left itemElse Copy Right item // only big items left on right
Else Copy Left item // only big items left on left}
COMP1100 Lecture 26: 2004 • 7
Step 4 - Recognise Recursionpublic void mergesort(int A[ ], int low, int high) {
if (low < high) { mergesort(A, low, pivot); mergesort(A, pivot + 1, high); for (i = 0; i < length; i++) { If still have elements in right half then
If still have elements in left half then If lowest Left item > lowest Right item Copy Right item Else Copy Left item Else Copy Right item // only big items left on right
Else Copy Left item // only big items left on left } }}
COMP1100 Lecture 26: 2004 • 8
Step 5 - Final Versionpublic void mergesort(int A[ ], int low, int high) {
if (low < high) { int pivot = (low + high) / 2; int length = high - low + 1; mergesort(A, low, pivot); mergesort(A, pivot + 1, high); W = copy(A); int m1 = 0; int m2 = pivot - low + 1; for (i = 0; i < length; i++) { if (m2 <= high - low) // still have elements in right half then
if (m1 <= pivot - low) // still have elements in left half then if (W[m1] > W[m2]) // lowest Left item > lowest Right item A[i + low] = W[m2++] // Copy Right item else A[i + low] = W[m1++] // Copy Left item else A[i + low] = W[m2++] // Copy Right - big items remain right
else A[i + low] = W[m1++] // Copy Left - big items remain left } }}
COMP1100 Lecture 26: 2004 • 9
Mergesort demonstration Demo of Mergesort.
if (low == high) return; // is not approved if (low == high) // do nothing
else {…} // is much better!
COMP1100 Lecture 29: 2004 • 1
Recursion In this lecture we discuss Recursion:
from Chapter 11 of Lewis and Loftus Hilbert curve demo
Some comments for Assignment 4
Chapter 11: RecursionChapter 11: Recursion
Presentation slides for
Java Software SolutionsFoundations of Program Design
Third Edition
by John Lewis and William Loftus
Java Software Solutions is published by Addison-Wesley
Presentation slides are copyright 2002 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.
3
RecursionRecursion Recursion is a fundamental programming technique thatcan provide elegant solutions certain kinds of problems
Chapter 11 focuses on:・ thinking in a recursive manner・ programming in a recursive manner・ the correct use of recursion・ examples using recursion・ recursion in graphics
4
Recursive ThinkingRecursive Thinking Recursion is a programming technique in which a methodcan call itself to solve a problem
A recursive definition is one which uses the word orconcept being defined in the definition itself; whendefining an English word, a recursive definition usually isnot helpful
But in other situations, a recursive definition can be anappropriate way to express a concept
Before applying recursion to programming, it is best topractice thinking recursively
5
Recursive DefinitionsRecursive Definitions Consider the following list of numbers:
24, 88, 40, 37
A list can be defined recursively
A LIST is a: number or a: number comma LIST
That is, a LIST is defined to be a single number, or anumber followed by a comma followed by a LIST
The concept of a LIST is used to define itself
6
Recursive DefinitionsRecursive Definitions The recursive part of the LIST definition is used severaltimes, ultimately terminating with the non-recursive part:
number comma LIST 24 , 88, 40, 37
number comma LIST 88 , 40, 37
number comma LIST 40 , 37
number 37
7
Infinite RecursionInfinite Recursion All recursive definitions must have a non-recursive part
If they don't, there is no way to terminate the recursivepath
A definition without a non-recursive part causes infiniterecursion
This problem is similar to an infinite loop with thedefinition itself causing the infinite “loop”
The non-recursive part often is called the base case
8
Recursive DefinitionsRecursive Definitions Mathematical formulas often are expressed recursively
N!, for any positive integer N, is defined to be theproduct of all integers between 1 and N inclusive
This definition can be expressed recursively as:
1! = 1 N! = N * (N-1)!
The concept of the factorial is defined in terms ofanother factorial until the base case of 1! is reached
9
Recursive DefinitionsRecursive Definitions
5!
5 * 4!
4 * 3!
3 * 2!
2 * 1!
1
2
6
24
120
10
Recursive ProgrammingRecursive Programming A method in Java can invoke itself; if set up that way, itis called a recursive method
The code of a recursive method must be structured tohandle both the base case and the recursive case
Each call to the method sets up a new executionenvironment, with new parameters and new localvariables
As always, when the method execution completes,control returns to the method that invoked it (which maybe an earlier invocation of itself)
11
Recursive ProgrammingRecursive Programming Consider the problem of computing the sum of all thenumbers between 1 and any positive integer N, inclusive
This problem can be expressed recursively as:
i = 1
N
i = 1
N-1
i = 1
N-2
= N + = N + (N-1) +
= etc.
Recursive ProgrammingRecursive Programming
public int sum (int num){
int result;if (num == 1)
result = 1;else
result = num + sum (num - 1);return result;
}
13
Recursive ProgrammingRecursive Programming
main
sum
sum
sum
sum(3)
sum(1)
sum(2)
result = 1
result = 3
result = 6
14
Recursion vs. IterationRecursion vs. Iteration Just because we can use recursion to solve a problem,doesn't mean we should
For instance, we usually would not use recursion to solvethe sum of 1 to N problem, because the iterative versionis easier to understand; in fact, there is a formula whichis superior to both recursion and iteration!
You must be able to determine when recursion is thecorrect technique to use
Recursion vs. IterationRecursion vs. Iteration Every recursive solution has a corresponding iterativesolution
For example, the sum (or the product) of the numbersbetween 1 and any positive integer N can be calculatedwith a for loop
Recursion has the overhead of multiple methodinvocations
Nevertheless, recursive solutions often are more simpleand elegant than iterative solutions
16
Indirect RecursionIndirect Recursion A method invoking itself is considered to be direct recursion
A method could invoke another method, which invokes another, etc.,until eventually the original method is invoked again
For example, method m1 could invoke m2, which invokes m3, which inturn invokes m1 again until a base case is reached
This is called indirect recursion, and requires all the same care asdirect recursion
It is often more difficult to trace and debug
17
Indirect RecursionIndirect Recursion
m1 m2 m3
m1 m2 m3
m1 m2 m3
Maze TraversalMaze Traversal We can use recursion to find a path through a maze; apath can be found from any location if a path can befound from any of the location’s neighboring locations
At each location we encounter, we mark the location as“visited” and we attempt to find a path from thatlocation’s “unvisited” neighbors
Recursion keeps track of the path through the maze
The base cases are an prohibited move or arrival at thefinal destination
Maze TraversalMaze Traversal
See MazeSearch.java (page 611) See Maze.java (page 612)
Towers of HanoiTowers of Hanoi The Towers of Hanoi is a puzzle made up of three verticalpegs and several disks that slide on the pegs
The disks are of varying size, initially placed on one pegwith the largest disk on the bottom with increasinglysmaller disks on top
The goal is to move all of the disks from one peg toanother according to the following rules:・ We can move only one disk at a time・ We cannot place a larger disk on top of a smaller disk・ All disks must be on some peg except for the disk in transitbetween pegs
Towers of HanoiTowers of Hanoi
Towers of HanoiTowers of Hanoi A solution to the three-disk Towers of Hanoi puzzle
Towers of HanoiTowers of Hanoi To move a stack of N disks from the original peg to the destinationpeg・ move the topmost N - 1 disks from the original peg to extra peg・ move largest disk from the original peg to the destination peg・ move the N-1 disks from the extra peg to the destination peg・ The base case occurs when a “stack” consists of only one disk
This recursive solution is simple and elegant even though the numberof move increases exponentially as the number of disks increases
The iterative solution to the Towers of Hanoi is much more complex
Towers of HanoiTowers of Hanoi
See SolveTowers.java (page 618) See TowersOfHanoi.java (page 619)
25
Recursion in GraphicsRecursion in Graphics Consider the task of repeatedly displaying a set of tiledimages in a mosaic in which one of the tiles contains acopy of the entire collage
The base case is reached when the area for the“remaining” tile shrinks to a certain size
See TiledPictures.java (page 622)
FractalsFractals A fractal is a geometric shape than can consist of thesame pattern repeated in different scales andorientations
The Koch Snowflake is a particular fractal that beginswith an equilateral triangle
To get a higher order of the fractal, the middle of eachedge is replaced with two angled line segments
FractalsFractals (Figure 11.7 here)
See KochSnowflake.java (page 625) See KochPanel.java (page 628)
Hilbert curve demo
SummarySummary Chapter 11 has focused on:・ thinking in a recursive manner・ programming in a recursive manner・ the correct use of recursion・ examples using recursion・ recursion in graphics
Lecture Outline
● please collect Handout for Tute/Lab Week 13
● 13:00–13:17: CEDAM Surveys
■ please take and fill out one each of Form A, Form C, and
Open-Ended Comments
■ Form A (Large Group Teaching) is for Peter Strazdins’ part of the course only
◆ e.g. for the Fundamental Programming Concepts module only
◆ Lectures 1–15, Labs 1–8 , Assignments 1–3 and the Mid Semester Exam
(at 13:15. please put filled out forms in boxes on each side at front and rear, to be
collected by one of our Class Reps
● review topic: development of the Card and Deck classes
■ object modelling principles, stepwise refinements, object diagrams, use of
assertions and inheritance
● Exam Hints and Concluding Remarks
COMP1100 Lecture 30: Review 2004 JJ J • I II × 1
Design of the Card.java Class
● essential features of a card object
■ has attributes suit (S,C,D,H) and kind (A,2-10,J,Q,K)■ derived attributes: string value (for printing) and value (0..51)■ can be created (but is immutable from then on) and compared
● design (‘data refinement’)
■ represent suit with int suit (1..4) and kind with int rank (1..13)■ represent derived attributes as functions String toString() and
int value()◆ should their values be stored internally?
■ creation via the constructor Card(int r, int s)■ comparison via boolean equals(Card c)■ is anything missing?
● style considerations:
■ enforce immutability by making suit and rank privateprovide int getRank() and int getSuit() for read-only access by clients
■ are the constants (SIZE_OF_SUIT etc) really needed? should they be public?static?
COMP1100 Lecture 30: Review 2004 JJ J • I II × 2
Applying Stepwise Refinement to Card.java: toString()
● top-level refinement (return 2-char rank-suit string value of a Card object)
1. set r to string value of rank2. get s to string value of suit3. return the concatenation of r and s
● refinement of step 2: (idea: use conditional control structures)
■ if (suit is Spades), set s to "H", else if (suit is Clubs), set s to "C", ...
■ which can be refined in Java to either: (which is better?)if (suit == 1) {
s = "S";} else if (suit == 2) {
s = "C";} else if (suit == 3) {
s = "D";} else {
s = "H";}
switch (suit) {case 1:
s = "S"; break;case 2:
s = "C"; break;case 3:
s = "D"; break;default:
s = "H"; break; }
● alternatively (idea: use ‘lookup table’ String[] suits = {"S", "C", "D", "H"}):
■ set s to suits[suit-1]
which is better? are private static final qualifiers to suits appropriate?
COMP1100 Lecture 30: Review 2004 JJ J • I II × 3
Applying Stepwise Refinement to Card.java: value()
● top-level refinement (return value of Card object in range 0..51)
1. calculate contribution from rank
2. calculate contribution from suit
3. return the sum of these
● refinement of step 1
(idea: as suit increases, value increases by 1; e.g. 2S=0, 2C=1, 2D=2, 2H=3)
■ contribution is (suit-1)
● refinement of step 2
(idea: as rank increases, value increases by 4, e.g. 2S=0, 3S=4, . . . ; treat Aces
(AS=48) separately)
■ if (rank is a Ace), contribution is 48
else contribution is (rank-2)*4
● again, by separating concerns, it is easier to come to a solution
● class development is thus done by data design and stepwise refinement
COMP1100 Lecture 30: Review 2004 JJ J • I II × 4
Appropriate Use of Assertions in Card.java
Ref: Sun’s Java assert page
● precondition: in Card(int r, int s)Assert.preCondition((1 <= r) && (r <= SIZE_OF_SUIT), "Rank");Assert.preCondition((1 <= s) && (s <= NUMBER_OF_SUITS), "Suit");
● object consistency (class invariant) in toString()assert (1 <= suit && suit <= suits.length):
"Card internal error: suit=" + suit + " invalid";
● postcondition: in value()int v = rankValue + (suit-1);assert (0 <= v && v < SIZE_OF_SUIT*NUMBER_OF_SUITS):
"Card.value(): return value="+ v +" invalid";
● note use of a meaningful error message (containing erroneous value)
● these are an example of an important class of software engineering techniquecalled defensive programming
■ can greatly aid debugging (why? how?)
note that one of the strengths of Java is its in-built error checking (and stack tracesupon exceptions)
COMP1100 Lecture 30: Review 2004 JJ J • I II × 5
PicCard.java: extending the Card Class for GUI Applications
● GUI applications (e.g. poker machine program) may want to display a card object inpictorial form
● approach 1: simply modify the Card class accordingly
● approach 2: extend the class via inheritance:public class PicCard extends Card {
private Image image;
// construct a card with a rank r and suit s and non-null image ipublic PicCard(int r, int s, Image i) {
super(r, s); // checks and initializes rank and suit via Card()Assert.preCondition(image!=null, "null image");image = i;
}
/* return the image object of the card */public Image getImage() {
return image;}
}
● why is this better?
COMP1100 Lecture 30: Review 2004 JJ J • I II × 6
Design of the Deck.java Class
● essential features of a deck object
■ has a subset of the 52 playing cards (no duplicates)■ card order is important■ can be created (initially full), shuffled, deal a card from, displayed■ attributes: the number of cards left, a random number object (for shuffling) and
the remaining cards
● design (data ‘refinement’)
■ represent attributes by int cardsLeft, Random rand and the 1st cardsLeftelements of Card[] theCards
◆ again these are private, with int numCardsLeft() for clients to accessthe 1st of these
■ creation via the constructor Card(long seed) (seed is used to initialize rand)◆ in sorted order!
■ other operations void shuffle(), Card dealCard() (can return null whendeck is empty) and display()
■ use of assertions: check no duplicate cards in Card() or shuffle()■ is anything missing (for a ‘useful’ deck class)?
COMP1100 Lecture 30: Review 2004 JJ J • I II × 7
Creation of a Deck object (Deck.java)
● after the statement Deck deck = new Deck(0): , the corresponding (short form)
object diagram is:
rank:
suit: 0
Card
deck:
Card[]
Random
52
0 1 51
...
.....
length:
theCards:
cardsLeft:
rand:
52
2
rank:
suit:
Card
2
rank:
suit: 3
Card
1
1
.....
Deck
● note: deck is a reference to the created Deck object (hence it ‘points’ to it)
● note the form of objects (especially array objects), as well as the contents
COMP1100 Lecture 30: Review 2004 JJ J • I II × 8
Closing Remarks
● Introduction to programming and Algorithms
■ requires very different kinds of skills than other disciplines◆ continuum between those of a computer user and a computer programmer◆ procedural thinking, management of complexity and organization
■ usually much harder, but potentially (career) rewards correspondingly greater◆ Java is an industrial-strength language; skilled programmers / designers in
high demand
● successor courses COMP1110/2100:
■ follows up on the advanced topics, e.g. inheritance, recursion, sort/search/assertions
■ emphasis on data structures (“algorithms + data structures = programs)■ introduction to SE principles and management of complexity
◆ building up to moderate-sized systems (≈ 10 classes, ≈ 1000 lines of code)
● incidentally, a different (brand new!) non-programming course available inSemester 2:
■ COMP1710: Tools for New Media and the Web
COMP1100 Lecture 30: Review 2004 JJ J • I II × 9
Exam Hints
● format / level of difficulty like Practice Exam
● Q1–2 (M1): like MSE but a few M2/3 bits may be added
● Q3 (M1): some longer code writing/analysis & debugging bits
● Q5–6; bit ‘heavier’ than Practice Ex; stepwise refinement important
● some particularly relevant lecture topics: . . .
and some topics you don’t really have to revise: . . .
● previous exams also worth looking at (especially years . . . )
● Good Luck!
COMP1100 Lecture 30: Review 2004 JJ J • I II × 10