Sei sulla pagina 1di 222

CITS1001'Notes'2014'

!
Printed!copies!of!these!handouts!are!available!to!buy!from!the!Co7op!bookshop.!!!
Electronic!copies!are!also!available!from!the!unit!web!page.""Please"bring"a"copy"
of"the"In5class"Test"questions"and"the"Code"Listings"handout"(and"a"pen"or"pencil)"
with"you"to"lectures."
"

Contents'
!
1. 2014!teaching!schedule!(lectures,!workshops,!labs,!and!projects)!
2. CITS1001!in!a!nutshell:!an!overview!of!the!material!covered!in!this!unit!
3. Lecture!powerpoints!(printed!4!per!page)!
4. Workshop!powerpoints!(printed!4!per!page)!
5. In7class!test!questions!–!quiz!questions!that!will!be!used!in!lectures!
6. Java!code!handouts!–!example!code!that!will!be!used!in!lectures!

'
Other'Resources'
!
CITS1001!web!page!
!
http://undergraduate.csse.uwa.edu.au/units/CITS1001/!!
!
All!unit!material!is!available!from!the!unit!web!page!!
(not!UWA!LMS)!
!
help1001!discussion!forum:!https://secure.csse.uwa.edu.au/run/help1001!!
For!announcements,!questions!and!answers!to!frequently!asked!questions.!
!
!
Text!Book:!Objects!First!with!Java,!5th!Ed,!by!David!Barnes!and!Michael!Kölling,!
http://www.bluej.org/objects7first/!!
!
!
Rachel!Cardell7Oliver!
CITS1001!Unit!Coordinator!
Semester!1!2014!
School  of  Computer  Science  and  Software  Engineering

CITS1001 Object Oriented Programming and


Software Engineering
Teaching  Schedule  for  CITS1001
Week  1  (starts  February  24)
No  labs  this  week
L01  Introduction  to  Computer  Programming
L02  Objects  and  Classes
W01  Workshop  Unit  Administration  and  Introduction  to  BlueJ

Week  2  (starts  March  3)


LAB1:  Shapes  shapes-­week2.zip
L03  Class  definitions:  attributes,  constructors,  methods
L04  Variables  and  Types
W02  Workshop  on  Syntax  Bugs
UWA  Admin:  Fri  March  8  is  Last  day  to  add  a  Semester  1  unit;;  Last  day  to  withdraw  from  Semester  1
units  (unit  does  not  show  on  formal  academic  record)

Week  3  (starts  March  10)


LAB  2:  Assignment  and  Expressions
L05  Expressions  and  Assignment  Statements
L06  Conditional  Statements
W03  Workshop  on  Identifying  Logic  Bugs  and  Software  Testing  with  Calculator  project  example.

Week  4  (starts  March  17)


LAB  3:  Conditionals
L07  Grouping  Objects  :  ArrayList  and  for-­each  loops
L08  Library  classes:  String,  Math,  Color
W04  Workshop  on  Strategies  and  Tools  for  Finding  and  Fixing  Logic  Bugs

Week  5  (starts  March  24)


LAB  4:  ArrayLists  and  loops
Revision  for  the  test  (bring  your  questions)
Mid-­semester  test
Project  1  published  (end  of  week).  Project  briefing  and  questions  in  the  workshop  class.

Week  6  (starts  March  31)


Work  on  project  1  in  labs
L09  Object  interaction
L10  Repetition  with  for-­loops  and  while-­loops
Open  Workshop  for  any  questions  on  the  exam  or  project
UWA  Admin:  Mon  March  31  is  census  date  (Semester  1)  financial  penalty

Week  7  (starts  April  7)


Programming  week.  
There  will  be  no  lectures  or  workshop  this  week  so  you  can  focus  on  the  project  in  the  lab.  
Extra  support  will  be  available  in  the  labs  during  normal  lecture  and  workshop  times.
UWA  Admin:  Fri  April  11  Last  day  to  withdraw  from  Semester  1  units  (unit  shows  on  formal  academic
record  without  academic  penalty)
Week  8  (starts  April  14)
Project  Demonstrations  (during  lab  times)
L11  Library  classes:  Characters,  Strings  and  Files
L12  Library  classes:  HashMap,  HashSet,  Iterators
Good  Friday  University  holiday  (no  classes)

Midsemester  Study  Break  (April  21  to  25)

Week  9  (starts  April  28)


LAB  5  :  Strings,  Loops,  Collections
L13  Programming  patterns
L14  Defensive  programming  and  Java  exceptions
Project  2  published  (end  of  week).  Project  briefing  and  questions  in  the  workshop  class.

Week  10  (starts  May  5)


Work  on  project  2  in  labs
L15  Arrays  1
L16  Arrays  2  with  Game  of  Life  code  game-­of-­life.zip
W05  Workshop  on  Style  and  Readability  and  Documenting  with  Javadoc

Week  11  (starts  May  12)


Work  on  project  2  in  labs
L17  Efficiency:  sorting  algorithms  with  sorting  code(as  BlueJ  project  zip)
L18  Recursion  :  quicksort
Open  Workshop  for  any  questions  on  the  exam  or  project

Week  12  (starts  May  19)


Programming  week.  
There  will  be  no  lectures  or  workshop  this  week  so  you  can  focus  on  the  project  in  the  lab.  
Extra  support  will  be  available  in  the  labs  during  normal  lecture  and  workshop  times.

Week  13  (starts  May  26)


Project  Demonstrations  (during  normal  lab  times)
LAB  6:  Arrays  (revision  for  exam)
Tue:  Catch  up  or  exam  revision  questions
Thu:  Catch  up  or  exam  revision  questions
Fri:  NO  workshop  this  week
UWA  Admin:  Fri  May  30  Last  day  to  withdraw  from  semester  1  units  (unit  shows  on  formal  academic
record  with  a  grade  of  FN)
CITS1001'in'a'nutshell''''''''''''''''''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!page! 1!
Rachel!Cardell-Oliver!Version!2.1!2014! ! !

Terminology+for+Java+Classes+
/* TicketMachine models a naive ticket machine
Javadoc! * @author David J. Barnes and Michael Kölling
comment! * @version 2011.07.31
*/
!
Class!definition! public class TicketMachine
! {
Constant! public final static int MAX_PRICE = 100;
!
Field! private int price;
declarations! private int balance;
!
/**
Visibility! * Create a machine that issues tickets
modifiers! */
! public TicketMachine(int cost)
Constructor! {
! price = cost;
Parameter! balance = 0;
(cost)! }
!
Accessor!
methods! public int getPrice() { return price; }
(getters)!!
! public int getBalance() { return balance; }
Return!type!
(int)!
!
public void insertMoney(int amount)
Mutator!
{
methods! balance = balance + amount;
(setters)! }
!
! public void printTicket()
Method!! {
!!!!!signature! System.out.println("# Ticket " +
! price + " cents.");
balance = 0;
Method!body!
}
}
CITS1001'in'a'nutshell''''''''''''''''''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!page! 2!
Rachel!Cardell-Oliver!Version!2.1!2014! ! !

Java+Data+ Declare+and+Instantiate+ Examples+of+Use+


Types+
boolean, boolean found = false; (!found && i<10)
int, int i; i++;
double, double pi = 3.14; i=i+1;
char char ch = ‘a’; a = r*r*pi;

byte, short,
long, float

String String msg1 = “hello ”; msg1+msg2; //”hello there”


String msg2 = “there” msg1.equals(“hello “);
msg1.contains(“lo”);

ArrayList<E> ArrayList<String> names = new names.add(“Ben”);


ArrayList<String>(); names.add(“Moose Smith”);
names.get(names.size()-1);
ArrayList<Student> classlist; //get last name
classlist = new
ArrayList<Student>();
classlist.add(new
Student(“fred”,100));

HashMap<K,V> HashMap<String,String> phonebook.put(“fred”,”+61


phonebook; 345 6677”);
phonebook.get(“fred”);
//is String “+61…”
phonebook = new phonebook.size()
HashMap<String,String>(); phonebook.keySet()
//all the keys (names)
phonebook.values()
//all the values (ph nums)

HashSet<E> HashSet<String> words = for (String word :


new HashSet<String>(); wordArray) {
words.add(word);
}
words.contains(“hello”)
words.size()

arrays int[] mode = new int[10]; int places = new int[]


{1,2,3,4,5};
(places.length == 5)
String[] = new String[5]; places[0]=places[0] - 2;
//was 1 now -1
places[4]=places[3] * 3;
//pos 4 w 5 now 12
CITS1001'in'a'nutshell''''''''''''''''''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!page! 3!
Rachel!Cardell-Oliver!Version!2.1!2014! ! !

Programming+Patterns+
!
Programming!patterns!correspond!to!fragments!of!code!that!accomplish!common!
programming!goals.!!Bergin!notes!that!“A!"pattern"!is!a!solution!to!a!problem!in!a!
context.!…!a!pattern!is!an!attempt!to!establish!"best!practice"!with!respect!to!a!problem!
or!class!of!problems.”!

Whether+Or+Not++
!
Whether!Or!Not!is!a!selection!pattern.!Bergen!describes!the!Whether!Or!Not!pattern!as:!
!
``You!are!in!a!situation!in!which!some!action!may!be!appropriate!or!inappropriate!
depending!on!some!testable!condition.!...!You!don't!need!to!repeat!the!action,!only!to!
decide!whether!or!not!it!should!be!done.!There!are!no!other!actions!to!do!instead!of!this!
one.!You!want!to!write!simply!understood!code."!!!!
!
For!example:!a!bank!deposit!method!should!only!update!the!balance!if!the!amount!
deposited!is!positive:!
!
if (amount > balance) {
balance = balance + amount;
}

Whether+Or+Not+with+warning+
+
Barnes!and!Kölling!use!a!variant!of!the!Whether!Or!Not!pattern!in!which!an!else!branch!
containing!only!print!statement(s)!is!used!to!inform!the!user!of!the!error!condition.!!For!
example,!
!
if (amount > balance) {
balance += amount ;
} else {
System.out.println("amount must be >0");
}

Alternative+Action+(Selection)
!
Bergen!describes!this!pattern!as!follows:!

You!are!in!a!situation!in!which!one!of!exactly!two!actions!is!appropriate!depending!on!
some!testable!condition.!

When!the!condition!holds!you!want!to!do!one!action,!and!when!it!does!not!hold!you!
want!to!do!some!different!action.!There!are!exactly!two!actions!and!exactly!one!
condition,!which!may!be!true!or!false.!

Therefore,!use!a!single!IF!statement!with!an!ELSE!part,!expressing!the!test!as!a!
positive!condition.!
CITS1001'in'a'nutshell''''''''''''''''''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!page! 4!
Rachel!Cardell-Oliver!Version!2.1!2014! ! !

!IF!<condition>!
!! <one!action>!
!ELSE!
! <another!action>!
!
For!example!a!student!may!pass!or!fail!an!exam!depending!on!the!value!of!the!numeric!
grade.!

if ( numericGrade > 50 ){
output ("passing");
} else {
output("failing");
}

Process+All+Items+
+
Process!All!Items!is!a!loop!pattern.!!Astrachan!and!!Wallingford!!describe!the!Process!
All!Items!pattern!as:!``The!items!are!stored!in!an!array!a.!!Use!a!definite!loop!to!process!
all!the!items."!!For!example,!
!
for(int k=0; k < a.length; k++) {
process a[k ];
}
!
Barnes!and!Kölling!give!a!for-each!version!of!this!pattern!for!collections!(and!arrays!
since!Java!5)!!
!
ArrayList<String> names = new ArrayList<String>();

for (String ni: names) {


process ni;
}
!
!

Search+
!
You!are!working!with!a!collection!or!stream!of!objects.!

How$do$you$find$an$object$that$meets$a$specific$condition?!

Suppose!that!you!have!a!set!of!students,!and!you!would!like!to!find!the!first!student!
with!an!"A"!average.!In!the!worst!case,!you!will!look!at!the!whole!collection!before!
finding!your!target.!But,!if!you!find!a!match!sooner,!you!would!like!to!terminate!the!
search!and!work!with!the!object!that!you!found.!
CITS1001'in'a'nutshell''''''''''''''''''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!page! 5!
Rachel!Cardell-Oliver!Version!2.1!2014! ! !

Therefore,!construct!a!Process!All!Items!loop,!but!provide!a!way!to!exit!the!loop!early!
should!you!find!your!target!sooner.!
!
ArrayList<String> names = new ArrayList<String>();
String key; //String to search for

for (String ni: names) {


if (ni.equals(key)) {
return true; //key is found
}
}
return false; //when key not found
!
!

Temporary+variable+patterns+
!
The!process!all!items!pattern!usually!requires!some!local!variable(s).!
Beck!describes!several!different!patterns!for!local!variable!use:!!
``How!do!you!save!the!value!of!an!expression!for!later!use!within!a!method?!...!
wherever!possible!create!variables!whose!scope!and!extent!is!a!single!method.!Declare!
them!just!below!the!method!selector.!Assign!them!a!value!as!soon!as!the!expression!is!
valid.!…!
!
Collecting'Temporary'Variable!...!saves!intermediate!results!for!later!use.!!
!
int[]a = new int[] {0,-1,3,4,-5,-6,10};
int countnegs = 0;
for ( int ai : a ) {
if (ai < 0) {
countneg++;
}
}
return countneg; !
!
Caching'Temporary'Variable!...!improves!performance!by!saving!values.!!
'
Explaining'Temporary'Variable!...!improves!readability!by!breaking!up!complex!
expressions."!!!
!
double[] scores = new double[12];
double avg = average(scores);
double sumsq = 0;
for ( double si : scores ) {
double diff = (ai – avg) * (ai – avg);
sumsq = sumsq + diff;
}
double stddev = (sum / a.length);
return stddev;!
!
CITS1001'in'a'nutshell''''''''''''''''''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!page! 6!
Rachel!Cardell-Oliver!Version!2.1!2014! ! !

In!the!example!above,!stddev and diff are!explaining!temporary!variables.


sumsq!is!s!collecting!variable!and!avg!is!a!caching!temporary!variable.!
!
The!Collecting!temporary!variable!pattern!is!often!combined!with!the!Process!All!Items!
pattern!to!evaluate!extreme!values!and!for!summing!or!counting!a!collection.!

Further+Reading+

O.!Astrachan!and!E.!Wallingford.!Loop!patterns:!Definite!process!all!items,!1998.!
Retrieved!March!2012!from!
http://www.cs.duke.edu/~ola/patterns/plopd/loops.html!
!
D.!J.!Barnes!and!M.!Kolling.!Objects!First!with!Java:!A!Practical!Introduction!using!BlueJ.!
Prentice!Hall,!Pearson!Education,!5th!edition,!2012.!
!
K.!Beck.!Portland!pattern!repository:!Temporary!variables,!1995.!Retrieved!March!
2012!from!http://c2.com/ppr/temps.html!

J.!Bergin.!Patterns!for!Selection!Version!4,!1999.!Retrieved!March!2009!from!
http://csis.pace.edu/~bergin/patterns/Patternsv4.html!
CITS1001'in'a'nutshell''''''''''''''''''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!page! 7!
Rachel!Cardell-Oliver!Version!2.1!2014! ! !

Properties+of+Java+Applications+
!
Most$of$the$definitions$in$this$section$are$from$Barnes$and$Kölling,$Objects$First$With$Java.$

Syntax+
!
The!syntax!of!the!Java!programming!language!is!the!set!of!rules!that!defines!how!a!Java!
program!is!written!and!interpreted.!!!
Java’s!grammar!rules!define!the!legal!forms!of!Java!statements,!including!correct!use!of!
brackets,!semi-colons!and!key!words.!
Java’s!static!typing!rules!check!that!all!expressions!are!correctly!typed.!
The!Java!compiler!flags!syntax!errors!and!type!errors!in!Java!code.!
Logical+Correctness+
!
A!logical!error!is!a!problem!where!the!program!compiles!and!executes,!but!delivers!the!
wrong!result.!!!Techniques!such!as!code!inspection!and!JUnit!unit!testing!can!be!used!to!
help!to!identify!logical!errors.!
Style+and+Readability+
!
A"major"goal"of"any"software"developer"should"be"to"write"consistently"clear,"high"quality,"
maintainable"code."This"is"not"always"easy"and"requires"a"certain"amount"of"discipline"at"
the"best"of"times."One"way"to"help"achieve"high"quality"code"is"via"the"use"of"coding"
standards.""The"programming"style"guide"used"in"CITS1001"is"available"from"
http://www.csse.uwa.edu.au/UWAJavaTools/checkstyle/!and!is"based"on"the"Barnes"and"
Kölling"Objects"First"with"Java"M"Style"Guide"Version"2.0"from""
www.bluej.org/objectsMfirst/styleguide.html""(and"see"appendix)"

Coupling+
!
Coupling!describes!the!interconnectedness!of!classes.!!We!strive!for!loose'coupling'in!
a!system!–!that!is,!a!system!where!each!class!is!largely!independent!and!communicates!
with!other!classes!via!a!small,!well-defined!interface.!
Well-designed!classes!should!hide!implementation!information!from!view,!making!only!
information!about$what$a!class!can!do!should!be!visible!to!the!outside,!but!not!how!it!
does!it.!!Proper!encapsulation!in!classes!reduces!coupling!and!thus!leads!to!a!better!
design.!!!
One!of!the!main!goals!of!a!good!class!design!is!that!of!localizing$change:!making!changes!
to!one!class!should!have!minimal!effects!on!other!classes.!

Cohesion+
Cohesion!describes!how!well!a!unit!of!code!maps!to!a!logical!task!or!entity.!!In!a!highly!
cohesive!system,!each!unit!of!code!(method,!class,!or!module)!is!responsible!for!a!well-
defined!task!or!entity.!!Good!class!design!exhibits!a!high!degree!of!cohesion.!
A!cohesive!method!is!responsible!for!one,!and!only!one,!well-defined!task.!
A!cohesive!class!represents!one!well-defined!entity.!
High'cohesion!benefits!a!design!by!improving!its!readability!and!giving!higher!
potential!for!reuse.!
CITS1001'in'a'nutshell''''''''''''''''''!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!page! 8!
Rachel!Cardell-Oliver!Version!2.1!2014! ! !

Efficiency+
!
Java!programs!may!be!optimized!to!execute!faster!or!to!use!less!memory!storage!or!
other!resources.!!Sorting!algorithms!provide!some!good!examples!of!the!ways!in!which!
the!choice!of!algorithms!and!data!structures!affects!performance.!!The!topic!of!
efficiency!will!be!covered!in!more!detail!in!Data!Structures!and!Algorithms.!
!
CITS1001 CITS1001
OBJECT ORIENTED In CITS1001 you will learn how to write simple computer
PROGRAMMING AND programs using the Java programming language
SOFTWARE ENGINEERING The purpose of today’s lecture is to give an overview of the
unit and what you will have learnt by the end.
What is a computer program? What is a programming language?
•  A sequence of elementary instructions that when followed •  A program for a computer to follow must be expressed
achieves a specified goal completely unambiguously
•  There are many different programming languages in
– a procedure, a recipe, an algorithm which programs can be written
•  In order to write a working program, you need to learn
1. Heat oil in wok.
2. Stir fry 1 clove garlic, 1 tbsp black beans, 100g preferred roast •  the vocabulary and syntax of the language, so that you can write
meat. statements that can be understood
3. Add 2 small bok-choy and toss to coat. •  how to make sequences of legal statements that do simple tasks
4. Scatter a pinch of sugar and add 2 tbsp water.
•  how to express what you wish the computer to do in a simple
5. Reduce heat, cover and cook for two minutes.
6. Serve with rice. enough
•  way to translate into the programming language
Stephanie Alexander, the cook’s
companion •  Similar to learning the words, how to form sentences and
how to write a story when learning a new human language
Programming in the large For example, a web application
Most computer programs these days •  responds to mouse clicks, and text entries
•  run continuously
•  communicates with computers across the Internet
•  respond to input from users and other programs
•  deliver output to users and other programs
•  formats and displays Web pages
•  are programmed by large teams of programmers •  starts up “helper applications” if necessary
•  are too big and complex for any one person to understand
Complexity Object Oriented Programming
How is something moderately complex organized in the •  OOP refers to the process of designing and
real world? Consider a restaurant ... implementing a co-operative community of interacting
•  Diners want meals objects.
•  Chefs prepare dishes •  each object provides a small number of relatively simple
•  Waiters take orders from diners, and bring food to the tables services
•  Busboys collect and wash plates •  objects communicate with each other to exchange
•  Barmen prepare and serve drinks
information
•  complex behaviour is achieved by the co-operation of objects
•  The maitre’d makes reservations and seats diners
•  Using objects allows us to focus on a problem at a high level
Each type of person provides a narrow range of services. without worrying about the minor details.
The restaurant operates through the co-operative
interaction of all the restaurant staff •  That is, we use ABSTRACTION to manage COMPLEXITY
Object Oriented Programming What does OOP provide?
•  Complexity management
•  encapsulation and information hiding work on the principle that objects
should interact only through pre-specified interfaces
•  software development can be more reliably divided between
independent groups
•  Reusable software
•  class libraries provide easy access to many standard services
•  developing software components that match the reliability and
interchangeability of hardware components is an elusive goal
•  Natural modelling
•  problem identification, program design and program implementation all
follow same process
An early algorithm
1800-1600 BC Mesopotamia
The first computer programmer
•  In 1837 Charles Babbage proposed
A cistern. The height is 3,20,
and a volume of 27,46,40 has a type of computer called the
been excavated. The length Analytical Engine
exceeds the width by 50. You
should take the reciprocal of •  In 1842 Ada Lovelace wrote the first
the height, 3,20, obtaining 18. algorithm for computing Bernoulli
Multiply this by the volume, numbers using the Analytical Engine
27,46,40, obtaining 8,20. Take
half of 50 and square it, •  A Babbage Engine was not actually
obtaining 10,25. Add 8,20 and built until 2002
you get 8.30,25. The square root
is 2,55. Make two copies of this,
adding to the one and
subtracting from the other. You Source: Ancient Babylonian Algorithms,
find that 3,20 is the length and D.K. Knuth, CACM 1972 Augusta Ada King, Countess of
2,30 is the width. This is the Lovelace (10 December 1815 – 27
(see cits1001 resources page)
procedure.! November 1852)
Source: http://en.wikipedia.org/
Are there any problems we can’t solve
with a computer program ?
That is …
•  YES "You can never find general mechanical means
•  Example, the halting problem: there can be no program
to decide whether another program will halt or run forever for predicting the acts of computing machines;
on a given input. it’s something that cannot be done … ”
•  Alan Turing 1937
From "Snooping the Loop Snooper"
•  And furthermore, some things are computable but would http://www.lel.ed.ac.uk/~gpullum/loopsnoop.html
take unreasonable time or space.
•  Example, the travelling salesman problem: given a list
of cities and distances between each pair, is there a route
with length less than k that visits all cities?
(can I visit all my friends with half a tank of petrol ?)
Can computers think ? A first programming course
•  Turing test 1950s: can a computer •  Becoming an expert programmer (or expert
program show “intelligence” ? anything) requires at least 10,000 hours
Alan Turing, Mind, October 1950
•  Can a computer “think” ?
•  In your first 150 hours in CITS1001 you will learn
•  Researchers in Artificial Intelligence
are still studying this question today •  What are programs for ?
•  Syntax – speak the language
•  Semantics – understand what is done
•  Algorithms – designs and plans
•  Tools - development, check, test, debug
Alan Mathison Turing •  Quality Assurance – good vs bad programs
Source:
en.wikipedia.org
By mid-semester you will be able to By the end of the unit
•  Program a drawing You will be able to manipulate more complex data
application to create and structures and design algorithms to solve problems
modify image collages
For example, program a (seemingly) intelligent chat
•  You will be manipulating program.
collections of objects
Recommended
Reading CITS1001
ORGANISATION
See the resources page CITS1001
on the Semester 1 2014
CITS1001 web pages 15 mins on the 4 most important things you need
for more links to know
The 4 most important things you need to 1. Where to find ALL online material …
know about cits1001
•  Website
ALL online material for CITS1001 will be available from
1.  Where to find all online material
2.  How learning works (and doesn’t) http://undergraduate.csse.uwa.edu.au/units/CITS1001
3.  Your rights and responsibilities Bookmark this page now!
UWAs Moodle LMS system will NOT be used for this unit
4.  Things to do this week
•  Discussion list
•  help1001 uses the cshelp facility. Bookmark this page too.
•  To make a query, or to view or post answers, go to
https://secure.csse.uwa.edu.au/run/help1001
1. Where to find ALL online material … 2. How Learning Works
•  Use •  Learning is a process that involves not only your skills,
http://undergraduate.csse.uwa.edu.au/units/CITS1001 for knowledge and abilities, but also your social and
emotional experiences
•  Announcements
•  Motivation is a critical factor that determines, directs and
•  Assessment details and dates
sustains what you learn
•  Lecture notes
•  Lab sheets •  The quality of learning is enhanced by goal-based
•  Exam and test information practice and targeted feedback
•  Resources – links for the text book and online resources •  Ability to reflect on and adapt their learning strategies
•  Contact information also impacts your learning success
•  Links to csmarks, cssubmit
•  Prior knowledge and how you organise knowledge can
•  Link to the help forum, help1001
•  Link to the official unit outline, rules etc.
either support or hinder your learning
Ambrose et al. How Learning Works, Wiley, 2010
2. How learning DOESN’T work 2. Learning Programming is Emotional (!)
“Learning how to program was my favourite unit … It is incredibly
satisfying when your program works.”
IN: information “I felt accomplished and happy [because] on top of finishing
delivered in mine, I helped two other friends and a random person…”
lectures and labs
“Okay, this should work. Compile. And then the compiler says
“no” and we’re like, Oh no, not again. Not this. Oh, come on. It’s
not doing this to us again, is it? Oh man. Give us a break here.”
OUT: same info
in the exam ALL students encounter problems when learning to program.
The thriving student has a positive perception of their ability to
deal with problems, and effective strategies for overcoming
problems when they are encountered.
3. Rights and Responsibilities 3. Rights and Responsibilities
•  Every student has the right to Satisfactory Progress
•  study in a supportive and encouraging environment;
•  In order to pass CITS1001, consistent practice and
•  expect the University to provide a high quality of education including a
high quality of teaching, supervision, curriculum and unit content, a effort are needed throughout the semester
commitment to inclusivity, and good access to staff;
•  assessment that is valid, educative, explicit, reliable and fair; To pass CITS1001 you need to achieve ALL of the
following:
•  Every student has the responsibility to
•  act at all times in a way that respects the rights and privileges of •  an overall mark of at least 50%, AND
others;
•  bring an open and enquiring mind and enthusiasm to their studies;
•  at least 40% in Programming Project 1 and the mid-
•  participate actively in the teaching and learning and research
environment, in particular by attending classes as required, complying
semester test combined, AND
with workload expectations, and submitting required work on time;
•  at least 40% in the final examination.
UWA Charter of Student Rights and Responsibilities www.aps.uwa.edu.au/home/policies/charter
3. In the unlikely event of an emergency… 3. UWA Important Dates
(these dates are also on the CITS1001 schedule page)
•  If you are struggling, the most important thing is to recognize
it and to respond early: letting it slide is always a mistake
•  make sure you use all the help that is available
•  Be realistic about your strengths, interests, and motivation
•  almost everyone who fails Java programming does so not because
of lack of ability, but because of lack of interest
•  the most common way to fail is to fall behind, start missing lectures
and lab sessions, and then try to cram at the last moment
•  withdrawing is better than failing!
Failing a unit is expensive, permanently mars your
academic record, and is almost always avoidable!
4. Things to do this week Text Book
Objects First With Java 5th Edition
1. Set up your computer account David Barnes & Michael Kölling
http://www.ecm.uwa.edu.au/students/itsupport
2. Sign up in OCLR for a lab class (classes start in week 2) •  An excellent introduction to
Object Oriented Programming
3. Get a copy of the text book and start reading it
•  Many Java code examples
4. Buy or print a copy of the lecture handouts
•  Uses the BlueJ IDE
5. If you will be using your own laptop then
•  Focuses on objects and classes
Set up Unifi wireless access on your laptop
http://www.is.uwa.edu.au/it-help/access/wireless •  CITS1001 covers chapter 1-7
and install BlueJ (and Java 7 if needed) •  This is a good reference book on
OOP and SE that you will be
http://www.bluej.org/
able to refer to and learn from
throughout your UWA course
Text Book (cont)
•  Every student should have a
copy of this book
•  Copies in the library
OBJECTS AND
•  Buy from the bookshop (wk2) or
many sources on-line CLASSES
•  There is an online version available
more cheaply CITS1001
•  The 4th edition is fine too and there
are many second hand copies of
that available
Concepts for this Lecture Classes and Objects
A class is a group of objects that have similar
•  object; class;
characteristics and exhibit similar behaviour
•  method; parameter; signature;
•  data type;
An object is a specific instance of a class
•  multiple instances; state;
•  method calling; source code; method result
Objects – represent ‘things’ from the real world, or
from some problem domain
Example: the red car down there in the car park
•  Reading: Objects First with Java, Chapter 1
Classes – represent all objects of a kind
Example: car, lecturer, student
Example Example
•  The set of all students forms the class Student •  The set of all dogs forms the class Dog
•  Each individual student is an object of the class Student •  Each individual dog is an object of the class Dog
•  John Smith and Janice Lee are instances of the class •  Spot, Rover and Rex are all instances of the class Dog
Student
Why do we use classes? Describing a Class
•  To reduce complexity •  We describe a class by listing the common features that
•  We can often deal with a specific object based purely on are shared by all the objects in that class, divided into the
knowledge of its class, rather than that particular attributes that each object has, and the actions that each
instance object can perform
•  For example, if we encounter a dog – in other words, an •  Example:
instance of the class Dog – walking down the street, we •  Student number is an attribute of the class Student
already have a basic understanding of how to deal with •  Every student has a student number, although each individual
student has a different student number
it, even if we have never met that particular dog
•  Example
•  Barking is an action that all objects of the class Dog have in
common
What is a Waiter ? Exercise
•  A Waiter has the following attributes and actions •  Download and open the shapes BlueJ project
•  Attributes of a Waiter •  Create some objects from the classes Circle, Square and
•  Name Triangle (right click on the class and select new(...))
•  Actions of a Waiter
•  Inspect the objects (double click on any object in the
•  Bring menus
•  Take orders
object bench)
•  Bring meals •  Invoke their methods (right click on an object and select
•  This collection of attributes and actions defines the class one of its methods)
of Waiters •  Experiment! Making mistakes is OK - it is a good way of
•  We can deal with any individual waiter just based on our learning to program
knowledge of the class Waiter
What's in an Object? Object State
•  Notice the types of the fields:
•  Objects have operations that can be invoked (Java calls
int, String, boolean
them methods).
•  Types restrict the values a field can take
•  Objects usually do something if we invoke a method.
•  Objects have state. The state is represented by stored
values in fields.
Instances A Java Method
•  Multiple instances:
Many similar objects /**!
can be created from a * Move the circle horizontally by !
single class. * 'distance' pixels.!
•  An object has
*/!
attributes: values
stored in fields. public void moveHorizontal(int distance)!
•  The class defines
{!
what fields an object erase();!
has, but each object xPosition += distance;!
stores its own set of draw();!
values (the state of }!
the object).
About Methods Source Code
•  Methods may have parameters. •  The source code of a class determines the structure and
•  Parameters pass additional information needed to behaviour (fields and methods) of each of the objects of
execute the method. That is, “input” to the method. that class
•  Parameters have types. The type defines what kinds of •  A Java project (application) is a collection of classes
values a parameter can take.
•  Methods may return a result via a return value
•  The head of a method is called its signature. It provides
the information needed to invoke that method.
•  Objects can communicate by calling each other’s
methods.
Return Values Summary of concepts introduced
•  All the methods in the figures project have void return You should now be able to give an explanation of each
types; but … of these terms:
•  … methods may return a result via a return value
•  Such methods have a non-void return type object; class; method; parameter; signature; data type;
•  More on this in future lectures multiple instances; state; method calling; source code;
result
Try it! Turn to code example 1
Main concepts to be covered
UNDERSTANDING •  Fields / Attributes
•  Constructors
CLASS DEFINITIONS •  Methods
•  Parameters
CITS1001
Source ppts: Objects First with Java - A Practical Introduction
using BlueJ, © David J. Barnes, Michael Kölling
Source Code A very important point
•  In Java, classes are defined by text files of source code
•  Program code is designed to be human readable
•  Familiar words are used for programming constructs (if, else,
•  Source code is designed to be while, repeat, for)
•  human readable and
•  Indented format is similar to paragraphs and sections in text
•  machine readable
•  Meaningful variable names suggest what is intended (eg. price,
mark, studentname)
•  Source code must specify everything about how each of the
objects of a class behave
•  AND program code is also executed by a computer
Turn to the first code examples in the handouts •  The computer will do exactly what it is TOLD to do
Java Class File: Student.java •  The RULES of the language determine EXACTLY what happens
when the program is run
•  THE COMPUTER DOES NOT KNOW WHAT YOU INTENDED
Q: Where does the name of the class appear ? THE PROGRAM TO DO
Fields / Attributes
•  Source code specifies the list of attributes that each
“Programming can be difficult at first. object has
It is annoying when your program doesn’t •  Each object in a class has the same attributes, but the
work, and you spend ages trying to figure values of those attributes may be different for different
our why. Bugs can seem to come from objects
•  e.g. each student has some student number, but different
nowhere, for no reason. But there is
students have different student numbers
always a logical reason behind a bug. It
is incredibly satisfying when your program •  Q: Identify the attributes of the Student class.
does work.”
Ticket machines
Constructor and Methods – an external view
•  It specifies how the objects are constructed
•  It specifies what methods the objects have, and exactly •  Turn to example 3 in the code handouts:
what each method does TicketMachine.java
•  Each object in a class has the same collection of methods
•  Constructor is a special method (maybe more than one) •  Exploring the behavior of a typical ticket machine.
•  It has the same name as the class •  Use the naive-ticket-machine project.
•  It has no return type •  Machines supply tickets of a fixed price.
•  How is that price determined?
•  Other methods have a return type or void •  How is ‘money’ entered into a machine?
•  How does a machine keep track of the money that is entered?
•  Q: identify the constructor and other methods of the
student class
Ticket machines
Ticket machines – an internal view
•  Interacting with an object gives us clues about its
Demo behavior.
•  Looking inside allows us to determine how that behavior is
provided or implemented.
See Code Handouts •  All Java classes have a similar-looking internal view.
in the Lecture Notes
Basic class structure Keywords
The outer wrapper of •  Words with a special meaning in the language:
public class TicketMachine
TicketMachine •  public
{
Inner part omitted. •  class
} •  private
•  int
public class ClassName •  Also known as reserved words.
{
Fields
The inner contents
Constructors
of a class
Methods
}
Fields Constructors
public TicketMachine(int cost)
•  Fields store values for an public class TicketMachine
{
object. {
price = cost;
private int price;
•  They are also known as balance = 0;
private int balance;
instance variables or private int total;
total = 0;
attributes. }
•  Fields define the state of Further details omitted.
an object. } •  Constructors initialize an object.
•  Use Inspect to view the •  Have the same name as their class.
state in BlueJ •  Close association with the fields.
type
•  Some values change visibility modifier variable name •  Store initial values into the fields.
often.
•  External parameter values for this object.
•  Some change rarely (or private int price;
not at all).
Passing data via parameters Choosing variable names
•  There is a lot of freedom over choice of names. Use it
wisely!
•  Choose expressive names to make code easier to
understand:
•  price, amount, name, age, etc.
•  Avoid single-letter or cryptic names:
•  w, t5, xyz123
Parameters are another sort of
variable.
Methods Method structure
•  The header provides the method s signature:
•  Methods implement the behavior of objects.
•  Methods have a consistent structure comprised public int getPrice()
of a header and a body.
•  Accessor methods provide information about an •  The header tells us:
object. •  the name of the method
•  what parameters it takes
•  Mutator methods alter the state of an object.
•  whether it returns a result
•  Other sorts of methods accomplish a variety of •  its visibility to objects of other classes
tasks.
•  The body encloses the method s statements
Review Accessor (get) methods
•  Class bodies contain fields, constructors and methods.
•  Fields store values that determine an object’s state. return type
•  Constructors initialize objects – particularly their fields. visibility modifier method name
•  Methods implement the behavior of objects. parameter list
public int getPrice() (empty)
{
return price;
} return statement
start and end of method body (block)
Accessor methods Mutator methods
•  An accessor method always has a return type that is not •  Have a similar method structure: header and body.
void. •  Used to mutate (i.e., change) an object s state.
•  An accessor method returns a value (result) of the type •  Achieved through changing the value of one or more
given in the header. fields.
•  The method will contain a return statement to return the •  Typically contain assignment statements.
value. •  Often receive parameters.
•  NB: Returning is not printing!
Mutator methods set mutator methods
•  Fields often have dedicated set mutator methods.
•  These have a simple, distinctive form:
visibility modifier return type
•  void return type
method name parameter •  method name related to the field name
•  single parameter, with the same type as the type of the field
public void insertMoney(int amount)
{ •  a single assignment statement
balance = balance + amount;
}
field being mutated assignment statement
A typical set method Protective mutators
•  A set method does not have to assign the parameter to
public void setDiscount(int amount)
{ the field.
discount = amount; •  The parameter may be checked for validity and rejected if
}
inappropriate.
•  Mutators thereby protect fields.
•  Mutators support encapsulation.
We can infer that discount
is a field of type int, i.e:
private int discount;
Method summary Review
•  Methods implement all object behavior. •  Fields, parameters and local variables are all variables.
•  A method has a name and a return type. •  Fields persist for the lifetime of an object.
•  Parameters are used to receive values into a
•  The return-type may be void.
constructor or method.
•  A non-void return type means the method will return a
•  Local variables are used for short-lived temporary
value to its caller. storage.
•  A method might take parameters.
•  Parameters bring values in from outside for the method
to use.
Review
•  Methods have a return type.
•  void methods do not return anything.
VARIABLES AND
•  non-void methods return a value.
•  non-void methods have a return statement.
TYPES
•  String values can be printed to the terminal using CITS1001
System.out.println()
•  String values can be concatenated using +
•  For example “cat” + “fish” is “catfish”
Scope of this lecture Primitive types
•  Every piece of data that is stored or moved around in Java must have a type
•  Types in Java
•  Java supplies eight primitive types for the most fundamental pieces of data
•  the eight primitive types
•  the unlimited number of object types
•  Values and References
•  The Golden Rule
short!
int!
long! boolean!
float! char!
double!
byte
Integer primitive types Floating point primitive types
•  Four of the types are used for storing whole numbers •  There are two types used for floating point values – in other
•  Each occupies a fixed amount of memory words, numbers with decimal points
•  byte uses 1 byte and stores integers from 128 to 127
•  short uses 2 bytes and stores integers from –32768 to 32767 •  float uses 4 bytes and stores floating point numbers, positive or
•  int uses 4 bytes and stores integers from
negative, in the range 1.4e 45 to 3.4028235e38
–2147483648 to 2147483647 •  double uses 8 bytes and stores floating point numbers, positive or
negative, in the range 4.9e 324 to 1.7976931348623157e308
•  long uses 8 bytes and stores integers from
– 9223372036854775808 to 9223372036854775807
(that is –263 to 263 – 1)
Declaring variables Assignments to numeric types
•  In Java, all variables must be declared before they are used •  An assignment sets the value of a variable
•  The declaration specifies the type and name of the variable int x; ! !// this is a declaration!
x = 100; ! !// this is an assignment!
•  When a primitive variable is created, a fixed amount of memory
is set aside for that variable •  Here are some legal assignments
•  byte b;! int x;!
double y;!
•  double temp;!
double z;!
•  int balance;! temp!
b! !
x = 200;!
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 0 0
y = -354.278;!
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 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 0 0 0 0 z = 23e5;!// this is scientific notation
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 0 0
balance!
Typecasting Non-numeric primitive types
•  The compiler will warn you if you attempt to use a smaller- •  boolean is used to hold one of the two boolean values
sized variable than it thinks the value needs true or false!
•  For example, if you attempt
boolean isDone; // declaration!
float b;! isDone = false;! // assignment!
b = 12.35;!
then the compiler will warn you of a possible loss of •  char uses two bytes and holds a Unicode character
precision because 12.35 is regarded as a double !
char ch; ! !// declaration!
•  If this is really what you want, then you can cast the value
ch = A ;! !// assignment!
float b;!
b = (float) 12.35;
•  for literals, there is a quick cast – b = 12.35f;!
Literals Initialization
•  Actual values that you type into the source code are called •  If a variable is given an initial value directly after it is declared,
literals - these are things like then you can combine the two steps into one
int x;!
100, -23, true, Z , 37, 1e-5, 22, 3.1415926! x = 10;!
boolean isFinished;!
isFinished = true;!
•  Everything in Java has a type, even the literals, so the types of
these are respectively
is equivalent to
!int, int, boolean, char, int, double, int, double!
int x = 10;!
boolean isFinished = true;!
Type-checking Variable declarations
•  The Java compiler does extensive type-checking to make sure •  Declaring reference types is just the same as for primitive types,
that the program does not have any obvious problems with the type occurring before the name
•  The compiler will not allow the wrong type of value to be String s;!
assigned to a variable BankAccount b1;!
int x;! BankAccount b2;!
x = true; // cannot assign boolean to int SimpleCanvas sc;!
•  Similarly, the compiler will not allow the wrong type of value to •  This has created the variables – the names for the objects –
be used as a method or constructor argument but we have not actually created the objects themselves
•  What about this?
int x = 20;! Although the types don t match perfectly, the
double y;! computer knows that there is a value of type
Creating objects is (almost always)
y = x;! double corresponding to any value of type int done with the Java keyword new
– in this case the value 20.0 is assigned to y!
Creating objects References
•  To actually create the object, the constructor is called Garbage
sc = new SimpleCanvas();! b1!0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 1 1 0 1 0 0 0
b1 = new BankAccount( BillG ,12345,10000);!
•  An object is fundamentally different from a primitive value
•  It does not have a fixed size when it is created
The variable b1 contains a
reference to some location
•  Its size can change during runtime
in the heap
•  For this reason, objects are stored in a different part of the
The actual object
computer s memory, and the value that is stored in the variable
that b1 refers to is
is a reference to the object stored on the heap
•  A reference contains the information needed to find the actual object in the
computer s memory
•  The variable refers to an object (rather than contains an object) The Heap
Some other object
The Golden Rule Summary
•  The behaviour of reference types and primitive types appears •  Java supplies eight primitive types for the most
quite different, but it all hinges on the following observation fundamental pieces of data
•  A variable of primitive type contains a value •  A variable name and type must be declared before the
•  A variable of reference type refers to an object variable can be used in a program.
•  The Java compiler does extensive type-checking to make
sure that the program does not have any obvious
The Golden Rule problems
Whenever a variable is used, it is the contents of the •  Creating objects is (almost always) done with the Java
keyword new!
shoebox that is used
•  Every variable has a name used to refer to it
•  this is the value for a variable of primitive type
•  Every variable has a value, that changes during program
•  this is the reference for a variable of reference type run time.
© CSSE, Gordon Royle 2008
Scope of this lecture
EXPRESSIONS AND •  Assignment statements
ASSIGNMENT •  Expressions
CITS1001
Assignment Statements
! ! !mark = 50;!
!
Read as “the value in variable on the LHS
becomes equal to the value of expression on
the RHS”
ASSIGNMENT STATEMENT
Remember: a running program follows the
RULES of the language. It does not interpret
what you meant to do.
Sequence and Assignment
Assignment computer memory
•  Values are stored into fields (and other variables) via int x, y, z;! x y z
assignment statements: time
x = 10;! 10
(execution
4 order)
y = 4;!
variable = expression; 4
x = y;!
price = cost; 6
z = y + 2;!
•  A variable stores a single value, so any previous value is
lost x y z
final
•  A sequence of statements are performed one after the 4 4 6 state
other. Each statement uses the context provided by the
previous statements.
© CSSE, Gordon Royle 2008
Expressions
•  An expression is a portion of Java code that is evaluated to yield
a value
•  any expression has a type and a value
! ! total = price + 10;!
EXPRESSIONS •  Whenever a statement is executed, each expression will be
evaluated and replaced with its value
•  The process of evaluating expressions and doing something
with the resulting value is the fundamental process of
computing
© CSSE, Gordon Royle 2008 © CSSE, Gordon Royle 2008
Evaluation of Expressions Types of Expression
•  A simple example •  There are several types of expression
•  literals and names
int x;! •  method invocations
x = 10 + 15;! •  object creations
•  compound expressions built up with operators
•  The first line creates a variable called x of type int, while the second •  arithmetic operators
line will evaluate the expression 10+15, replace it with its value
•  relational operators
(which is 25) and then assign the resulting value to x!
•  logical operators
•  Evaluation of an expression may take several steps and require the
cooperation of several objects
double y;!
y = (b1.getBalance()*0.01) +
(b2.getBalance()*0.05);
© CSSE, Gordon Royle 2008 © CSSE, Gordon Royle 2008
Literals Casting (an aside)
•  Literals are values that are hard wired into the code •  If the programmer really wants to assign a double value to a
23, 10009, a , -23.456, 10e-5, 100e2 float variable, then the compiler can be prevented from
•  In Java, the types int and double are dominant, in that any complaining by using a cast
literal that does not use a decimal point is assumed to be of type •  The number is simply truncated to fit the new type
int, and any literal uses a decimal point (or scientific notation)
is assumed to be a double! float f;!
•  The Java compiler will complain if you try to assign a value to a f = (float) 23.5;!
smaller type
This says to the compiler I know this
looks dumb, but I do know what I m doing
float f;!
so please just treat this number as a float
f = 23.5;! rather than a double
© CSSE, Gordon Royle 2008 © CSSE, Gordon Royle 2008
Names Method invocations
•  Names are the declared variables that are in scope; the •  Another form of expression is the calling of a non-void method of some
expression has the value and the type currently associated with object
•  The value of the expression is the returned value
that variable
•  The type of the expression is the return type of the method
•  the value in the shoebox if it is a primitive type
•  The method call (here b1 is a BankAccount)
•  the reference in the shoebox if it is a reference type
•  b1.getBalance()
is an expression
•  For example, •  Its type is int, because the return type of the method is int
•  Its value is the current value of b1 s balance!
circle, price, total, mark, studentname, i •  You can use such an expression anywhere that an int is allowed – the
compiler will complain if you violate this
•  type checking is a valuable aid to debugging!
© CSSE, Gordon Royle 2008 © CSSE, Gordon Royle 2008
Object Creations Compound Expressions
•  The construction of an object with new returns a reference to •  A compound expression is obtained by combining one or more
the newly created object, so this is also an expression simple expressions with an operator
5 + 3!
is a compound expression, obtained by combining the literals 5 and 3 with
•  The expression
the operator +
•  The value of this expression is 8
!new SimpleCanvas()!
•  The type of this expression is int
!
•  We have already used one compound expression !
returns a reference to a SimpleCanvas object and so can
•  balance is a simple expression
be used anywhere that such a reference is valid
! •  amount is a simple expression
•  balance + amount is a compound expression
© CSSE, Gordon Royle 2008 © CSSE, Gordon Royle 2008
Classes of Operators Arithmetic Operators
•  Java has a large number of operators •  We will concentrate on the arithmetic operators first
•  Arithmetic Operators •  They are as follows:
•  take numeric expressions and perform arithmetic on them, producing numeric
answers
•  Relational Operators Precedence Operator Operation Association
•  take numeric, or other, expressions and make logical tests of equality, inequality
etc, producing boolean answers + Unary plus
•  Logical Operators 1 Right-to-left
- Unary minus
•  take boolean expressions and combine them using the rules of logic, producing
boolean answers * Multiplication
•  Miscellaneous Operators 2 / Division Left-to-right
•  other operators, acting on Strings, bit patterns etc. % Remainder
+ Addition
3 Left-to-right
- Subtraction
© CSSE, Gordon Royle 2008 © CSSE, Gordon Royle 2008
Association Arithmetic Operators
•  The association rules explain how to combine a sequence of •  These behave (almost) as you would expect
operators of the same precedence
•  Consider evaluating the expression Expression Value
100 / 10 / 5 23+53
! 76
!
•  The / operator associates left-to-right so the value is 13*5
! 65
!
(100 / 10) / 5! 30/5
! !
6
•  If it associated right-to-left, it would be 100 / (10 / 5)! 2.37 * 2
! 4.74
!
•  The association rules just follow normal mathematical usage, so 12 - 15
! -3
!
there are no surprises
•  But what is 5 * 6 + 3 * 2 - 4 + 6 * 11 ?
© CSSE, Gordon Royle 2008 © CSSE, Gordon Royle 2008
Precedence Watch your types!
•  The compiler uses the precedence and association rules to •  Every expression has a type, which depends on the operators
determine the order of evaluation! involved and the types of the operands
5 * 6 + 3 * 2 - 4 + 6 * 11! •  In particular, the division operator / returns an int if its
becomes! operands are ints
(5 * 6) + (3 * 2) - 4 + (6 * 11)!
•  So,
because * has a higher precedence than + or -
•  7/5 yields 1
•  The resulting expression is calculated left to right
•  12/4 yields 3, but so does 13/4 and 14/4
•  7.0/5 yields 1.4, as does 7/5.0 or 7.0/5.0 because the expression
(((30 + 6) - 4) + 66)! is a floating point number
•  The integer is obtained by truncating the expression
•  The programmer can explicitly use parentheses if a particular •  100/51 yields 1
order is required
© CSSE, Gordon Royle 2008 © CSSE, Gordon Royle 2008
Integer Division The remainder operator
•  Java s integer division is always a fertile source of difficult-to- •  The operator % returns the remainder in a division with two
trace bugs integer arguments
double d = 8 / 5;!
Expression Value
•  After this statement the value of d is 1.0 and not 1.6 !
10 % 3
! !
1
•  Why? 12 % 4
! !
0
•  first the expression 8 / 5 is evaluated, and as both the arguments are of
13 % 7 % 4
! !
2
type int, the answer is truncated to an int!
13 % (7 % 4)
! !
1
•  then the value 1 is assigned to the double variable, and hence d has the
value 1.0 •  An important Java idiom or cliché is the use of / and % together
•  This leads to some potentially confusing situations •  If someone is 7000 days old, then how old are they?
2.0/3 * 6 is not equal to 2/3 * 6.0! 7000/365 years, plus 7000%365 days
!
© CSSE, Gordon Royle 2008
The CodePad Evaluate an expression
•  Enter any expression in
Turn on the CodePad by using the View menu and selecting order to have it
Show Code Pad! immediately evaluated
•  Here we discover that
This is the CodePad 15 % 11 !
which allows you to has the value 4 and the
enter either expressions type int!
or statements and have
them performed •  Notice that the CodePad
immediately knows you want to evaluate
an expression because it has
no semicolon
© CSSE, Gordon Royle 2008
© CSSE, Gordon Royle 2008 © CSSE, Gordon Royle 2008
Relational operators Logical Operators
•  Relational operators are crucial in allowing a programs to •  Boolean expressions can be combined into compound
choose among different courses of action depending on the expressions using operators for NOT, AND and OR
results of calculations
•  They are often used to determine a program s flow of control,
using if statements (and others) Operator Operation
•  if the balance is less than zero, then print out an overdraft statement
a && b
! a AND b
!
if (balance < 0) {!
a || b
! a OR b
!
// print out the overdraft statement!
} !a
! NOT a
!
© CSSE, Gordon Royle 2008 © CSSE, Gordon Royle 2008
Use of the logical operators Relational Operators
•  The logical operators combine boolean expressions in the obvious way •  The six relational operators compare numeric values and return
•  Suppose that <bool1>'and <bool2>'represent arbitrary boolean expressions a boolean
<bool1>'&&'<bool2>' Operator Operation
is true if both <bool1>'and <bool2>'are true a == b
! Is a equal to b
<bool1>'||'<bool2>' a != b
! Is a not equal to b
is true if either <bool1>'or <bool2>'are true a > b
! Is a greater than b
!'<bool1>'
a < b
! Is a less than b
is true if <bool1>'is false, and false if <bool1>'is true!
a >= b
! Is a greater than or equal to b
!
a <= b
! Is a less than or equal to b
© CSSE, Gordon Royle 2008 32
Shortcut Evaluation Summary: Expression and Assignment Rules
•  Java uses shortcut evaluation of the logical operators
•  as soon as it knows the final answer it stops calculating •  Assignment statement means “the value in variable on the
LHS becomes equal to the value of expression on the RHS”
if (balance > 2000000 || accountName.equals( Kerry Packer )) {! •  An expression is a portion of Java code that is evaluated to
// send grovelling letter!
}!
yield a value
! •  However complicated the expression, it is evaluated from a
•  There are two relational tests, one on balance and the other
tree of operations and values to give a final value
on accountName, combined with an OR
•  if the first test is true, then the entire boolean expression will be true interest = Math.pow(bal,monthlyRate);

regardless of the second test 

•  thus, Java saves time by not even bothering to do the second test bal = bal + interest - monthlyPayment;!
Objects First with Java - A Practical Introduction using BlueJ,
© David J. Barnes, Michael Kölling
Lecture Outline
•  The ArrayList Collection
GROUPING OBJECTS •  Process all items : the for-each loop
Collections, the for-each loop and the while loop
Slides Source: Objects First with Java - A Practical Introduction using
BlueJ, © David J. Barnes, Michael Kölling
2
Scope of this lecture
•  Expressions
•  Conditional Statements
CONDITIONALS
CITS1001
Source ppts: Objects First with Java - A Practical Introduction using BlueJ,
© David J. Barnes, Michael Kölling
And Gordon Royle, UWA
Reflecting on the ticket machines
•  Their behavior is inadequate in several ways:
•  No checks on the amounts entered.
•  No refunds.
•  No checks for a sensible initialization.
•  How can we do better?
MAKING CHOICES •  We need more sophisticated behavior.
Making choices in everyday life Making a choice in everyday life
•  If I have enough money left, then I will go out for a meal
•  otherwise I will stay home and watch a movie. if(I have enough money left) {
go out for a meal;
}
else {
stay home and watch a movie;
}
Objects First with Java - A Practical Introduction using BlueJ, © Objects First with Java - A Practical Introduction using BlueJ, © David
David J. Barnes, Michael Kölling J. Barnes, Michael Kölling
Making a choice in the
Making choices in Java ticket machine
public void insertMoney(int amount)
boolean condition to be tested {
if keyword
if(amount > 0) {
actions if condition is true balance = balance + amount;
}
if(perform some test) { else {
Do these statements if the test gave a true result System.out.println(
} "Use a positive amount: " +
else { amount);
Do these statements if the test gave a false result }
} }
actions if condition is false
else keyword
Variables – a recap
•  Fields are one sort of variable.
•  They store values through the life of an object.
•  They are accessible throughout the class.
•  Parameters are another sort of variable:
How do we write 'refundBalance'? •  They receive values from outside the method.
•  They help a method complete its task.
•  Each call to the method receives a fresh set of values.
•  Parameter values are short lived.
Local variables Scope highlighting
•  Methods can define their own, local variables:
•  Short lived, like parameters.
•  The method sets their values – unlike parameters, they
do not receive external values.
•  Used for temporary calculation and storage.
•  They exist only as long as the method is being
executed.
•  They are only accessible from within the method.
Scope and lifetime Local variables
•  Each block defines a new scope.
•  Class, method and statement. A local variable
•  Scopes may be nested:
public int refundBalance()
•  statement block inside another block inside a method body inside
{
a class body. No visibility
int amountToRefund;
modifier
•  Scope is static (textual). amountToRefund = balance;
balance = 0;
•  Lifetime is dynamic (runtime).
return amountToRefund;
}
Scope and lifetime // This method should return how many of its three
// arguments are odd numbers.
•  The scope of a local variable is the block in which it is public static void printNumOdd(int n1, int n2, int n3) {
declared.
int count = 0;
•  The lifetime of a local variable is the time of execution of
the block in which it is declared. if (n1 % 2 != 0) {
•  The scope of a field is its whole class. count++;
•  The lifetime of a field is the lifetime of its containing object. } else if (n2 % 2 != 0) {
count++;
} else if (n3 % 2 != 0) {
count++;
}
System.out.println(count + " of the 3 numbers are odd.");
}
Summary Summary of Conditional Statement Rule
•  ‘Correct behavior often requires objects to make •  First evaluate the expression (giving true or false)
decisions •  If true then execute the first statement(s)
•  Objects can make decisions via conditional (if) •  Otherwise execute the second statement(s)
statements •  The else part is optional
•  A true-or-false test allows one of two courses of
actions to be taken if (input.contains("bye")) {!
finished = true;!
} else {!
response = responder.generateResponse(input);!
System.out.println(response);!
}!
Objects First with Java - A Practical Introduction using BlueJ,
© David J. Barnes, Michael Kölling
Lecture Outline
•  The ArrayList Collection
GROUPING OBJECTS •  Process all items : the for-each loop
Collections, the for-each loop and the while loop
Slides Source: Objects First with Java - A Practical Introduction using
BlueJ, © David J. Barnes, Michael Kölling
Objects First with Java - A Practical
Introduction using BlueJ, © David J.
Barnes, Michael Kölling
The requirement to group objects
•  Many applications involve collections of objects:
•  Personal organizers.
•  Library catalogs.
•  Student-record system.
•  The number of items to be stored varies.
ARRAYLIST COLLECTION •  Items added.
•  Items deleted.
Objects First with Java - A Practical Objects First with Java - A Practical
Introduction using BlueJ, © David J. Introduction using BlueJ, © David J.
Barnes, Michael Kölling Barnes, Michael Kölling
An organizer for music files Class libraries
•  Track files may be added. •  Collections of useful classes.
•  There is no pre-defined limit to the number of files. •  We don t have to write everything from scratch.
•  It will tell how many file names are stored in the collection. •  Java calls its libraries, packages.
•  It will list individual file names. •  Grouping objects is a recurring requirement.
•  Explore the music-organizer-v1 project. •  The java.util package contains classes for doing this.
import java.util.ArrayList;
/**
* ...
Collections
*/
public class MusicOrganizer •  We specify:
{ •  the type of collection: ArrayList
// Storage for an arbitrary number of file names. •  the type of objects it will contain: <String>
private ArrayList<String> files;
•  private ArrayList<String> files;
/**
* Perform any initialization required for the
•  We say, “ArrayList of String”.
* organizer.
*/
public MusicOrganizer()
{
files = new ArrayList<String>();
}
...
}
Generic classes Creating an ArrayList object
•  Collections are known as parameterized or •  In versions of Java prior to version 7:
generic types. •  files = new ArrayList<String>();
•  ArrayList implements list functionality: •  Java 7 introduced diamond notation
•  add, get, size, etc. •  files = new ArrayList<>();
•  The type parameter can be inferred from the variable
•  The type parameter says what we want a list of:
being assigned to.
•  ArrayList<Person> •  A convenience.
•  ArrayList<TicketMachine>
•  etc.
Objects First with Java - A Practical
Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Object structures with collections Adding a third file
Objects First with Java - A Practical Objects First with Java - A Practical
Introduction using BlueJ, © David J. Introduction using BlueJ, © David J.
Barnes, Michael Kölling Barnes, Michael Kölling
Features of the collection Using the collection
public class MusicOrganizer
•  It increases its capacity as necessary. {
private ArrayList<String> files;
•  It keeps a private count:
•  size() accessor. ...
•  It keeps the objects in order.
public void addFile(String filename)
•  Details of how all this is done are hidden. {
files.add(filename); Adding a new file
•  Does that matter? Does not knowing how prevent us from using it?
}
public int getNumberOfFiles()
{
return files.size(); Returning the number of files
(delegation)
}
...
}
Objects First with Java - A Practical Objects First with Java - A Practical
Introduction using BlueJ, © David J. Introduction using BlueJ, © David J.
Barnes, Michael Kölling Barnes, Michael Kölling
Index numbering Retrieving an object
public void listFile(int index)
{ Index validity checks
if(index >= 0 &&
index < files.size()) {
String filename = files.get(index);
System.out.println(filename);
}
else {
// This is not a valid index.
}
}
Retrieve and print the file name
Needed? (Error message?)
Objects First with Java - A Practical
Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Removal may affect numbering The general utility of indices
•  Using integers to index collections has a general utility:
•  next is: index + 1
•  previous is: index – 1
•  last is: list.size() – 1
•  the first three is: the items at indices 0, 1, 2
•  We could also think about accessing items in sequence:
0, 1, 2, …
Objects First with Java - A Practical Objects First with Java - A Practical
Introduction using BlueJ, © David J. Introduction using BlueJ, © David J.
Barnes, Michael Kölling Barnes, Michael Kölling
Review Review
•  Collections allow an arbitrary number of objects to •  Items may be added and removed.
be stored. •  Each item has an index.
•  Class libraries usually contain tried-and-tested •  Index values may change if items are removed (or further
collection classes. items added).
•  The main ArrayList methods are add, get, remove
•  Java’s class libraries are called packages. and size.
•  We have used the ArrayList class from the •  ArrayList is a parameterized or generic type.
java.util package.
Main concepts to be covered
•  Loops: the for-each loop
•  Loops: the while loop
•  Iterators (extension material)
FOREACH LOOP
Iteration fundamentals For-each loop pseudo code
•  We often want to repeat some actions over and over.
General form of the for-each loop
•  Loops provide us with a way to control how many times
for keyword
we repeat those actions. loop header
•  With collections, we often want to repeat things once for
for(ElementType element : collection) {
every object in a particular collection. loop body
}
Statement(s) to be repeated
Pseudo-code expression of the actions
of a for-each loop
For each element in collection, do the things in the loop body.
A Java example Selective processing
•  Statements can be nested, giving greater selectivity:
/**
* List all file names in the organizer.
*/ public void findFiles(String searchString)
public void listAllFiles() {
{
for(String filename : files) { for(String filename : files) {
System.out.println(filename); if(filename.contains(searchString)) {
}
} System.out.println(filename);
}
for each filename in files, print out filename }
}
Search and return pattern Critique of for-each
•  Easy to write.
public String findFiles(String searchString)
•  Termination happens naturally.
{ •  The collection cannot be changed.
for (String filename : files) {
if (filename.contains(searchString)) { •  There is no index provided.
return filename; // return the first match if one is found
•  Not all collections are index-based.
}
} •  We can t can stop part way through
return “”; //return empty string if NO match is found
}
when a return is used;
•  e.g. find-the-first-that-matches and return
•  It provides definite iteration – aka bounded
iteration .
Process all items pattern Summary of for-each rule
The for-each loop is used whenever we need to perform 1. Get first element of the collection files
some action on every item in a collection: 2. Execute statement using that value
view every one 3. Get next element from the collection and repeat from 2
change every one 4. But if no elements left then stop
check every one
select some or count some from every one for (String filename : files) {!
if (filename.contains(searchString)) {

Examples: see MusicOrganiser.java and Club.java code in System.out.println(filename);

the handouts and MarksAnalyser in the labs }!
}!
Main concepts to be covered
JAVA LIBRARY •  Using library classes: String, Math, Color
•  Reading documentation
CLASSES •  Java 7 API
http://www.csse.uwa.edu.au/programming/jdk-1.7/api/
CITS1001
(see menu link from cits1001 web page)
Slides Source: Objects First with Java - A Practical Introduction
using BlueJ, © David J. Barnes, Michael Kölling
5.0
The Java class library Hint: using code completion
•  Thousands of classes. •  The BlueJ editor supports lookup of methods
•  Tens of thousands of methods. •  Use Ctrl-space after a method-call dot to bring up a list of
•  Many useful classes that make life much easier. available methods
•  Library classes are often inter-related. •  Use Return to select a highlighted method
•  Arranged into packages.
•  Use code completion to help you remember method
names of library classes
Code completion in BlueJ
STRING LIBRARY
String Library Documentation for startsWith
•  Methods for creating and manipulating Strings of startsWith
characters
public boolean startsWith(String prefix)
•  String greeting = “hello world!”; Tests if this string starts with the specified
prefix.
•  String output = “hello ” + name + “, you have ” + points;
Parameters:
prefix - the prefix.
•  More details later in the unit
Returns:
true if the …; false otherwise
Methods from String
•  contains
•  endsWith
•  indexOf
•  charAt
•  substring
•  toUpperCase toLowerCase
•  Trim
MATH LIBRARY
•  More about Strings in Lecture 13
11
Using the class Math Math.random()
•  Whenever you need a mathematical function, it will public static double random()!
(probably) be the in the class Math!
•  java.lang.Math (can be referred to just as Math)
Returns a double value with a positive sign, greater than or
•  For example, Java does not have a power operator, but it is
equal to 0.0 and less than 1.0
available in Math!
public static double circleArea(double radius) {
Try it in the BlueJ codePad
double area = 3.14159 * Math.pow(radius,2);
return area;
Example
}
Aside: Why is this is poor quality code?
boolean isheads =
!(Math.random() < 0.5);!
13 14
Math Constants Utility Classes
•  Class variables are often used to provide access to constants •  A class like Math that contains only static methods is
– values that are frequently used but not changed sometimes called a utility class, because it just provides
•  Constants can be numerical values utility methods for use in other classes
•  Math.PI!
•  There is no point in ever creating an object of the class Math
•  Math.E! because it can never do anything that the existing methods
!
cannot do
public static double circleArea(double radius) {! •  In fact it has been made impossible to create an object of the
double area = Math.PI * Math.pow(radius,2);! class Math!
•  this is done by giving a dummy constructor, but making it private!
return area;!
}!
16
Constant Objects: Colours
•  import java.awt.Color; (before the class header)
•  The class java.awt.Color makes available a number of
“pre-constructed’’ objects
Color.RED!
COLOR LIBRARY Color.BLUE!
…!
Color.BLACK!
•  You can use these colours without having to construct them
from scratch
Review
•  Java has an extensive class library.
•  A good programmer must be familiar with the
library.
•  The documentation tells us what we need to
OBJECT INTERACTION
know to use a class (its interface). CITS1001
•  Use BlueJ’s code completion: type Ctrl-space
after a method-call dot to bring up a list of
available methods
Overview A digital clock
•  Coupling and Cohesion
•  Internal/external method calls
•  null objects
•  Chaining method calls
•  Class constants
•  Class variables
Abstraction and modularization Modularizing the clock display
•  Abstraction is the ability to ignore details of parts to focus
attention on a higher level of a problem.
•  Modularization is the process of dividing a whole into
well-defined parts, which can be built and examined One four-digit display?
separately, and which interact in well-defined ways.
Or two two-digit
displays?
Implementation - NumberDisplay Implementation - ClockDisplay
public class NumberDisplay public class ClockDisplay
{ {
private int limit; private NumberDisplay hours;
private int value; private NumberDisplay minutes;
Constructor and Constructor and
methods omitted. methods omitted.
} }
Classes define types Object diagram
•  New concept: classes define types
private NumberDisplay hours;
•  A class name can be used as the type for a variable.
Variables that have a class as their type can store objects
of that class.
Dynamic view at runtime (when the system is running)
Object diagram Class diagram
•  The object diagram shows the objects and their
relationships at one moment in time during the
execution of an application.
•  It gives information about objects at runtime and
presents the dynamic view of a program.
ClockDisplay depends on NumberDisplay
ClockDisplay makes use of NumberDisplay
Class diagram Objects creating objects
•  The class diagram shows the classes of an application public class ClockDisplay
{
and the relationships between them. private NumberDisplay hours;
•  It gives information about the source code and presents private NumberDisplay minutes;
private String displayString;
the static view of a program.
public ClockDisplay()
{
hours = new NumberDisplay(24);
minutes = new NumberDisplay(60);

}
}
Objects creating objects ClockDisplay object diagram
in class ClockDisplay:
hours = new NumberDisplay(24);
actual parameter
in class NumberDisplay:
public NumberDisplay(int rollOverLimit);
formal parameter
Method calling External method call
•  external method calls
public void timeTick()
{
! !minutes.increment();
minutes.increment();
if(minutes.getValue() == 0) {
// it just rolled over! object . methodName ( parameter-list )
hours.increment();
}
updateDisplay();
}
Exerise: modify this method to include a day of week
NumberDisplay
(e.g. 0=Mon to 6=Sun).
What test cases should we to use?
Internal method call Internal method
•  internal method calls /**
! !updateDisplay(); * Update the internal string that
* represents the display.
•  No variable name is required. */
private void updateDisplay()
•  this
{
•  could be used as a reference to the invoking object, but not used displayString =
for method calls. hours.getDisplayValue() + ":" +
minutes.getDisplayValue();
}
Objects First with Java - A Practical
Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Method calls null
•  NB: A method call on another object of the same type •  The Java reserved word null is used to mean “no object”
would be an external call. when an object variable is not currently referring to a
•  ‘Internal’ means ‘this object’. particular object.
•  ‘External’ means ‘any other object’, regardless of its type. •  A field that has not explicitly been initialised will contain
the value null by default.
null Anonymous objects
•  null is a special value in Java •  Objects are often created and handed on elsewhere
•  Object fields are initialized to null by default. immediately:
•  You can test for and assign null:
Lot furtherLot = new Lot(…);
private NumberDisplay hours; lots.add(furtherLot);
if(hours != null) { ... } •  We don t really need furtherLot:
hours = null; lots.add(new Lot(…));
Chaining method calls Chaining method calls
•  Methods often return objects. •  Each method in the chain is called on the object returned
•  We often immediately call a method on the returned from the previous method call in the chain.
object.
Bid bid = lot.getHighestBid();
Person bidder = bid.getBidder();
String name =
•  We can use the anonymous object concept and chain lot.getHighestBid().getBidder().getName();
method calls:
lot.getHighestBid().getBidder() Returns a Bid object from the Lot
Returns a Person object from the Bid
Returns a String object from the Person
Class variables
CLASS AND CONSTANT •  A class variable is shared between all instances of the
class.
•  In fact, it belongs to the class and exists independent of
VARIABLES any instances.
•  Designated by the static keyword.
•  Public static variables are accessed via the class name;
e.g.:
•  Thermometer.boilingPoint
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Class variables Constants
•  A variable, once set, can have its value fixed.
•  Designated by the final keyword.
•  final int max = list.size();
•  Final fields must be set in their declaration or the
constructor.
•  Combing static and final is common.
Class constants
•  static: class variable
•  final: constant
private static final int gravity = 3;
•  Public visibility is less of an issue with final fields.
•  Upper-case names often used for class constants:
REPETITION
public static final int BOILING_POINT = 100;
CITS1001
public static final int WINDOW_WIDTH = 400;
Best Practice: Define constants instead of scattering
“magic numbers” through your code.
Makes code easier to read and avoids update errors
when changes are made.
2
Scope of this lecture Repetition
•  Repetition •  Computers are good at repetition
•  For loops •  We have already seen the for each loop
•  While loops •  The for loop is a more general loop form
•  It is often used to iterate (repeat an activity) a fixed
number of times.
For loop pseudo-code A Java example
for loop version
General form of the for loop
for(initialization; condition; post-body action) { for(int count = 0; count < 100; count++) {
statements to be repeated System.out.println(“I can count to: " + count);
} }
Equivalent in while-loop form
while loop version
initialization; int count= 0;
while(condition) { while(count < 100) {
statements to be repeated System.out.println(“I can count to: " + count);
post-body action count++;
} }
The for loop
The$for$loop$is$the$most$important$looping$structure,$although$
it$takes$some$ge5ng$used$to.$It$has$the$following$syntax:
for (<initialization>; <boolean-expression>; <post-
body update>) !
{!
FOR LOOP
<statement-1>!
<statement-2>!
…!
<statement-n>! The body of the loop is the
} collection of statements
between the curly brackets
7
The initialization part The boolean-expression part
•  The initialization part consists of any Java statement •  The boolean expression controls whether or not the body of the
•  It is performed once only when execution first reaches the loop is executed
for loop •  The expression is evaluated immediately after the initialization
•  It is normally used to initialize a counter variable has occurred
! •  If its value is true, then all of the statements in the body of
the loop are executed in turn
•  If its value is false, then the loop has finished, none of the
statements in the body are executed, and execution continues at
the first statement after the for loop
8 9
The post-body update The for loop
Initialization
•  The post-body update is a Java statement that is executed once
Before loop After loop
each time the body of the for loop is executed
•  It is executed immediately after the last statement of the body
has been executed Is the boolean No
expression true?
•  It is usually used to update the counter variable
Yes
Perform Body
Post-body
update
10 11
The for loop idiom How did this work?
Initialization creates i and sets it equal to 0
Check if i < 5, yes
•  for-loops are most often used when we want to do something a
Print out i – causes 0 to appear on terminal window
specific number of times Update i from 0 to 1
Check if i < 5, yes
Print out i – causes 1 to appear on terminal window
for (int i=0; i<5; i=i+1) ! Update i from 1 to 2
{! Check if i < 5, yes
Print out i – causes 2 to appear on terminal window
System.out.println(i);!
Update i from 2 to 3
}! Check if i < 5, yes
Print out i – causes 3 to appear on terminal window
Update i from 3 to 4
Check if i < 5, yes
Print out i – causes 4 to appear on terminal window
System.out.println is Update i from 4 to 5
a library method that just Check if i < 5, NO
prints out its argument to the
12 terminal window 13
The increment operator A one-statement body
•  The post-body update so often consists of •  If the body consists of only one statement, then you can leave
i = i+1; out the braces BUT it is good style to ALWAYS include them
that there is a short-hand notation for this operation
for (int i=0; i<10; i++) {!
•  The statement i=i+1 may be replaced simply by i++!
!System.out.println(i*i);!
for (int i=0; i<5; i++) {! }
System.out.println(i);!
} is the same as
•  In fact i++ is both a statement and an expression
for (int i=0; i<10; i++)!
•  as an expression it has the value of i after the incrementing
System.out.println(i*i);!
Warning: Either use i=i+1; or i++; but never You have been warned! Many hard to trace bugs arise from
mix them together and use i=i++;! leaving out the brackets in a statement block!
14 15
Common mistake Common mistake
! int i;
•  A surplus semicolon! (this mistake is hard to track down)
for (i=0; i<10; i++) ; !
int i;
{! The first for
for (i=0; i<10; i++) ;!
!System.out.println(i*i);! loop has an
{!
!System.out.println(i*i);!
}! empty body (just
}! a single
int i; semicolon!),
•  The output from this code is just
for (i=0; i<10; i++) ! while the
100!
{! second shows
•  Why? What went wrong with the loop? !System.out.println(i*i);! the desired
•  There was a problem with the body }!
body
16 17
Making tables A for loop is the solution
•  Another common use of for loops is to produce tables int celsius;!
int fahrenheit;!
•  For example, suppose you are asked to produce a temperature
!
conversion table listing the Fahrenheit equivalents of 0C - 100C
for (celsius=0; celsius <= 100; celsius = celsius + 5)!
in increments of 5 degrees
{!
!fahrenheit = 32 + celsius*9/5;!
0 32
!System.out.print(celsius);!
5 41
!System.out.print( );!
10 50 !System.out.println(fahrenheit);!
15 59 }
20 68 Notice : the easy-to-read variable names
Notice: the use of System.out.print() to print things
without starting a new line
18 19
A numerical example π to a fixed number of terms
•  It is well known that public double pi(int n) {!
!
! double approx = 0;!
π =$$4$(1$–$1/3$+$1/5$–$1/7$+$1/9$–$…$)$ ! double mult = 4;!
!
•  Suppose that we wish to approximate π using this formula ! for (int i=0; i<n; i++) {!
•  There are two ways that we can do it ! approx = approx + mult/((2*i)+1);!
•  approximate by adding up a fixed number of terms ! mult = -mult;!!
•  approximate to with a certain accuracy ! }!
•  The first way is best done using a for loop !
! return approx;!
!}
20 21
Situation at top of loop Practice
Make a circle object and move it 20 places to
!
i mult
! (2*i+1)
! approx
! the right
!
0 4.0
! !
1 0.0
!
!
1 -4.0
! !
3 4.0
!
!
2 4.0
! !
5 2.666666667
! Circle c = new Circle();
!
3 -4.0
! !
7 3.466666667
! c.makeVisible();
!
4 4.0
! !
9 2.895238095
!
!
5 -4.0
! 11
! 3.339682540
! for ...
!
6 4.0
! 13
! 2.976046176
!
c.moveRight();
Stops when i reaches the requested value
22
Practice for loop with bigger steps
Print the first 10 even numbers greater than 0
// Print multiples of 3 that are below 40.
2 4 6 8 10 12 14 16 18 20 ... for(int num = 3; num < 40; num = num + 3) {
System.out.println(num);
for ...
}
Review
•  For loops are used when an index variable is required
•  For loops are used when the number of repetitions is
known
•  Used with a regular step size
•  For each loops are less error-prone than for loop
•  So use a for each loop unless you need access to indices
WHILE LOOP
or step size
Objects First with Java - A Practical
Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Search tasks are indefinite The while loop
•  We cannot predict, in advance, how many places we will •  A for-each loop repeats the loop body for each object in a
have to look. collection.
•  Although, there may well be an absolute limit – i.e., •  Sometimes we require more variation than this.
checking every possible location. •  We use a boolean condition to decide whether or not to
•  Infinite loops are also possible, either through error or keep going.
the nature of the task. •  A while loop provides this control.
Objects First with Java - A Practical
Introduction using BlueJ, © David J.
Barnes, Michael Kölling
While loop pseudo code Looking for your keys
while(the keys are missing) {
General form of a while loop
look in the next place;
while keyword
boolean test }
while(loop condition) {
loop body Statements to be repeated Or:
}
while(not (the keys have been found)) {
Pseudo-code expression of the actions of
a while loop look in the next place;
}
while we wish to continue, do the things in the loop body
Objects First with Java - A Practical
Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Looking for your keys A Java example
boolean searching = true; /**
* List all file names in the organizer.
while(searching) { */
public void listAllFiles()
if(they are in the next place) { {
searching = false; int index = 0;
while(index < files.size()) {
} String filename = files.get(index);
} System.out.println(filename);
index++;
} Increment index by 1
}
Suppose we don t find them? while the value of index is less than the size of the collection,
get and print the next file name, and then increment index
Elements of the loop Continuing a search
•  We have declared an index variable. •  With a while loop we need to state the condition for
•  The condition must be expressed correctly. continuing:
•  We have to fetch each element. •  So the loop s condition will be the opposite of that for
•  The index variable must be incremented explicitly.
finishing:
index < files.size() && ! found
index < files.size() && searching
•  NB: or becomes and when inverting everything.
Objects First with Java - A Practical
Introduction using BlueJ, © David J.
Barnes, Michael Kölling
Searching a collection Indefinite iteration
int index = 0; •  Does the search still work if the collection is empty?
boolean found = false; •  Yes! The loop s body won t be entered in that case.
while(index < files.size() && !found) {
String file = files.get(index); •  Important feature of while:
if(file.contains(searchString)) { •  The body will be executed zero or more times.
// We don't need to keep looking.
found = true;
}
else {
index++;
}
}
// Either we found it at index,
// or we searched the whole collection.
Objects First with Java - A Practical
Introduction using BlueJ, © David J.
Barnes, Michael Kölling
for-each versus while Searching a collection
•  for-each: •  A fundamental activity.
•  easier to write. •  Applicable beyond collections.
•  safer: it is guaranteed to stop.
•  Necessarily indefinite.
•  while:
•  We must code for both success and failure – exhausted
•  we don’t have to process the whole collection.
search.
•  doesn’t even have to be used with a collection.
•  Both must make the loop s condition false.
•  take care: could be an infinite loop.
•  The collection might be empty.
Objects First with Java - A Practical
Introduction using BlueJ, © David J.
Barnes, Michael Kölling
While without a collection Finishing a search
• How do we finish a search?
• Either there are no more items to
// Print all even numbers from 2 to 30.
int index = 2; check:
while(index <= 30) { index >= files.size()
System.out.println(index);
index = index + 2; • Or the item has been found:
}
found == true
found
! searching
Review Summary of for loop rule
•  Loop statements allow a block of statements 1.  Execute initialiser statement (i=0)
to be repeated. 2.  Test exit condition expression (i<10)
•  The for-each loop allows iteration over a 3.  If exit condition is false then execute loop body (in { })
whole collection. and then execute loop increment statement (i++)
•  The for-loop allows bounded iteration to 4.  If exit condition is true then stop
iterate a fixed number of times. You are responsible for making sure the exit condition is
•  The while-loop allows indefinite iteration when
eventually true!
!
you don’t know how many times a loop will be
repeated. for (int i=0; i<10; i++) {!
!System.out.println(i*i);!
}!
Summary of while loop rule
1.  Evaluate the boolean expression of the while
2.  If true then execute the loop body (in { }) CHARACTERS &
3.  Then repeat from step 1
4.  If expression is not true then exit STRINGS & FILES
You are responsible for ensuring that the condition
does eventually become true (or the program loops CITS1001
forever)
!
!
while(index <= 30) {!
System.out.println(index);!
index = index + 2;!
}!
2 3
Outline In the beginning there was ASCII
•  On computers Characters are represented by a standard code: •  Internally every data item in a computer is represented simply
either ASCII or Unicode by a bit-pattern
•  String is one of the classes of the standard Java library •  To store integers this is not a problem, because we can simply
•  The String class represents character strings such as “This is store their binary representation
a String!”
•  However for non-numerical data such as characters and text we
•  Strings are constant (immutable) objects
need some sort of encoding that assigns a number (really a bit-
•  StringBuilder is used for changeable (mutable) strings pattern) to each character
•  Use the right library for your Strings - it makes a difference!
•  In 1968, the American National Standards Institute announced a
code called ASCII - the American Standard Code for
•  Reference: Objects First, Ch 5 Information Interchange
•  This lecture is based on powerpoints by Gordon Royle UWA •  This was actually an updated version of an earlier code
4 5
ASCII ASCII cont
•  ASCII specified numerical codes for 96 printing characters and •  The lower-case alphabetic characters ‘a’ to ‘z’ were assigned the
32 “control characters” making a total of 128 codes numerical codes from 97 onwards
•  The upper-case alphabetic characters ‘A’ to ‘Z’ were assigned
a 97 b 98 c 99 d 100
the numerical codes from 65 onwards
e 101 f 102 g 103 h 104
A 65 B 66 C 67 D 68 i 105 j 106 k 107 l 108
E 69 F 70 G 71 H 72 m 109 n 110 o 111 p 112
I 73 J 74 K 75 L 76 q 113 r 114 s 115 t 116
M 77 N 78 O 79 P 80 u 117 v 118 w 119 x 120
Q 81 R 82 S 83 T 84 y 121 z 122
U 85 V 86 W 87 X 88
Y 89 Z 90
6 7
ASCII cont Unicode
•  Other useful printing characters were assigned a variety of •  Unicode is an international code that specifies numerical values
codes, for example the range 58 to 64 was used as follows for characters from almost every known language, including
alphabets such as Braille
: 58 ; 59 < 60 = 61
•  Java’s char type uses 2 bytes to store these Unicode values
> 62 ? 63 @ 64 A 65
•  For the convenience of pre-existing computer programs,
Unicode adopted the same codes as ASCII for the characters
covered by ASCII
•  As computers became more ubiquitous, the need for additional
characters became apparent and ASCII was extended in various
different ways to 256 characters
•  However any 8-bit code simply cannot cope with many
characters from non-English languages
8 9
To characters and back Character Arithmetic
•  To find out the code assigned to a character in Java we can •  Using the codes we can do character “arithmetic”
simply cast the character to an int
•  For example, it is quite legitimate to increment a character
variable as in the following code
char ch;!
ch = ‘A’;!
ch++;
•  Now ch has the value ‘B’
•  Conversely we can cast an integer back to a char to find
out what character is represented by a certain value
10 11
Characters as numbers Unicode notation
•  As characters are treated internally as numbers, this means they •  Unicode characters are conventionally expressed in the form
can be freely used in this way U+dddd
•  A loop involving characters
for (char ch = ‘a’; ch <= ‘z’; ch++) {!
// ch takes the values ‘a’ through ‘z’ in turn! •  Here dddd is a 4-digit hexadecimal number which is the code
} for that character
•  You can use characters in a switch statement •  We have already seen that ‘A’ is represented by the code 65,
switch (ch) {!
case ‘N’: // move north!
which is 41 in hexadecimal
case ‘E’: // move east! •  So the official Unicode code for ‘A’ is U+0041
case ‘W’: // move west!
case ‘S’: // move south!
}
12 13
Unicode characters in Java More interesting characters
•  Java has a special syntax to allow you to directly create
characters from their U-numbers
char ch;!
ch = ‘\u0041’;
•  You can of course do this in BlueJ’s code pad
See www.unicode.org
for these code charts
14 15
Strings String literals
•  A string is a sequence of (Unicode) characters •  You can create a String literal just by listing its characters
ABCDEFGHIJ! between quotes
Hello, my name is Hal
String s = “Hello”;!
String s = “\u2600\u2601\u2602”
•  One of the major uses of computers is the manipulation and
processing of text and so string operations are extremely
important
•  Java provides support for strings through two classes in the
fundamental java.lang package: String and
StringBuilder !
•  Use StringBuffer only for multi-threaded applications
16 17
java.lang.String Methods in the String class
•  The class String is used to represent immutable strings •  The String class provides a wide variety of methods for
•  Immutable means that a String object cannot be altered after it has been creating and using strings
created •  Two basic methods are
•  In many other languages a string actually IS just an array of
characters, and so it is quite legal to change a single character public int length()
with commands like •  this returns the number of characters in the String
s[23] = ‘z’ public char charAt(int index)!
•  There are a variety of reasons for having Strings being •  This returns the character at the given index, where as usual the indexing
immutable including certain aspects of efficiency and security starts at 0
18 19
Processing a String Counting vowels
•  These two methods give us the fundamental mechanism for public int countVowels(String s) {!
int numVowels = 0;!
inspecting each character of a String in turn for (int i=0; i<s.length(); i++) {!
char ch = s.charAt(i);!
if (ch == 'a' || ch == 'A') !
public void inspectString(String s) {! numVowels++;!
if (ch == 'e' || ch == 'E’) !
int len = s.length();! numVowels++;!
if (ch == 'i' || ch == 'I')!
for (int i=0; i<len; i++) {! numVowels++;!
if (ch == 'o' || ch == 'O')!
char ch = s.charAt(i);! numVowels++;!
if (ch == 'u' || ch == 'U')!
// Do something with ch! numVowels++;!
}!
}! return numVowels;!
}
}
20 21
String comparison Lexicographic ordering
•  Lexicographic ordering is like alphabetic ordering
•  First we order the alphabet
a, b, c, d, e, f, … , z
•  The following words are alphabetically ordered
aardvark, apple, applet, ban, band!
•  What are the rules for alphabetic ordering of two words?
•  Find the first character where the two words are different and use that
character to order the words e.g. aardvark before apple
•  If there are no such characters, then use the length of the words to order
them e.g ban before band
22 23
compareTo Other methods
•  It is the Unicode value of the characters that determines •  To convert a String to lower case:
their ordering, so for example public String toLowerCase()!
Xylophone comes before apple !
•  The method just specifies that it returns either a negative !
number, 0, or a positive number as follows: !
•  A negative number if the target occurs before the argument !
•  A positive number if the target occurs after the argument !
•  Zero if the target is equal to the argument
•  Hey, I thought Strings were immutable! How can you
change it to lower case?
•  I haven’t because this creates a NEW String that is a lower-case
version of the old one
•  This duplication of Strings can be very memory-intensive
24 25
Many other methods Concatenation
public int indexOf(char ch)! •  We have already seen that the + operator can be used to
public int indexOf(String s) concatenate strings
•  Find the first occurrence in the target string of the character ch, or String s1 = “Hello”;!
substring s and return their location String s2 = “ there”;!
String s = s1 + s2;!
public String replace(char oldChar, char newChar)!
!
•  Create a new String by replacing all occurrences of oldChar with
•  The immutability of Strings can have serious consequences for
newChar!
memory usage that may catch out the unaware - suppose for
public char[] toCharArray()! example that we had to create a single String consisting of all
•  Retrieve the characters in the String as an array of chars
the words in a book
26 27
Slow code Mutable Strings
public String concatenate(String[] words) {! •  The class StringBuilder is used to represent strings that can
String text = words[0];! be efficiently altered
for (int i=1; i<words.length; i++) {! •  Internally a StringBuilder is (essentially) an array of
text = text + “ “ + words[i];! characters
•  It provides efficient ways to append and insert with a whole range
}!
of methods of the following form
return text;!
} !public StringBuilder append(String s)!
!public StringBuilder insert(String s, int offset)!
!
This code is disastrously slow if the number of words is even moderately •  StringBuilder is a single-threaded, non-synchronised class
large (a few thousand) because every single time through the loop creates •  Instances of StringBuilder are not safe for use by multiple
an entirely new String with just one word added, hence a vast amount threads. If synchronisation is required then use StringBuffer
of copying is done and a large number of orphaned objects are created instead.
28 29
Appending Using a StringBuilder to concatenate
public StringBuilder append(String s)! public String concatenate(String[] words) {!
!
•  Appends the String s to the end of the target StringBuilder
StringBuilder text = new StringBuilder(words[0]);!
•  It then returns a reference to the newly altered StringBuilder!
!
•  Notice that the method both alters the target object and also
for (int i=1; i<words.length; i++) {!
returns a reference to it
text.append(" ");!
text.append(words[i]);!
StringBuilder s1 = new StringBuilder(“Hello”);! }!
s1.append(“ there”); !
return new String(text);!
}
30 31
How much difference does it make? Inserting
•  A StringBuilder also permits characters or strings to be
Number of words Using String Using inserted into the middle of the string it represents
StringBuilder
1000 5 ms 1 ms
public StringBuilder insert(int offset, String s)!
2000 17 ms 1 ms
4000 71 ms 2 ms
•  This inserts the string s into the StringBuilder starting at
8000 278 ms 2 ms
the location offset - the other characters are “shifted along”
16000 1126 ms 2 ms
0123456789!
32000 4870 ms 3 ms
Hello John
32 33
Inserting Inside a StringBuilder
StringBuilder s = new StringBuilder(“Hello John”);! •  The StringBuilder internally maintains an array to store
s.insert(5,“ to”);! the characters
•  Usually the array is a bit longer than the number of characters
0123456789! 01234 56789! currently stored
Hello John! Hello John! •  If appends or inserts cause the number of characters to
exceed the capacity, then the StringBuilder automatically
creates a new bigger array and copies everything over
0123456789...!
•  This basic mechanism is used in all of Java’s “growable”
Hello to John! classes
Files File I/O Methods from Simple to Complex
•  Java provides new and simplified API for reading and writing Use these for CITS1001 project
files.
•  There is an excellent tutorial here:
•  http://docs.oracle.com/javase/tutorial/essential/io/file.html
•  Week 10 lab: Write a utility class to read and write
all lines to and from simple text files using the
“commonly used small files” methods.
•  You will need this file class in the project.
•  Also see Barnes and Kölling Chapter 12.9
Source:http://docs.oracle.com/javase/tutorial/essential/io/file.html
36
Review
•  On computers Characters are represented by a standard
code: either ASCII or Unicode SETS, MAPS AND
•  String is one of the classes of the standard Java library
•  The String class represents character strings such as
“This is a String!”
ITERATORS
•  Strings are constant (immutable) objects CITS1001
•  StringBuilder is used for changeable (mutable)
strings
•  Be aware that Java7 has a new (better) API for reading
and writing files
•  Use the right library for your Strings and Files - it makes a
difference!
Overview Working with the library
•  Further library classes •  A competent Java programmer must be able to work with
•  Set the libraries.
•  Map •  You should:
•  know some important classes by name;
•  Iterators for collection classes •  know how to find out about other classes.
•  Remember:
•  References: Barnes and Kölling: Chapter 5 and •  we only need to know the interface, not the implementation.
see the world-of-zuul game in Chapter 6
•  Slides Source: Objects First with Java - A Practical
Introduction using BlueJ, © David J. Barnes, Michael
Kölling
Using library classes Packages and import
•  Single classes may be imported:
•  Classes organized into packages.
•  Classes from the library must be imported using an import java.util.ArrayList;
import statement (except classes from the java.lang
package). •  Whole packages can be imported:
•  They can then be used like classes from the current import java.util.*;
project. •  Good style recommends: import classes named
explicitly (B&K app J)
•  Importation does not involve source code insertion.
Reading class documentation
•  Documentation of the Java libraries in HTML format;
•  Readable in a web browser
•  Class API: Application Programmers’ Interface
•  Interface description for all library classes
Interface vs implementation Interface vs implementation
The documentation includes The documentation does not include
•  the name of the class;
•  a general description of the class; •  private fields (most fields are private)
•  a list of constructors and methods •  private methods
•  return values and parameters for constructors •  the bodies (source code) of methods
and methods
•  a description of the purpose of each constructor the implementation of the class
and method
the interface of the class
Using sets
import java.util.HashSet;
...
HashSet<String> mySet = new HashSet<String>();
mySet.add("one");
SETS AND MAPS mySet.add("two");
mySet.add("three");
Compare with
code for an
ArrayList!
for(String element : mySet) {
do something with element
}
Sets Tokenising Strings
public HashSet<String> getInput()
•  The Set<E> class represents mathematical sets with
{
members of type E: sets are collections with no duplicates System.out.print("> ");
•  The HashSet class implements the Set interface, backed String inputLine =
by a hash table (that is, an efficient index) reader.nextLine().trim().toLowerCase();
•  Set operations include:
String[] wordArray = inputLine.split(" ");
HashSet<String> words = new HashSet<String>();
•  Membership: boolean contains(Object o)!
•  Size of the set: int size()! for(String word : wordArray) {
•  Test for empty set: boolean isEmpty()! words.add(word);
•  Insert an element (if not already present): boolean add(E e)! }
return words;
}
Maps Using maps
•  Maps are collections that contain pairs of values. •  A map with strings as keys and values
•  Pairs consist of a key and a value.
•  Lookup works by supplying a key, and retrieving a
:HashMap
value.
•  Example: a telephone book. "Charles Nguyen" "(531) 9392 4587"
"Lisa Jones" "(402) 4536 4674"
"William H. Smith" "(998) 5488 0123"
Using maps List, Map and Set
•  Alternative ways to group objects.
HashMap <String, String> phoneBook = •  Varying implementations available:
new HashMap<String, String>();
•  ArrayList, LinkedList
phoneBook.put("Charles Nguyen", "(531) 9392 4587"); •  HashSet, TreeSet
phoneBook.put("Lisa Jones", "(402) 4536 4674"); •  But HashMap is unrelated to HashSet, despite similar
phoneBook.put("William H. Smith", "(998) 5488 0123");
names.
String phoneNumber = phoneBook.get("Lisa Jones"); •  The second word reveals organizational relatedness.
System.out.println(phoneNumber);
Until now …
for (Track track: tracks) { … }!
use to process every item in a collection
!
int index = 2;!
Track track = tracks.get(index);!
ITERATORS use to access a particular item (when you
know its index)
TODAY: iterators – for more flexible looping
Iterator and iterator() Iterator
•  Collections have an iterator() method. •  An Iterator is an object that provides functionality to iterate
over all elements of a collection
•  This returns an Iterator object.
•  Iterator<E> has three methods: •  import java.util.Iterator;
•  boolean hasNext()
•  E next()
•  void remove()
Using an Iterator object
returns an Iterator object
myList:List
myList.iterator()
java.util.Iterator
Iterator<ElementType> it = myCollection.iterator();
while(it.hasNext()) {
:Element :Element :Element :Element
call it.next() to get the next object
do something with that object
}
public void listAllFiles()
{
Iterator<Track> it = files.iterator(); :Iterator
while(it.hasNext()) {
Track tk = it.next();
System.out.println(tk.getDetails());
}
}
myList:List myList:List
:Element :Element :Element :Element :Element :Element :Element :Element
:Iterator:Iterator :Iterator :Iterator
hasNext()? hasNext()?
next() next()
Element e = iterator.next();
myList:List myList:List
:Element :Element :Element :Element :Element :Element :Element :Element
:Iterator :Iterator :Iterator :Iterator
hasNext()? hasNext()?
next() next()
Index versus Iterator
myList:List
•  Ways to iterate over a collection:
•  for-each loop.
•  Use if we want to process every element.
•  while loop.
:Element :Element :Element :Element •  Use if we might want to stop part way through.
•  Use for repetition that doesn't involve a collection.
•  Iterator object.
•  Use if we might want to stop part way through.
•  Often used with collections where indexed access is not very
:Iterator efficient, or impossible.
•  Use to remove from a collection.
•  Iteration is an important programming pattern.
hasNext()?
Removing from a collection
Iterator<Track> it = tracks.iterator();
while(it.hasNext()) {
Track t = it.next();
String artist = t.getArtist();
if(artist.equals(artistToRemove)) {
it.remove();
} RANDOM LIBRARY
}
Use the Iterator s remove method.
Using Random Review
•  The Set class represents mathematical sets:
•  The library class Random can be used to generate a
collections with no duplicates
sequence of psuedorandom numbers
•  The HashSet class implements the Set interface,
backed by a hash table (that is, an efficient index)
import java.util.Random;
•  The Map<K,V> class maps keys of type K to
...
Random rand = new Random(); values of type V
... •  The HashMap class implements the Map
int num = rand.nextInt();
int value = 1 + rand.nextInt(100);
interface
int index = rand.nextInt(list.size()); •  All collection classes provide special Iterator
objects that provide sequential access to a whole
collection
Review PROGRAMMING
•  Java has an extensive class library.
•  A good programmer must be familiar with the PATTERNS AND
library.
•  The documentation tells us what we need to know
PROCESS
to use a class (interface). CITS1001
•  The implementation is hidden (information
hiding).
•  We document our classes so that the interface
can be read on its own (class comment, method
comments).
3
Motivation Scope of this lecture
•  “The labs were all really interesting and well •  What are programming patterns?
paced. Large seemingly impossible tasks were •  Why use patterns ?
broken down into manageable chunks.” •  Some useful elementary patterns:
•  CITS1001 student 2012 •  Whether-or-not
•  Process-all-items
•  Variable use patterns
•  Question addressed in this lecture: how to break
“large, seemingly impossible tasks” into •  Program development processes:
manageable chunks. •  Waterfall, Agile, STREAM
Compare and Contrast
public void depositA(int amount) public void depositB(int amount)
{ {
if ( amount > 0 ) { if (amount < 0) {
balance = balance + amount; balance = balance;
PROGRAMMING if (balance > maxBalance) {
} else {
balance += balance;
PATTERNS }
maxBalance = balance; }
} if (maxBalance < balance) {
} maxBalance = balance;
}
}
Programming Patterns Whether Or Not Selection
•  Programming patterns correspond to fragments of code •  Bergen describes the Whether Or Not pattern as follows:
that accomplish common programming goals
•  Recognising and applying patterns is one of skills that “You are in a situation in which some action may be
appropriate or inappropriate depending on some testable
distinguishes expert programmers from novices condition. ... You don't need to repeat the action, only to decide
Whether Or Not it should be done. There are no other actions
to do instead of this one. You want to write simply understood
code.”
•  For example,
if (amount > balance) { !
!balance += amount ; !
}
Whether Or Not Selection (cont) Process All Items
•  Astrachan and Wallingford describe the Process All Items
•  Barnes and Kölling use a variant of the Whether Or Not pattern as: “The items are stored in an array a. Use a
pattern in which an else branch containing only print definite loop to process all the items.”.
statement(s) is used to inform the user of the error •  For example,
condition. For example, for (int k=0; k < a.length; k++) { !
!a[k] = a[k]*2; !
if (amount > balance) { !
} !
!balance += amount ; !
•  Barnes and Kölling use a for-each version of this pattern
} else { !
!System.out.println("amount must be >0"); !
for collections (and arrays since Java 5)
} !
!for (Atype ak : a) { process ak; } !
Temporary Variables Temporary Variable Pattern Examples
•  Kent Beck explains “Temporary variables let you store and •  Collecting
reuse the value of expressions. They can be used to !int sum = 0;!
improve the performance or readability of methods.” !for (int ai : a) { sum = sum + ai; }
•  Caching
!int avg = average(a); int var = 0;!
•  See http://c2.com/ppr/temps.html for
!for (int ai : a) { !
•  Temporary variable
! var = var + Math.Pow(ai-avg, 2); !
•  Collecting temporary variable
!}
•  Caching temporary variable
•  Explaining
•  Explaining temporary variable
!if (a[j] < min) {!
•  Reusing temporary variable
! min = a[j];!
•  Role suggesting temporary variable name
! swappos = j;!
}!
Further Reading
•  Loop patterns: Definite process all items, O. Astrachan and
E. Wallingford. 1998. Retrieved March 2012 from http://
www.cs.duke.edu/ ola/patterns/plopd/loops.html
•  Portland pattern repository: Temporary variables, K. Beck.
1995. Retrieved March 2012 from http://c2.com/ppr/temps.html
•  Patterns for Selection Version 4, J. Bergin., 1999. Retrieved SOFTWARE
March 2009 from http://csis.pace.edu/ bergin/patterns/
Patternsv4.html DEVELOPMENT PROCESS
•  Design Patterns: Elements of Reusable Object-Oriented
Software, Erich Gamma, Richard Helm, Ralph Johnson, John
Vlissides, (the “Gang of Four”), Addison Wesley, 2004
14 15
Outline Some important terms
•  Software Development Processes
•  top down; bottom up; islands of functionality •  Process (n)
•  Stepwise improvement activities •  a series of actions or operations designed to achieve an
•  restructure; refine; extend end
•  STREAM: a systematic process for novices •  Product (n)
•  something produced by a natural or artificial process
•  Reference: •  a saleable or marketable commodity
STREAM: A First Programming Process, •  Lifecycle (n)
M.E. CASPERSEN and M. KOLLING,
•  the series of stages in form and functional activity
ACM Transactions on Computing Education, 9(1), March 2009
through which an organism passes during its lifetime
•  http://dl.acm.org/citation.cfm?id=1513597
16 17
Software Development Lifecycle (SDLC) Chaotic (opportunistic) SDLC
•  A model for the process of developing SW
•  Three standard models (you should know)
•  opportunistic (aka chaotic) Modify Think of Idea
First
•  waterfall Prot otype Until for
•  iterative (agile)
Satisfied Im provement
•  All SDLCs involve steps for requirements, design,
implementation and quality assurance
18 19
Chaotic approach (not recommended) Top Down Development
Waterfall Model
•  Does not acknowledge the importance of working
out the requirements and the design before
implementing a system
•  Since there are no plans, there is nothing to aim
towards, or measure against
•  No explicit recognition of the need for systematic
testing or other forms of quality assurance.
•  Leads to … very high cost of developing and
maintaining software with the opportunistic
approach
20 21
Waterfall model limitations Agile Development Techniques
•  The model implies that you should attempt to complete
a given stage before moving on to the next stage
•  Test Driven Development – because each
•  Does not account for the fact that requirements constantly iteration must deliver working software it must
change.
work.
•  It also means that customers can not use anything until the
entire system is complete. •  Short iterations – from 2 weeks to 2 months.
•  The model makes no allowances for prototyping. •  Strong customer involvement
•  It implies that you can get the requirements right by •  Adaptable process allowing for requirements to
simply writing them down and reviewing them. •  Change
•  The model implies that once the product is finished,
everything else is maintenance. •  Agile and Waterfall are opposite ends of the
“control” spectrum
22 23
Agile Development
Bottom Up Development
•  From 1990s OO programming
•  Lower level components developed first
•  Higher-level functionality slowly built on top of the
low-level modules
24 25
Growing Islands of Functionality
•  Initially implement small subsets of functionality
completely (from the user interface down to the available
machine)
•  Function is gradually increased
by growing
STEPWISE
the available
islands of
DEVELOPMENT
implementation
26 27
Stepwise Development Activities Stepwise Development
•  Extend the specification to cover more (use-)
cases;
•  Refine abstract code to executable code to meet
the current specification;
•  Restructure improves nonfunctional aspects of a
solution without altering its observable behavior:
design improvements through refactoring,
efficiency optimisation, or portability
improvements.
28 29
STREAM STREAM summary (1)
DEVELOPMENT •  Step 1: Stubs
•  Create a Skeleton Class with Method Stubs
PROCESS •  Step 2: Tests
•  Ensure that Tests Are Available
•  Step 3: Representations
•  Consider Alternative Representations
Reference:
STREAM: A First Programming Process, •  Step 4: Evaluation
M.E. Caspersen and M. Kölling, •  Evaluate the Alternative Representations
ACM Transactions on Computing Education, 9(1), March 2009
http://dl.acm.org/citation.cfm?id=1513597
30
STREAM summary (2)
•  Step 5: Attributes
•  Define Instance Fields DEFENSIVE
•  Step 6: Methods
•  Implement the Methods
PROGRAMMING
while there is an unfinished method: CITS1001
Pick an unfinished method;
//Implement the method
while not done:
improve the method;
test;
2
Lecture Outline
•  Why program
defensively?
•  Encapsulation
•  Access Restrictions
DEFENSIVE
•  Unchecked Exceptions PROGRAMMING
•  Checked Exceptions
4 5
Why Program Defensively? Encapsulation
•  Normally, your classes will form part of a larger system
•  One of the most important features of OOP is that it facilitates
•  So other programmers will be using and relying upon your encapsulation – a class encapsulates both the data it uses, and
classes the methods to manipulate the data
•  Obviously, your classes should be correct, but equally •  The external user only sees the public methods of the class, and
importantly, your classes should be robust – that is, resistant to interacts with the objects of that class purely by calling those
accidental misuse by other programmers methods
•  You should aim to ensure that no errors in the final system can •  This has several benefits
be attributed to the behaviour of your classes •  Users are insulated from needing to learn details outside their scope of
•  We use the terminology “client code” for the code written by competence
other programmers that is using your classes •  Programmers can alter or improve the implementation without affecting
any client code
6 7
Access Restrictions public and private
•  Encapsulation is enforced by the correct use of the •  If an instance variable is public, then
access modifiers, public, private, <default>, and •  Any object can access it directly
protected •  Any object can alter it directly
•  If you omit the access modifier, then you get the •  If an instance variable is private, then
default, sometimes known as “package” •  Objects that belong to the same class can access and alter it
•  These latter two modifiers are only really relevant for •  Notice that privacy is a per-class attribute not per-object
multi-package programs that use inheritance, so we •  If a method is public, then
need only consider public and private at the moment •  Any object can call that method
•  If a method is private, then
•  Objects that belong to the same class can call it
8 9
Public Methods Public variables
•  The public interface of a class is its list of public methods, •  Normally instance variables should not be public,
which details all of the services that this class provides since if client code can alter the values of instance
•  Once a class is released (for example, as part of a library), then
variables then the benefit of encapsulation is lost
it is impossible or very difficult to change its public interface,
because client code may use any of the public methods •  If client access to instance variables is desirable, then
•  Public methods must be precisely documented and robust to it should be provided by accessor and/or mutator
incorrect input and accidental misuse methods (getters and setters)
•  Classes should make as few methods public as possible – limit
them to just the methods needed for the class to perform its •  Advantages:
stated function •  Maintenance of object integrity
•  Permits change of implementation
10 11
Simple Example Use mutators instead
class MyDate { public void setDay(int day) {
// Check that day is valid for this.month
public int day;
// before setting the variables
public String month; }
public int year; public int getDay() {
md is corrupt and so could
} return this.day;
cause problems
elsewhere in the system }
Setter methods act as “gatekeepers” to protect the integrity of
MyDate md = new MyDate(); objects.
md.day = 31; Setters reject values that would create a corrupt object.
Getters return a value for client code to use, but do not allow the
md.month = “Feb”; object itself to be changed.
13
Dealing with Errors
•  Even if your classes are well-protected, errors still occur
•  Client code attempts to use your methods incorrectly, by passing incorrect
or invalid parameter values
•  Your code cannot perform the services it is meant to due to
circumstances outside your control (such as an Internet site being
unavailable)
•  Your own code behaves incorrectly and/or your objects become corrupted
JAVA EXCEPTIONS •  Java provides exceptions (checked and unchecked) to handle
these situations
14 15
Invalid Parameters The method “throws” an exception
•  If a parameter is invalid, then the method cannot do anything
•  The String method charAt(int index) sensible with the request and so it creates an object from an
returns the character at position index in a String Exception class and “throws” it
•  If an Exception is thrown, then the runtime environment
immediately tries to deal with it
•  The only valid values for the parameter are numbers from 0 up to •  If it is an unchecked exception, it simply causes the runtime to halt with
one less than the length of the String an error message
•  If it is a checked exception, then the runtime tries to find some object
willing to deal with it
•  What happens if charAt(-1) is ever called?
•  The method charAt throws a
StringIndexOutOfBoundsException
which is unchecked and hence causes the program to cease
execution (crash!)
16 17
Throw your own exceptions Throw your own
•  Your own methods and/or constructors can throw exceptions if Public BankAccount(int amount) {
clients attempt to call them incorrectly if (amount >= 0) {
•  This is how your code can enforce rules about how methods balance = amount;
should be used } else {
throw new IllegalArgumentException(
•  For example, we can insist that the deposit and withdraw "Account opening balance " +
methods from the BankAccount class are called with positive amount + " must be >0”);
values for the amount }
•  The general mechanism is to check the parameters and if they }
are invalid in some way to then •  If the amount is negative then declare the variable ie, create the
•  Create an object from class IllegalArgumentException object and then throw it
•  Throw that object •  The constructor for IllegalArgumentException takes a String
argument which is used for an error message that is returned to
the user
•  Throwing an exception is often used by constructors to
prohibit the construction of invalid objects
18 19
“Predictable” errors Checked Exceptions
•  Unchecked exceptions terminate program execution and are •  Methods prone to such errors may elect to throw
used when the client code must be seriously wrong
checked exceptions, rather than unchecked exceptions
•  However, there are error situations that do not necessarily mean
that the client code is incorrect, but reflect either a transient, •  Using checked exceptions is more complicated than
predictable or easily-correctable mistake – this is particularly using unchecked exceptions in two ways:
common when handling end-user input, or dealing with the
•  The programmer must declare that the method might throw a
operating system
checked exception, and
•  For example, printers may be out of paper, disks may be full,
Web sites may be inaccessible, filenames might be mistyped •  The client code using that method is required to provide code
and so on. that will be run if the method does throw an exception
20 21
Client Perspective try and catch
•  Many of the Java library classes declare that they might throw a •  If code uses a method that might throw a checked
checked exception exception, then it must enclose it in a try/catch block
try {
FileReader fr = new FileReader(“lect.ppt”);
public FileReader(File file) throws FileNotFoundException
// code for when everything is OK
Creates a new FileReader, given the File to read from.
} catch (java.io.FileNotFoundException e) {
Parameters:
// code for when things go wrong
file - the File to read from
Throws: }
FileNotFoundException - if the file does not exist, is a directory
rather than a regular file, or for some other reason cannot be •  Try to open and process this file, but be prepared to
opened for reading.
!
catch an exception if necessary
22 23
try and catch continued Using and Testing exceptions
•  If everything goes smoothly, the code in the try block
is executed, the code in the catch block is skipped @Test(expected =
IllegalArgumentException.class)
•  Otherwise, if one of the statements in the try block
public void testIllegalDeposit() {
causes an exception to be thrown, then execution
immediately jumps to the catch block, which tries to BankAccount(-20);
recover from the problem }
•  What can the catch block do?
•  For human users: report the error and ask the user to change •  Java provides a many exception classes that cover most
their request, or retype their password, or … common possibilities
•  In all cases: Provide some feedback as to the likely cause of
the error and how it may be overcome, even if it ultimately it •  Exceptions are simply objects in a Java program, so you
just causes execution to cease can write your own classes of exceptions if desired
24 25
Some useful Java Exceptions Exception vs RuntimeException
•  IllegalArgumentException •  Checked exceptions in Java extend the
•  IndexOutOfBoundsException java.lang.Exception class
•  NullPointerException •  Unchecked exceptions extend the
•  ArithmeticException
java.lang.RuntimeException class
•  IOException, FileNotFoundException
26 27
Programmer Perspective Checked or Unchecked ?
•  Unchecked Exceptions
•  If you choose to write a method that throws a checked
•  Any method can throw them without declaring the possibility
exception, then this must be declared in the source code, where
you must specify the type of exception that might be thrown •  No need for client code to use try/catch
public void printFile(String fileName) throws •  Causes execution to cease
java.io.FileNotFoundException { •  Used for fatal errors that are unexpected and unlikely to be recoverable
// Code that attempts to print the file •  Checked Exceptions
} •  Methods must declare that they might throw them
•  If you declare that your method might throw a checked •  Client code must use try/catch
exception, then the compiler will force any client code that uses •  Causes control flow to move to the catch block
your method to use a try/catch block
•  Used for situations that are not entirely unexpected and from which
•  This explicitly makes the client code responsible for these clients may be able to recover
situations •  Use only if you think the client code might be able to do something
about the problem
28
Summary
•  Programming defensively means making your code
robust to unexpected use.
•  Use the need to know principle: Only expose the
ARRAYS
parts of your class that your client classes need to CITS1001
know
•  Java exceptions provide a uniform way of handling
errors
•  Exceptions may be Unchecked or Checked
2
Scope of this lecture Fixed-size collections
•  Arrays •  ArrayList is used when the size of a collection is not
•  Constructing arrays
known in advance
•  Arrays of 2 or more dimensions
•  But sometimes the maximum collection size can be pre-
determined.
•  A special fixed-size collection type is available: an array.
•  Unlike the flexible List collections, arrays can store
object references or primitive-type values.
•  Arrays use a special syntax
4 5
Arrays Use of arrays
•  An array is an indexed sequence of variables of the same type •  Arrays are used when we have large numbers of identical
objects that we want to operate on as a collection
•  A collection of student marks that we want to analyse
•  A collection of temperatures that we want to average
•  A collection of names that we want to sort
a!
!
a[0]! a[1]! a[2]! a[3]! a[4]! Warning: In Java, the indexing of
•  The array is called a – its elements are called a[0], a[1], an array starts at 0, so the first
a[2] and so on; each element is a separate variable element of the array a is a[0]!
6 7
Declaring arrays Creating Arrays
•  An array is declared using similar syntax as other variables: •  An array is an object in a Java program
int[] a; •  Therefore the declaration simply creates a reference to refer to
•  Declares a to be a variable representing an array of ints the array, but does not create the array itself
double[] temps;!
•  Hence, the declaration
•  Declares temps to be a variable representing an array of doubles
int[] a;!
String[] names;
•  Declares names to be a variable representing an array of Strings
creates a shoebox called a, big enough to hold an object
Student[] marks; reference, and currently set to the special value null!
•  Declares marks to be a variable representing an array of Student objects
null Only space for the array
reference has been created,
a
not the array itself
8 9
Creating arrays II Creating arrays III
The seven variables do not have individual names, but
•  In order to actually create the array, we need to use the keyword
are referred to by the array name, and an index!
new (just like creating any other object)
int[] a;!
a = new int[7];!
0 0 0 0 0 0 0
a[0] a[1] a[2] a[3] a[4] a[5] a[6]
0 0 0 0 0 0 0
An object containing 7 variables
a a
of type int is created
10 11
Referencing array elements Indexing array elements
Array elements can be used in just the same way as any
•  The power of arrays comes from the fact that the index can be a
other variable of that type!
variable or expression
a[4] = 15;!
int x = 3;!
a[2] = 7;! a[x] = 5;!
a[3] = 2*a[2] – a[4];! a[7-x] = 44;!
a[6] = a[0] + 17;!
0 0 7 1 15 0 17 0 0 7 5 44 0 17
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[0] a[1] a[2] a[3] a[4] a[5] a[6]
12 13
Find maximum integer Arrays of objects
private int max(int[] a) ! •  An array can have any type as its base type, either primitive
{! type or reference type
int max;! •  When using an array of primitive type, there are two steps
max = a[0];! involved
for (int ai : a) ! •  Declare the variable to refer to the array
{! •  Create the space for the array elements using new!
if (ai > max) ! •  When using an array of reference type, there are three steps
{! involved
max = ai;! •  Declare the variable to refer to the array
}! •  Create the space for the array elements using new!
} ! •  Populate the array with objects by repeatedly using new in a loop!
return max;!
}!
14 15
Arrays of Students Creating a unit list
public class Student {!
private String studentNumber;!
!
private int mark;!
Student[] unitList;! Declare
public Student(String studentNumber, int mark) {! !
this.studentNumber = studentNumber;! unitList = new Student[numStudents];! Create
this.mark = mark;! !
}!
!
unitList[0] = new Student( 042371X ,64);!
public String getStudentNumber() {! A skeleton version unitList[1] = new Student( 0499731 ,72);! Populate
return studentNumber;!
of a possible unitList[2] = new Student( 0400127 ,55);!
}!
…!
! Student class in a
public int getMark() {!
student records unitList[numStudents-1] = new Student( 0401332 ,85);!
return mark;!
}! system !
}!
16 17
The three steps Using arrays of objects
null!
•  Using arrays of objects just requires remembering that each
unit
element of the array is (a reference to) an object
public Student topStudent(Student[] unitList) {!
null! null! null! null! null!
Student top;!
unit unit[0] unit[1] unit[2] unit[3] unit[4]
top = unitList[0];!
for (int i=1; i<unitList.length; i++) {!
if (unitList[i].getMark() > top.getMark()) {!
top = unitList[i];!
}!
}!
null! null! null! null! null!
return top;!
unit unit[0] unit[1] unit[2] unit[3] unit[4]
}!
18 19
Find top Student Method signatures
private Student top(Student[] unitList) ! •  Method signatures
{!
Student top = unitList[0];! int max(int[] a) !
!for (Student si : marks) !
{!
•  and
if (si.getMark() > top.getMark()) !
{!
top = si;! Student topStudent(Student[] unitList)
}!
} !
return top;!
}!
20 21
Initialization Initialization
for (int ai : a) {!
if (a[i] > max) {!
!
max = a[i];!
int max;!
}!
max = a[0];!
} !
!
Declare a variable to hold the best so far Check each element in turn, compare it with the best
and initialize it to the first element in the array so far, and update the best so far if necessary
for (Student si : unitList) {!
Student top;!
if (si.getMark() > top.getMark()) {!
top = unitList[0];!
top = si;!
}!
}!
22 23
Return Highest mark
•  What if the user wishes to find the highest mark?
return max;!
•  Two options
•  Return the Student object, and let the user call getMark to find it out
Finally return the extreme element – the highest
•  Provide another simple method that uses topStudent as a helper
int or the Student with the best mark
public int highestMark(Student[] unitList) {!
return top;!
!return this.topStudent(unitList).getMark();!
}!
24
Common array issues Array literals
•  The commonest problem with an array is using an array index •  The size is inferred from the data.
that is out of bounds, either less than 0 or larger than the largest
index private int[] numbers = { 3, 15, 4, 5 };
•  In particular, if we have an array declaration,
int[] a = new int[6];! creation and
then any attempt to access a[6] will generate an initialization
ArrayIndexOutOfBoundsException and execution will be
terminated •  Array literals in this form can only be
•  Another common problem is declaring and creating an array used in declarations
of objects, but forgetting to populate it •  Related uses require new:
•  Any attempt at making a method call such as numbers = new int[] {
unitList[i].getMark() will then result in a 3, 15, 4, 5
NullPointerException! };
Array length
private int[] numbers = { 3, 15, 4, 5 };
int n = numbers.length;
no brackets!
MORE THAN ONE
•  NB: length is a field rather than a method!
•  It cannot be changed – fixed size .
DIMENSION
28 29
2-dimensional arrays 2-dimensional arrays
•  We can declare and use arrays of more than one dimension!
0 0 0
int[][] a = new int[4][3]; a[0]!
a[0][0] a[0][1] a[0][2]
A 2-d array is
This creates an array 0 0 0 0 0 0
really an array of a[1]!
with four rows and a[0][0] a[0][1] a[0][2]
arrays - an array a[1][0] a[1][1] a[1][2]
three columns 0 0 0
a
of length 4, where
a[1][0] a[1][1] a[1][2] each element is an
The row index array of length 3! 0 0 0
0 0 0 a[2]!
ranges from 0-3 and a[2][0] a[2][1] a[2][2]
the column index a[2][0] a[2][1] a[2][2]
from 0-2! 0 0 0
0 0 0
a[3][0] a[3][1] a[3][2] a[3]!
a[3][0] a[3][1] a[3][2]
30
2-dimensional arrays
MORE ARRAYS:
a[0]! a[1]! a[2]! a[3]!
0 0 0 0
a[0][0]
0

a[1][0]
0

a[2][0]
0

a[3][0]
0
THE GAME OF LIFE
a[0][1] a[1][1] a[2][1] a[3][1]
CITS1001
0 0 0 0
a[0][2] a[1][2] a[2][2] a[3][2]
Of course the computer does not actually store the entries in
“rows” and so we should just view this 2d array as being 12
variables arranged in four groups of three
2 3
Scope of this lecture Game of Life
•  The Game of Life •  Invented by John Conway over 30 years ago
•  Implementation •  An example of a cellular automaton
•  Performance Issues •  The game is played on a rectangular grid of cells
•  References:
•  http://www.bitstorm.org/gameoflife/
•  (and hundreds of other websites)
4 5
A model world Births and Deaths
•  This grid is a model world , where each cell is either •  In this model world, time passes in discrete steps known as
occupied, or vacant generations
•  The initial configuration can be specified by the user, or chosen •  The beginning of time is generation zero
randomly •  At each time step, the occupants of the model world live or die
We colour the according to the following rules:
occupied cells, and
•  any individual with zero or one neighbours dies of loneliness
leave the others
•  any individual with four or more neighbours dies of overcrowding
blank; the colour
•  a new individual is born in any unoccupied cell with exactly three
scheme is irrelevant neighbours
to the game, but
•  (The neighbours of a cell are the occupants of the 8 cells
makes the
surrounding that particular cell)
application look
more attractive!
6 7
Example Interpretation
The occupants of
0! 0! 0! 0! 0! these cells died of
loneliness!
1! 2! 3! 2! 1!
1! 1! 2! 1! 1!
0! 0! 0! 0! 0!
1! 2! 3! 2! 1!
1! 2! 3! 2! 1!
0! 0! 0! 0! 0!
1! 1! 2! 1! 1! These two are
new-born
Initial Number of Next generation! 1! 2! 3! 2! 1! babies !
configuration! neighbours of each 0! 0! 0! 0! 0!
cell!
8 9
At the edges
•  The edges of the world are assumed to “wrap around” so that
the map is a flat map of a torus shaped world
10 11
Program Design Separate the responsibilities
•  The program needs classes to perform the following operations •  The Life class should!
•  Maintaining and updating the map of the world •  Maintain the current map of the world
•  Displaying and updating screen view of the world •  Update to “next generation” when requested
•  Provide access to the map for client use
•  We will design two classes for these two aspects, and use a •  The LifeViewer class should
SimpleCanvas to provide the display •  Create a SimpleCanvas to display the map
•  Display a single generation
•  Animate a client-specified number of generations
•  Therefore we will create two classes:
•  Life!
•  LifeViewer!
12 13
The Life instance variables The first constructor
!
public class Life!
We use a 2d array of public Life(boolean[][] initial) {!
{!
type boolean for map = initial;!
private boolean[][] map;! the map of the
width = map.length;!
private int width;! world; the value of
the [i][j] entry height = map[0].length;!
private int height;!
in the array map }!
!
indicates whether
// constructors & methods! the (i,j) cell is
This constructor allows the client to create a
! populated or not
Life object with any initial pattern of
}! occupied and unoccupied cells that they want
14 15
The second constructor Private helper method for initializing
private void initializeMap(double prob) {!
public Life(int width, int height, double probability) {!
for (int i=0; i<width; i++) {!
!map = new boolean[width][height];! for (int j=0; j<height; j++) {!
!this.width = width;! if (Math.random() < prob) {!
map[i][j] = true;!
!this.height = height;!
} else {! If the user specifies 0.2 as
!initializeMap(probability);! map[i][j] = false;!
}!
the probability, then
}!
}! approximately 20% of the
}! cells will be occupied
This allows the client to specify just the width and height }!
and have a random starting configuration created
Math.random() is a quick way to get
random doubles between 0 and 1
16 17
The default constructor A new generation
public void nextGeneration() {!
•  It is always polite to give a default constructor for users
who just wish to get going quickly, and are willing to accept boolean[][] nextMap = new boolean[width][height];!
programmer chosen values for (int i=0;i<width;i++) {!
for (int j=0;j<height;j++) {!
public Life() {! int n = numNeighbours(i,j);!
this(128,128,0.1);! if (n <= 1 || n >= 4) {nextMap[i][j] = false;}!
}! if (n == 2) {nextMap[i][j] = map[i][j];}!
if (n == 3) {nextMap[i][j] = true;}!
}!
Calls the 3-arg constructor with
128, 128 and 0.1 as the values }!
map = nextMap;!
}!
18 19
Code Dissection Code dissection
!boolean[][] nextMap = new boolean[width][height];! We haven’t defined
! this method yet
This creates the space for the “next generation” to be int n = numNeighbours(i,j);!
stored in; we use the instance variables width and if (n <= 1 || n >= 4) {nextMap[i][j] = false;}!
height which are always maintained at the correct if (n == 2) {nextMap[i][j] = map[i][j];}!
values if (n == 3) {nextMap[i][j] = true;}!
!
We cannot do the updating “in place” because the rules
specify that the updating from generation to generation The main loop processes each cell (i,j) in turn. The number
occurs over the entire grid simultaneously; we cannot of neighbours is calculated and the (i,j) cell of nextMap is
change some values and then use the new values in the set according to the rules of the Game of Life.
calculation for other cells
20 21
Code dissection Counting the neighbours
private int numNeighbours(int i, int j) {!
int n=0;!
map = nextMap;!
int ip = (i+1)%width;!
int im = (width+i-1)%width;!
int jp = (j+1)%height;!
The final statement now makes the instance variable int jm = (height+j-1)%height;!
map refer to the newly completed “next generation”. !
Now everything is correctly updated. if (map[im][jm]) n++; if (map[im][j]) n++; !
if (map[im][jp]) n++; if (map[i][jm]) n++; !
if (map[i][jp]) n++; if (map[ip][jm]) n++; !
if (map[ip][j]) n++; if (map[ip][jp]) n++;!
return n;!
}!
22 23
Code Dissection Dealing with wrap-around
When i is equal to width-1,
int ip = (i+1)%width;!
then i+1 is equal to width,
[i-1][j-1]![i][j-1]! [i+1][j-1]!
int im = (width+i-1)%width;!
which is off the right-hand side
int jp = (j+1)%height;!
of the picture
int jm = (height+j-1)%height;! Calculating (i+1)%width
[i-1][j]! [i][j]! [i+1][j]!
has the effect of wrapping
(i,j)!
around back to 0 which is what
Here, ip, im, jp and jm is needed
[i-1][j+1]![i][j+1]! [i+1][j+1]!
refer to i+1, i-1, j+1 and Similarly, when i=0, then
j-1 respectively (width+i-1)%width
wraps around back to
width-1!
24 25
More dissection One performance issue
!!
•  As written, this code consumes a large amount of memory
!if (map[im][jm]) n++;! This is simply a sequence of 8 if
!if (map[im][j]) n++;!
statements that just add 1 to the
!if (map[im][jp]) n++;!
variable n if the corresponding cell
is occupied
!if (map[i][jm]) n++;!
!if (map[i][jp]) n++;! Finally the value n is returned
!if (map[ip][jm]) n++;!
Notice that the method is
!if (map[ip][j]) n++;!
private, and only to be used by
!if (map[ip][jp]) n++;!
the Life object itself
!
!return n;!
!
map nextMap
26 27
What happens during the update? What happens during the update?
•  After the statement map = nextMap! •  When the method finishes..!
This area of
memory is now
map nextMap
“garbage” map
28 29
Garbage Collection In the nextGeneration() method
•  Java will automatically “collect” the garbage for you and •  Delete the code
recycle it, but there is a performance penalty associated with !boolean[][] nextMap = new boolean[width][height];!
this because we do not want to create a new array every generation, but instead
•  If the world is large and you are simulating many generations re-use the instance variable nextMap!
then the memory will very rapidly fill up and the garbage !
collector will keep interrupting the smooth “animation” •  Replace
•  To fix this, it is better to keep two “maps of the world” as map = nextMap; !
instance variables and then just swap them over at each
generation! with
private boolean[][] map;!
boolean[][] swap = map;!
private boolean[][] nextMap;!
map = nextMap;!
nextMap = swap;!
30 31
How does this work?
map map
nextMap nextMap
swap swap
map
map
nextMap
nextMap
swap
32 33
Program Design Interaction
•  Recall that our program design called for three classes •  The LifeViewer needs the Life object to do the following:
•  Life! •  Send the data for the current generation to be displayed
•  LifeViewer! •  Update to the next generation when required
•  SimpleCanvas! •  This means that the Life class must have the following methods
•  The internal structure of the Life class has been written
public boolean[][] getMap()!
•  Now we must decide
•  When called, this will return the array representing the current map
•  How the LifeViewer interacts with the Life object
•  The internal structure of the LifeViewer object
public void nextGeneration()!
•  When called, this will update the Life object to the next generation
34 35
The extra method for Life! Variables defined in LifeViewer!
!public boolean[][] getMap() {! public class LifeViewer {!
private Life life;!
! !return map;!
private int width;!
!}!
private int height;!
private SimpleCanvas c;!
!
private final static int CELL_SIZE = 4;!
Very simple method; simply returns a reference
!
to the array representing the current generation private final static java.awt.Color BACK_COLOUR = java.awt.Color.white;!
private final static java.awt.Color CELL_COLOUR = java.awt.Color.red;!
private final static java.awt.Color GRID_COLOUR = java.awt.Color.black;!
36 37
Instance Variables for LifeViewer! Class Variables for LifeViewer!
public class LifeViewer {! private final static int CELL_SIZE = 4;!
private Life life;!
Each LifeViewer is responsible !
!
for displaying one Life object private final static java.awt.Color BACK_COLOUR = java.awt.Color.white;!
private final static java.awt.Color CELL_COLOUR = java.awt.Color.red;!
!
private final static java.awt.Color GRID_COLOUR = java.awt.Color.lightGray;!
private int width;! The width and height are stored as
private int height;! instance variables for convenience
!
!
Here we define useful constants for the size of the
private SimpleCanvas c;!
Each LifeViewer has one cells and the colours to be used for the drawing.
SimpleCanvas on which to draw They are declared final because they will not
change during the runtime of the program
38 39
The constructor for LifeViewer! What the constructor does!
public LifeViewer(Life life) {! public LifeViewer(Life life) {! The user must
pass the LifeViewer!
! this.life = life;! an instance of Life!
to be displayed
this.life = life;! width = life.getMap().length;!
!
width = life.getMap().length;! height = life.getMap()[0].length;!
height = life.getMap()[0].length;!
! The constructor’s job is to initialize all the instance variables;
c = new SimpleCanvas("Life",width*CELL_SIZE+1,! the argument is an instance of the class Life, and so this
height*CELL_SIZE+1,false);! must be saved in the corresponding instance variable. The
!
width and height variables are then determined by asking
the life object for a reference to its 2-d boolean array,
display();!
and finding its dimensions
}!
40 41
The constructor for LifeViewer! Auto-repaint
•  We are using the 4-arg constructor for SimpleCanvas where the fourth
c = new SimpleCanvas("Life", width*CELL_SIZE+1,! argument is a boolean indicating whether the user wants to use automatic
height*CELL_SIZE+1, false);! repainting or manual repainting
•  Behind the scenes, every drawing command has two effects
•  the new pixel values are stored by the SimpleCanvas!
We need the “+1” to •  the new pixel values are displayed on the computer screen
give the right hand •  The first operation is very fast, because it just involves the computer s
edge and the bottom memory, while the second is much slower
edge a nice border •  When automatic repainting is turned off, drawing commands just affect the
memory and the screen is only changed when the client explicitly requests a
CELL_SIZE! CELL_SIZE! CELL_SIZE! repaint
•  can do lots of drawing commands, followed by one single repaint
+1!
42 43
Displaying the Life object A method to display the Life object
•  Now we need a method to display the Life object
private void display() {!
•  This is basically three steps erase();! Notice how the displaying
•  getting the current map from the Life object functions – erasing the old
!
•  drawing the appropriate picture on the drawing area, which will involve picture, drawing the cells
painting every cell of the grid the right colour drawCells();!
and drawing the grid are all
•  calling rePaint() to have the drawing rendered to the screen drawGrid();!
migrated to separate
! methods; this makes for
c.rePaint();! code that is very easy to read
}! and to update
44 45
Erasing the old picture Drawing the cells
private void drawCells() {!
boolean[][] map = life.getMap();!
private void erase() {!
c.setForegroundColour(BACK_COLOUR);!
c.setForegroundColour(CELL_COLOUR);! First we ask the Life
for (int i=0; i<width; i++) {!
for (int i=0;i<width;i++) {! object to tell us what the
c.drawLine(i,0,i,height);!
for (int j=0;j<height;j++) {! current world map is
if (map[i][j]) {!
}!
for (int k=0;k<CELL_SIZE;k++){!
}!
c.drawLine(i*CELL_SIZE+k,j*CELL_SIZE,!
i*CELL_SIZE+k,(j+1)*CELL_SIZE);!
Familiar code to simply overwrite the entire screen with a !}!
collection of vertical lines in the background colour }!
}!
}!
}!
46 47
Drawing the cells Drawing the grid
for (int i=0;i<width;i++) {! private void drawGrid() {!
for (int j=0;j<height;j++) {! c.setForegroundColour(GRID_COLOUR);!
if (map[i][j]) {!
!
for (int k=0;k<CELL_SIZE;k++){!
for (int i=0;i<=width;i++) {!
c.drawLine(i*CELL_SIZE+k,j*CELL_SIZE,!
c.drawLine(i*CELL_SIZE,0,i*CELL_SIZE,height*CELL_SIZE);!
i*CELL_SIZE+k,(j+1)*CELL_SIZE);!
!}!
}!!
}! for (int j=0;j<=height;j++) {!
}! c.drawLine(0,j*CELL_SIZE,width*CELL_SIZE,j*CELL_SIZE);!
}! Go through the 2-d array; if the value is }!
true then draw a filled-in square to
}! }!
represent a populated cell
48 49
A method to display the Life object Animating the display
private void display() {!
public void animate(int n) The only public method is the
erase();!
{! one that allows the user to
!
for (int i=0;i<n;i++) {! specify that they want to see n
drawCells();! Finally, we repaint the
SimpleCanvas with life.nextGeneration();! generations of “The Game of
drawGrid();!
the new generation drawn Life” one after the other; it is a
display();!
!
on it in order to make all simple loop that asks the
c.repaint();! c.wait(250);! Life object to calculate the
the changes visible on the
}!
screen
}! next generation, then displays
}! it, and then waits briefly to
give an “animated” effect
50 51
Create the Life object It appears on the workbench
52 53
Now create a LifeViewer to view it
The initial randomly
chosen configuration
is displayed on a
SimpleCanvas!
54 55
After 100 generations, A new colour scheme
the map looks a bit can be obtained just by
more organized changing the three
constants
56 57
Extensions Extending the code
•  There are hundreds of research papers, websites and •  We could simply alter the code to accommodate any
recreational articles about Conway s Game of Life particular set of rules, but a more object-oriented approach
•  Life is just one example of an entire class of systems known as
would be to devise a class so that any such rule set could be
cellular automata, many of which have been heavily studied plugged in by the client
•  This maximizes the re-use of the existing code, and
•  There are many variants, but we will just consider what happens
if we change the rules determining birth and death minimizes the temptation to cut-n-paste every time the
user wants to experiment with a new rule set
•  Conway s rules are sometimes described as the String!
•  However, this does require re-engineering the Life class
B3/S23!
•  a new individual is born in a cell with 3 neighbours
•  an individual survives in a cell with 2 or 3 neighbours
58 59
The CARule interface The new Life class
•  The Life class will now maintain a CARule object as an
The CARule class has the following interface - that is, the
following list of methods instance variable car, and refer to it whenever it wants to
decide whether a particular value should cause an individual
The implementation of the methods isn t yet specified to be born or survive
public class CARule {!
for (int i=0;i<width;i++) {!
public CARule(String b, String s); ! for (int j=0;j<height;j++) {!
int n = numNeighbours(i,j);!
public boolean birth(int value);!
nextMap[i][j] = false;!
public boolean survival(int value);! if (map[i][j] && car.survival(n) !
|| !map[i][j] && car.birth(n)) !
}!
nextMap[i][j] = true;!
The role of a CARule object is simply to respond as }!
}!
to whether a particular value is a birth value or
not, or a survival value or not
Listen to the sound of sorting
ALGORITHMS FOR •  Various algorithms
SORTING •  http://www.youtube.com/watch?v=t8g-iYGHpEA
CITS1001 •  Quicksort
•  http://www.youtube.com/watch?v=m1PS8IR6Td0
•  Or Google for sound of sorting
3
Scope of this lecture
•  Linear Search
•  Sorting and Bubble Sort
•  References:
•  Wirth, Algorithms + Data Structures = Programs, Chapter 2
SEARCHING
•  Knuth, The Art of Computer Programming, Volume 3, Sorting and
Searching
This lecture is based on powerpoint slides by Gordon Royle UWA
5 6
Searching Our favourite Student class
public class Student {!
•  Searching refers to the process of finding data items that match private String studentID;!
private int mark;!
certain criteria; we may either want a yes/no answer to a !
question or additional details as well public Student(String studentID, int mark) {!
this.studentID = studentID;!
•  Find out whether any students got a mark of 49
this.mark = mark;!
•  Find out which students got a mark of 49 }!
!
public String getStudentID() {! A skeleton version
•  The simplest searching technique is called linear search, which return studentID;!
of a possible
simply involves looking through each element in turn until we !
}!
Student class in a
find one that matches the criteria public int getMark() {!
student records
return mark;!
}! system
}!
7 8
Collections of Students Linear Search
•  We consider a class list being stored as an ArrayList
•  The question that we will consider is how to retrieve the data for public Student findStudent( ArrayList<Student> classlist, 

! ! ! ! ! ! ! String id) !
a student with a given student number
{!
for (Student s : classlist ) {!
•  So, we will write a method with the following signature String sid = s.getStudentID();!
if (sid.equals(id)) {!
public Student findStudent(ArrayList<Student> classlist, String id)! return s;!
}!
}!
The method returns The student ID we
a (reference to a) The arraylist of want is the other return null;!
Student object students is a parameter parameter }!
9 10
Comments Performance of linear search
•  If the arraylist does contain the desired value, then the method •  How fast does linear search work on an array of n items?
returns true as soon as it is found •  We can identify three situations
•  If the arraylist does not contain the desired value, then the •  Best case, when the input is the most convenient possible
method will return false after checking every element of the •  Worst case, when the input is the least convenient possible
arraylist without success •  Average case, averaged over all the inputs
•  We have shown the general situation of finding an object in a •  In the best case, linear search finds the item at the first position
collection of objects of the array, so it needs 1 comparison
•  In the worst case, linear search does not find the item and so
must perform n comparisons unsuccessfully
•  To calculate the average case performance we would need some
problem-specific assumptions about the input data
11 12
Linear search is too slow Sorted Collections
•  If we have very large amounts of data, then linear search is not •  The reason that
feasible Name Phone number
•  For example, we can view the telephone directory as a very
is quick, while
large array of objects, with each object consisting of a name and
a number Phone number Name
•  If you are asked to find out which person has phone number 9388 6105
then how long would it take you to do this by linear search? is slow is because the “collection” (i.e. phone book) is sorted
•  However, if I ask you to find out the phone number of a specific into alphabetical order, and somehow this allows us to find an
entry much more quickly (we will see why later)
person, then you can do it much, much faster
•  Most useful databases are sorted – dictionaries, indices etc.
•  How do you do it?
•  How can we program a computer to do this?
13 14
Sorting The basic set up
•  Before we examine how to efficiently search in a sorted •  We will implement a number of sorting methods, all of which
collection, we must consider how to sort the collection operate on an array of integers
•  We will again start with the “plain vanilla” example – •  We develop these as a utility class called Sorter – a class with
sorting an array of integers into increasing order no instance variables, but just class (static) methods (e.g. Math)
•  Each method will have a similar signature, where the only thing
before 6! 8! 1! 15!12!2! 7! 4!
that will vary is the name of the sorting technique
after 1! 2! 4! 6! 7! 8! 12!15! public static void nameSort(int[] a)
•  Later we will extend this to sorting arrays of objects •  Each method receives a (reference to an) array as a parameter
according to various other criteria (alphabetical etc) and will sort that array in place
16
bubbleSort
•  The idea behind bubbleSort is to systematically compare pairs
of elements, exchanging them if they are out of order
•  If the array contains n elements, then we view the algorithm as
consisting of n “passes”
•  In the first pass we compare
BUBBLE SORT •  Element 0 with element 1, exchange if necessary
•  Element 1 with element 2, exchange if necessary
•  …
•  Element n 2 with element n 1, exchange if necessary
17 18
The first pass The second pass
•  After the first pass, the largest element will be at the end •  The second pass doesn’t need to make the last comparison
6! 8! 1! 15!12!2! 7! 4! 6! 8! 1! 15!12!2! 7! 4! 6! 1! 8! 12!2! 7! 4! 15! 1! 6! 8! 12!2! 7! 4! 15!
6! 1! 8! 15!12!2! 7! 4! 6! 1! 8! 15!12!2! 7! 4! 1! 6! 8! 12!2! 7! 4! 15! 1! 6! 8! 12!2! 7! 4! 15!
6! 1! 8! 12!15!2! 7! 4! 6! 1! 8! 12!2! 15!7! 4! 1! 6! 8! 2! 12!7! 4! 15! 1! 6! 8! 2! 7! 12!4! 15!
6! 1! 8! 12!2! 7! 15!4! 6! 1! 8! 12!2! 7! 4! 15! 1! 6! 8! 2! 7! 4! 12!15!
19 20
The third pass The fourth pass
•  The third pass can omit the last two comparisons •  The fourth pass is even shorter
1! 6! 8! 2! 7! 4! 12!15! 1! 6! 8! 2! 7! 4! 12!15! 1! 6! 2! 7! 4! 8! 12!15! 1! 6! 2! 7! 4! 8! 12!15!
1! 6! 8! 2! 7! 4! 12!15! 1! 6! 2! 8! 7! 4! 12!15! 1! 2! 6! 7! 4! 8! 12!15! 1! 2! 6! 7! 4! 8! 12!15!
1! 6! 2! 7! 8! 4! 12!15! 1! 6! 2! 7! 4! 8! 12!15! 1! 2! 6! 4! 7! 8! 12!15!
21 22
The fifth and sixth passes Why does it work?
1! 2! 6! 4! 7! 8! 12!15! 1! 2! 6! 4! 7! 8! 12!15! •  We need to have some argument or “proof” that this works
•  We claim that
1! 2! 6! 4! 7! 8! 12!15! 1! 2! 4! 6! 7! 8! 12!15! After the i-th pass, the last i elements in
the array are in their correct positions
•  This is true after the first pass, because the largest element in
1! 2! 4! 6! 7! 8! 12!15! 1! 2! 4! 6! 7! 8! 12!15! the array is encountered at some stage and then “swapped all the
way to the end” of the array
1! 2! 4! 6! 7! 8! 12!15! •  The same argument – applied to the remainder of the array –
shows that the second pass puts the 2nd largest element into
place; repeating this argument i times gives the result
23 24
Coding Bubblesort Sorting Students
public static void bubbleSort(int[] a) {!
public static void bubbleSort(Student[] a) {!
for (int pass=1; pass<a.length; pass++) {!
!
for (int j=0; j<a.length-pass; j++) {! for (int pass=1; pass<a.length; pass++) {!
for (int j=0; j<a.length-pass; j++) {!
if (a[j] > a[j+1]) {!
if (/* a[j] and a[j+1] out of order */) {!
int swap = a[j+1];! Student swap = a[j+1];!
a[j+1] = a[j];!
a[j+1] = a[j];!
a[j] = swap;!
a[j] = swap;! }! Almost identical code except
}!
}! that we need to get the right
}! boolean condition to check
}! !
}
when two students are in the
}! “wrong order”
}!
25 26
What order do we want? For alphabetic order
•  The precise form of the statement depends on whether we want •  The comparison between the two Student objects a[j] and
to sort students: a[j+1] first needs to obtain the two ids to compare, so it will
•  Alphabetically according to their studentId involve the two Strings
•  Numerically according to their mark •  String s1 = a[j].getStudentID();
•  In addition, the desired sort could be ascending (lower values •  String s2 = a[j+1].getStudentID();
first) or descending (lower values last) •  To compare two Strings we use the compareTo method
•  Suppose that we want to sort the students into normal
(ascending) alphabetical order by studentId if (s1.compareTo(s2) > 0) {!
// Swap the two Students!
}
28
selectionSort
•  When sorting n items, Selection Sort has the following
properties:
•  The procedure has n stages
SELECTION SORT AND •  Select the smallest element in the array and swap it with the element in
position 0.
INSERTION SORT •  Then calculate the position of the smallest element in the array starting
from position 1, and swap that element into position 1
•  After the i’th stage, the first i items are sorted in order
•  At the (i+1)’st stage, the item originally in position i+1 is incorporated
into the sorted list and placed in position
29 30
Sorting cards Inserting a card
•  In card games, it is common to pick up the cards as they are •  The new card is then inserted into the correct position
dealt and to sort them into order as they arrive
•  For example, suppose your first three cards are
•  Next you pick up a 9 of clubs
31 32
insertionSort Example
•  We can develop this notion into a sorting algorithm called •  Initial array
Insertion Sort
6! 8! 1! 15!12!2! 7! 4!
•  When sorting n items, Insertion Sort has the following
properties: •  Stage 1: Move the first element into position (do nothing)
•  The procedure has n stages
•  After the i’th stage, the first i items are sorted in order 6! 8! 1! 15!12!2! 7! 4!
•  At the (i+1)’st stage, the item originally in position i+1 is incorporated
into the sorted list and placed in position •  Stage 2: Examine the second element and insert it into position
(again do nothing)
6! 8! 1! 15!12!2! 7! 4!
33 34
Stage 3 Stages 4 and 5
6! 8! 1! 15!12!2! 7! 4!
Stage 4 1! 6! 8! 15!12!2! 7! 4!
•  This element is out of position so will have to be inserted
6! 8! 15!12!2! 7! 4! 1! Stage 5 1! 6! 8! 15!12!2! 7! 4!
6! 8! 15!12!2! 7! 4! 1! 1! 6! 8! 15! 2! 7! 4! 12!
6! 8! 15!12!2! 7! 4! 1! 1! 6! 8! 15! 2! 7! 4! 12!
1! 6! 8! 15!12!2! 7! 4! 1! 6! 8! 12! 15! 2! 7! 4!
35 36
Stage 6 Stage 7
1! 6! 8! 12! 15! 2! 7! 4!
1! 2! 6! 8! 12! 15! 7! 4!
1! 6! 8! 12! 15! 7! 4! 2!
1! 2! 6! 8! 12! 15! 4! 7!
1! 6! 8! 12! 15! 7! 4! 2!
1! 2! 6! 8! 12! 15! 4! 7!
1! 6! 8! 12! 15! 7! 4! 2!
1! 6! 8! 12! 15! 7! 4! 2! 1! 2! 6! 8! 12! 15! 4! 7!
1! 6! 8! 12! 15! 7! 4! 2! 1! 2! 6! 8! 12! 15! 4! 7!
1! 2! 6! 8! 12! 15! 7! 4! 1! 2! 6! 7! 8! 12! 15! 4!
37 38
Final stage Code for InsertionSort
1! 2! 6! 7! 8! 12! 15! 4!
public static void insertionSort(int[] a) { !!
!
1! 2! 6! 7! 8! 12! 15! 4! for (int pass=1;pass<a.length;pass++) { !!
int tmp = a[pass];!
1! 2! 6! 7! 8! 12! 15! 4! int pos = pass-1;!
!
1! 2! 6! 7! 8! 12! 15! 4!
while (pos >= 0 && a[pos] > tmp) {!
a[pos+1] = a[pos];!
1! 2! 6! 7! 8! 12! 15! 4!
pos--;!
}!
1! 2! 6! 7! 8! 12! 15! 4!
! ! !!
a[pos+1] = tmp;!
1! 2! 6! 7! 8! 12! 15! 4!
}!
!
1! 2! 4! 6! 7! 8! 12! 15!
}!
39 40
Code Dissection Code dissection
public static void insertionSort(int[] a) { !!
! public static void insertionSort(int[] a) { !!
!
for (int pass=1;pass<a.length;pass++) { !!
for (int pass=1;pass<a.length;pass++) { !!
The variable tmp
! stores the value that
int tmp = a[pass];! int tmp = a[pass];! is to be inserted; the
int pos = pass-1;!
The body of the int pos = pass-1;! variable pos will
!
while (pos >= 0 && a[pos] > tmp) {!
for-loop while (pos >= 0 && a[pos] > tmp) {! eventually contain
a[pos+1] = a[pos];! contains the a[pos+1] = a[pos];! the position where
pos--;!
code for one pos--;! it should be inserted
}!
! ! !!
stage or “pass” } ! ! !!
a[pos+1] = tmp;! of the algorithm a[pos+1] = tmp;!
}!
}! }!
!
}!
41 42
Code dissection Code dissection
public static void insertionSort(int[] a) { !! public static void insertionSort(int[] a) { !!
! This code does the !
for (int pass=1;pass<a.length;pass++) { !! work of shifting for (int pass=1;pass<a.length;pass++) { !!
int tmp = a[pass];! each element in int tmp = a[pass];!
int pos = pass-1;! turn one space int pos = pass-1;! The while loop
while (pos >= 0 && a[pos] > tmp) {! along if it is while (pos >= 0 && a[pos] > tmp) {! finishes when we
bigger than the
a[pos+1] = a[pos];! value to be
a[pos+1] = a[pos];! have found the
inserted. We also
pos--;!
correct position
pos--;! } ! ! !!
need to ensure that for the element,
} ! ! !! we don’t fall off a[pos+1] = tmp;! and so it is now
a[pos+1] = tmp;! the left-hand end }! inserted into this
}! of the array! }! position
}!
Efficiency experiment Performance Comparison
•  Is there any difference between the performance of these
sorting algorithms ?
•  Which one(s) are more efficient ?
•  Why ?
•  Experiment: use the provided Java Sorter class and its
test harness SorterTest to estimate the execution time
of each algorithm for sorting a large, unsorted array.
•  Graph your results on the next page
A note on the accuracy of this test Summary
•  WARNING: testing the execution time of Java code this •  Searching for an element in a collection is a common
way is not completely accurate, in that you will not always requirement
get the same results
•  Searching can be more efficient if the collection is sorted
•  Activities such as garbage collection and other aspects of
the Java Virtual Machine may affect run time •  We study sorting algorithms because they provide good
examples of many of the features that affect the run-time
•  I have used random data and multiple runs to "average
out" unrepresentative runs of program code.
•  For more on the efficiency of Java programs, see for ex, •  Checking the efficiency of your own code ? Consider:
•  Number of loops and depth of nesting
•  Highly recommended: PhD Thesis (CORE winner)
•  Number of comparison operations
Garbage Collection and the Case for
•  Number of swap (or similar) operations
High-level Low-level Programming
•  http://cs.anu.edu.au/~Daniel.Frampton/
DanielFrampton_Thesis_Jun2010.pdf=
2
Scope of this lecture
•  A brief introduction to the concept of recursion
•  Simple recursive programs
RECURSION •  QuickSort
CITS1001
•  This lecture is based on notes by Gordon Royle, UWA
3 4
Recursion The simplest example
•  Consider the problem of computing the factorial function
•  We have already seen that a method in a class can call other
methods, either in the same or other classes
n!= n(n − 1)(n − 2)...(1)
•  However a method in a class can also call itself
•  This self-referential behaviour is known as recursion •  So 2!=2, 3!=6, 4!=24, 5!=120, 6!=720 and so on…
•  Recursion is an extremely powerful technique for expressing •  However rather than define factorial in this way, we could give an
certain complex programming tasks, as it provides a very equivalent, recursive definition
natural way to decompose problems 0!= 1
•  Despite this, there are costs associated with recursion and the n!= n × (n − 1)!
careful programmer will always be aware of these
•  This definition is recursive because it uses factorial in the definition of
factorial
5 6
Factorial in Java What happens in the method call?
public long factorial(int n) {!
factorial(4)! = 4 *! factorial(3)!
if (n == 0) {!
return 1;! We use long just to
give the method factorial(3)! = 3 *! factorial(2)!
}!
slightly greater range
!
factorial(2)! = 2 *! factorial(1)!
return n*factorial(n-1);!
}!
factorial(1)! = 1 *! factorial(0)!
The method factorial calls itself,
but with a smaller argument
factorial(0)! = 1!
7 8
Local variables Ingredients for recursive definition
•  Each recursive call to the method creates a “new copy” of •  Every valid recursive method definition needs two parts – the
the method – all the local variables are created again base case and the recursive part
•  The compiler keeps track of them all so that the programmer
•  The base case gives the value that the method should return for
cannot mix them up
some specified parameters
•  Usually the base case represents some sort of “trivial” case, such as a zero
factorial(4)has a parameter n equal to 4
parameter or an empty list etc.
factorial(3) has its own parameter n, equal to 3
factorial(2) has its own parameter n, equal to 2 •  The recursive part expresses the value to be returned in terms
factorial(1) has its own parameter n, equal to 1
of another call to the same method, but with different
parameters
•  This means that you should not use recursion to replace •  To work correctly, the “different parameters” must be closer to the base
straightforward iteration (like factorial), particularly if the case (in some sense)
loops are performed thousands or millions of times.
9 10
Order is important More than one base case
public long factorial(int n) {! •  There is no need to have just one base case
! •  The (mathematical) definition of the Fibonacci numbers is a
You must put the base recursive definition with two base cases
return n*factorial(n-1);!
case before the recursive
!
part of the definition or F0 = 1
if (n == 0) {! bad things will happen – F1 = 1
return 1;! in this case a stack
}! overflow will result! Fn = Fn −1 + Fn − 2
!
•  This gives the sequence 1, 1, 2, 3, 5, 8, 13, 21, 34, …
}!
11 12
Be careful though Binary Search
public int fibonacci(int n) {!! •  Binary search can be expressed recursively in a very natural
fashion, because we repeatedly perform the same operation of
if (n == 0 || n == 1) {!
calculating the middle element and then searching in an array of
return 1;! half the size
}! •  What is the “simplest case” in this situation?
else {! •  The length of the array is the parameter that is reduced at each
return fibonacci(n-1)+fibonacci(n-2);! stage of binary search and so the base case is when the left and
}!
the right bounds of the array are adjacent
•  In this situation it is trivial to determine whether or not the
}! This looks fine, but in fact is disastrously
slow because it unnecessarily repeats some element we are looking for is in the array or not
calculations over and over again!
13 14
Binary Search Public interface
boolean binarySearch(int[] a, int lf, int rt, int val) {!
•  This method would usually be made private!
if (rt – lf == 1)!
•  The public interface would be the simpler
return a[lf] == val || a[rt] == val;!
!
public boolean binarySearch(int[] a, int val)!
int mid = (lf+rt)/2;!
!
if (a[mid] > val) !
•  Its only role would be to call the recursive version
return binarySearch(a,lf,mid,val);!
else!
public boolean binarySearch(int[] a, int val) {!
return binarySearch(a,mid,rt,val);! return binarySearch(a, 0, a.length-1, val);!
! }!
}!
16
A recursive sorting algorithm
•  Suppose you had to sort the following array with 16 elements
53!49!57!35!18!11!23!62!71! 90! 95!87! 77! 92!83!
•  Just before starting, you notice that the array has a very special
structure
QUICKSORT 62!
53!49!57!35!18!11!23! 71! 90! 95!87! 77! 92!83!
All smaller than 62 All larger than 62
17 18
Divide and conquer But what if the array is not in this nice form?
•  We can now divide the problem into two smaller problems
Then we put it into this nice form!
53!49!57!35!18!11!23! 62! 71! 90! 95!87! 77! 92!83! First we choose an element to be the “fence”, and
then we adjust the array so that the fence is in the
Sort The fence Sort correct position, everything to the left of the fence is
smaller than it, and everything to the right of the
11!18!23!35!49!53!57! 62! 71! 77! 83!87! 90! 92!95! fence is larger than it
62! 49! 24! 77! 98! 53! 90! 11! 57! 95! 82!87! 35! 92! 18! 71!
11!18!23!35!49!53!57! 62! 71! 77! 83!87! 90! 92!95!
•  The two “half-size” problems take much less than half the time! Choose the fence (we explain how later)
19 20
Find out-of-place elements Then swap them over
L R L R
62! 49! 24! 77! 98! 53! 90! 11! 57! 95! 82!87! 35! 92! 18! 71! 62! 49! 24! 18! 98! 53! 90! 11! 57! 95! 82!87! 35! 92! 77! 71!
Now increase L until reaching an element bigger than the fence
L R L Move R
62! 49! 24! 77! 98! 53! 90! 11! 57! 95! 82!87! 35! 92! 18! 71! 62! 49! 24! 18! 98! 53! 90! 11! 57! 95! 82!87! 35! 92! 77! 71!
And decrease R until reaching an element smaller than the fence Exchange
L R
L R
62! 49! 24! 18! 35! 53! 90! 11! 57! 95! 82!87! 98! 92! 77! 71!
62! 49! 24! 77! 98! 53! 90! 11! 57! 95! 82!87! 35! 92! 18! 71!
21 22
Repeat When R < L
Move L R When R < L, then every element to the right of L is
larger than the fence, and every element (except the
62! 49! 24! 18! 35! 53! 90! 11! 57! 95! 82!87! 98! 92! 77! 71! fence) to the left of L is less than the fence
Exchange L R R L
62! 49! 24! 18! 35! 53! 57! 11! 90! 95! 82!87! 98! 92! 77! 71! 62! 49! 24! 18! 35! 53! 57! 11! 90! 95! 82!87! 98! 92! 77! 71!
Swap the fence
Until R < L R L and element R R
62! 49! 24! 18! 35! 53! 57! 11! 90! 95! 82!87! 98! 92! 77! 71! 11! 49! 24! 18! 35! 53! 57! 62! 90! 95! 82!87! 98! 92! 77! 71!
23 24
public void partition(int[] a) {! public void partition(int[] a) {!
int fence = a[0];! int fence = a[0];! The first element in the array is chosen
int left = 1;! int left = 1;!
as the fence and left and right are
int right = a.length-1;! int right = a.length-1;!
set up appropriately
while (right >= left) {! while (right >= left) {!
while (left <= right && a[left] <= fence) ! while (left <= right && a[left] <= fence) !
left++;! left++;!
while (right >= left && a[right] >= fence)! while (right >= left && a[right] >= fence)!
right--;! right--;!
if (right > left) {! if (right > left) {!
int swap = a[left];! int swap = a[left];! These loops
a[left] = a[right];! a[left] = a[right];! increase left and
a[right] = swap;! a[right] = swap;! decrease right
}! }! until they are on
}! }! swappable
a[0] = a[right];! a[0] = a[right];! elements or meet in
a[right] = fence;! a[right] = fence;! the middle
}! }!
25 26
public void partition(int[] a) {!
int fence = a[0];!
This swaps the two
QuickSort
int left = 1;!
elements if the two
int right = a.length-1;! •  QuickSort is a recursive sorting method defined as follows:
indices have not met
while (right >= left) {!
in the middle •  To sort an array,
while (left <= right && a[left] <= fence) !
•  Partition the array around some fence
left++;!
•  QuickSort the elements of array before the fence position
while (right >= left && a[right] >= fence)!
•  QuickSort the elements of array after the fence position
right--;!
if (right > left) {! •  This is a recursive definition because we have used QuickSort
int swap = a[left];! in the definition of QuickSort
a[left] = a[right];! •  We have only given the recursive part of the definition; what is
a[right] = swap;!
And when they do meet, the base case?
}!
the method finishes off by •  This is easy – if the array has 0 or 1 elements to be sorted, then we do not
}!
swapping the fence into need to do anything!
a[0] = a[right];! the correct position
a[right] = fence;!
}!
27 28
In-place sorting The actual quickSort code
private static int partition(int[] a, int start, int finish)! private static void quickSort(int[] a, int start, int finish)
{!! {!
! We just treat the elements if (finish-start > 0) {!
! !int fence = a[start];! a[start]..a[finish] as the array to int fence_position = partition(a,start,finish);!
Partition
! !int left = start+1;! be partitioned, and ignore the rest
! !int right = finish;! quickSort(a,start,fence_position-1);! Sort left
! quickSort(a,fence_position+1,finish);!
! !// omitted code is identical to before! }!
Sort right
! }!
! !a[start] = a[right];!
!!
! !a[right] = fence;! The method returns the correct
! position of the fence after it has
public static void quickSort(int[] a) {! The public method
! !return right;! been located quickSort(a,0,a.length-1);! should be as simple
}! }! to use as possible
29 30
The call quickSort(a) Comments on QuickSort
a! 62! 49! 24! 77! 98! 53! 90! 11! 57! 95! 82!87! 35! 92! 18! 71! •  Works well when the fence position ends up being roughly half
way through the array, as the two sub-problems are then about
First calls partition(a,0,15), which changes a to equal in size
•  Our choice of fence – position 0 – means that the worst case for
11! 49! 24! 18! 35! 53! 57! 62! 90! 95! 82!87! 98! 92! 77! 71! QuickSort is when the array is already ordered
•  In practice, it pays to avoid this case
and returns 7 as the fence position •  Pick the fence randomly
•  Randomly permute the array before sorting with QuickSort
quickSort(a,0,6) quickSort(a,8,15) •  Sample a small portion of the array, and choose the median as fence
sorts the left half sorts the right half
•  Average number of comparisons is
11! 49! 24! 18! 35! 53! 57! 62! 90! 95! 82!87! 98! 92! 77! 71! n log 2 n
Java library Summary
•  The Java library includes a number of optimized methods •  Recursion can be used to express some complex
for sorting. computations in an elegant way.
•  See, for example, •  However, there are overheads for using recursion that the
programmer needs to be aware of.
•  Arrays.sort and
•  Collections.sort(list)
•  The Quicksort algorithm is efficient, O(n log n), because it
breaks a large list into smaller ones and sorts those.
•  However, Quicksort is not always the best solution. For
example, it’s worst performance is when the list is already
sorted.
•  The Java library includes optimized methods for sorting.
See, for example, Arrays.sort and Collections.sort(list)
The*BlueJ*Window*
Class*diagram*
Introduc)on*to*BlueJ*
Workshop*1*
Object*workbench*
Compiling* Crea)ng*Our*First*Object*
Right*clicking*on*
There*are*6*classes:**
the*class*icon*
including*Picture,*
brings*up*a*menu*
Person,*Triangle*
* –*any*line*that*
The*icon*is*shaded*if* starts*with*new*
the*source*code*has* can*be*used*to*
not*been*compiled*
* construct*an*
To*compile*it,*press* object*of*that*class**
the*“Compile”*buFon* *
Objects*in*Java*are*
created*using*the**
keyword*new!
Crea)ng*Several*Objects* Inspec)ng*Objects*
We*have*created* Right*click*on*
three*objects:* an*object*on*
* the*object*
A*circle*object* bench*and*
and*two** choose*Inspect*
square*objects* to*inspect*the*
values*of*its*
aFributes:*its*
state*
Calling*Methods* Your*first*lab*session*
•  The*same*menu*also* 1.*Make*a*CITS1001*area*in*your*student*
shows*us*the*ac)ons* windows*account**
that*the*object*can*
perform*–*in*Java,*these*
2.*Go*to*Home*>*Labs*and*Projects**
are*called*methods.- 3.*Download*the*current*lab***
• *In*this*case*there*are* 4.*UNZIP*it*there*
many*methods*
available:* 5.*Double*click*on*the*blueJ*icon*(marked*
changeColor, package)*to*start*
changeSize,
moveUp etc.*
Your*first*lab*session*(cont)*
•  For*each*lab,*a*bluej*project*will*be*provided* Debugging(I(
•  All*instruc)ons*are*in*the*README*file*
•  Double*click*to*open*this*and*follow*the*
(
instruc)ons* Java(Syntax(
•  At#the#end#of#a#lab#I#recommend#you#make#a#
copy#of#your#project#directory#on#a#USB#drive#
or#to#a#dropbox#
1
Bugs(
The(term(bug(was(coined(by(computer(pioneer(( Debugging(
Grace(Hopper.(
•  Debugging(is(the(process(of(finding(and(repairing(bugs(in(
She(traced(an(error(in(the(MarkII(to(a(moth(trapped(in(a( a(program(
relay.((The(bug(was(carefully(removed(and(taped(to(a(daily(
•  It(is(a(very(important(skill(
log(book.(((
•  There(are(computer(tools(to(help(you:(compilers,(testers,(
Since(then,(whenever(a(( tracers,(style(checkers(
computer(has(a(problem(( •  In(this(lecture(we(look(at(debugging(Java(syntax(errors(
it(is(referred(to(as(a(bug.(
•  We(will(be(looking(“under(the(bonnet”(today.((You(don’t(
need(to(remember(the(details,(just(to(be(aware(of(what((
[Source: Wikipedia]
happens(when(you(press(the(“Compile”(buNon(in(BlueJ.(
© National Museum of American History
2 3
Java source code Machine code
Java(CompilaOon(in(BlueJ(
•  The(Java'compiler'
[ op | rs | rt | address/immediate] converts(Java(source(
code(to(Java(byte(code.(
32-bit instruction
•  When(it(finds(statements(
35 3 8 68 in(the(code(that(do(not(
decimal conform(to(Java(syntax(
100011 00011 01000 rules(it(generates(a(
00000 00001 000100 syntax'error.'
binary •  Your(code(can(not(be(
executed(on(a(computer(
if(it(has(any(syntax(
errors.'
4 5
What(is(going(on(?( Syntax(rules(of(Java(define(legal(code(
•  A(programming(language(is(a(formal'language:(that(is,(a(
set(of(finiteRlength(strings((=programs)((
•  Legal(programs(are(defined(by(a(set(of(rules(defined(by(a(
formal'grammar'
•  A(compiler(checks(whether(the(source(code(is(a(legal(Java( public int getBalance () { return balance; } ✔!
program,(and(if(it(is(then(generates(machineRexecutable( public int getBalance { return balance; } ✗!
code(for(that(program(
•  Source(code(that(does(not(match(the(Java(language(rules(
is(flagged(by(a(compiler'error'message'
More about this in CITS2211 Discrete Structures
6 7
Java(CompilaOon(Process(
•  Java(syntax(is(designed(to(be(user(friendly(and(human(readable(
–  Use(of(familiar(English(words((if,(else,(while),(block(structure,(maths(symbols(
•  In(order(to(run(Java(code(on(a(computer(it(is(converted(into((
Java'byte'code'that(runs(on(the(Java'Virtual'Machine'
•  In(turn,(this(representaOon(is(translated(into(machine(code(
Compiler(Errors(DemonstraOon(
instrucOons(that(fetch(and(write(values(from(memory(
Source: www.roseindia.net
More about this in CITS1002 Programming & Systems 8
We*have*to*deal*with*errors*
•  Early*errors*are*usually*syntax'errors.*
–  The*compiler*will*spot*these.*
Introduc)on*to*tes)ng*with*JUnit* •  Later*errors*are*usually*logic'errors.*
–  The*compiler*cannot*help*with*these.*
–  Also*known*as*bugs.*
Workshop*3* •  Some*logical*errors*have*no*immediately*obvious*
manifesta)on.*
–  Commercial*soEware*is*rarely*error*free.*
Objects First with Java - A
Practical Introduction using
BlueJ, © David J. Barnes,
Michael Kölling
Preven)on*vs*Detec)on*
(Developer*vs*Maintainer)*
Tes)ng*and*debugging*
•  We*can*lessen*the*likelihood*of*errors.* •  These are crucial skills.
–  Use*soEware*engineering*techniques,*like* •  Testing searches for the presence of
encapsula)on.*
errors.
•  We*can*improve*the*chances*of*detec)on.*
–  Use*soEware*engineering*prac)ces,*like*
•  Debugging searches for the source of
modulariza)on*and*documenta)on.* errors.
•  We*can*develop*detec)on*skills.* –  The manifestation of an error may well occur
some distance from its source.
Objects First with Java - A
Practical Introduction using Objects First with Java - A
BlueJ, © David J. Barnes, Practical Introduction using
Michael Kölling BlueJ, © David J. Barnes,
Michael Kölling
JUnit*
•  JUnit*is*a*Java*test*framework*
•  Test cases*are*methods*that*contain*tests*
•  Test classes*contain*test*methods*
•  Assertions*are*used*to*assert*expected*
method*results*
•  Fixtures*are*used*to*support*mul)ple*tests*
JUNIT&
Objects First with Java - A
Practical Introduction using
BlueJ, © David J. Barnes,
Michael Kölling
JUnit Automated Testing
•  de facto standard unit testing framework written by
Erich Gamma and Kent Beck •  Tests must run automatically without human
•  bundled in most IDEs
participation (beyond launching the test suite,
and maybe not even that)
•  www.junit.org
•  Results should be pass/fail
•  useful to have one complete test suite the
programmers can run with a pass fail result •  Test failures need to be blindingly obvious
•  automatic quality assurance: when the code changes, •  Tests must be reproducible and consistent
test cases are rerun to check that nothing breaks
7 8
What’s in a test case ? Coding a test case in JUnit4
@Test!
public void testGetAreaNormal() !
{!
Unit test cases have the following form: //1. describe input!
Rectangle r1 = new Rectangle(3,4);!
!
//2. describe expected output(s)!
1. describe the method s inputs int expected = 12;!
!
2. describe the expected outputs //3. call the method!
int actual = r1.getArea();!
3. call the method and observe actual output !
//4. compare actual output with expected (AEEA)!
assertEquals(expected, actual);!
4. compare expected with actual and report
}!
9 10
Before and After every test case How a test suite is executed
public void setUp() throws Exception {! 1.  setUp*method*is*executed*
! 2.  the*first*test*method*in*the*class*is*executed*
!/* TODO create objects/common variables for tests!
* setUp is called before EACH test case is run! 3.  tearDown*method*is*executed*
! */! 4.  setUp*method*is*executed*
!}!
! 5.  the*second*test*method*in*the*class*is*executed*
!public void tearDown() throws Exception {! 6.  tearDown*method*is*executed*
!
/* TODO reset or release objects, eg. normal=null; ! *
* to garbage collect old test object! Con)nue*un)l*all*test*cases*are*executed.*
* tearDown is called after EACH test case is run!
*
* NOT USUALLY USED FOR CITS1001 tests!
*/! IMPORTANT&each*test*case*is&independent'of*previous*tests*
!}!
11 12
Examples When does expected = actual ?
To*compare*any*variables*of*the*8*Java*
primi)ve*types*(boolean, byte, short, int, long,
char, float, double)
See labs and projects
assertEquals(expected, actual)
*
First*argument*(op)onal)*is*a*string*that*is*
printed*if*the*asser)on*fails*
*
assertEquals(message, expected, actual)!
13 14
StraightTforward*comparisons*for*basic*
Floating point arithmetic
types*
As*always*with*floa)ng*point*arithme)c*(double*
public static void !
!
or*float),*you*want*to*avoid*direct*equality*
assertEquals(int expected, int actual) ! comparisons.**
! **
assertEquals(boolean expected, boolean actual)
 public static void assertEquals(!
! ! double expected, double actual, !
assertEquals(byte expected, byte actual)
 double tolerance)!
!
assertEquals(char expected, char actual)
 For*example,**
!
assertEquals(short expected, short actual)
 *assertEquals(0.552, 0.510, 0.1) is*true*but'
!
assertEquals(long expected, long actual)! *assertEquals(0.552, 0.510, 0.01)**is*false*
since*the*values*are*equivalent*within*a*
tolerance*of*±*0.1*but*not*to*2*decimal*places.*
15 16
How to Test Objects Testing Objects Problem
JUnit responds with
What is the expected result of this test?
junit.framework.Asser)onFailedError:*resize*OK*
expected:<Rectangle@913fe2>*but*
public void testObjEquality() {! was:<Rectangle@1f934ad>*
!Rectangle r1 = new Rectangle(2,4);!
!Rectangle r2 = new Rectangle(2,4);!
!assertEquals(r1,r2);! Problem: we have tested for equivalence of the
!}! references to the 2 rectangle objects, not the
contents of those rectangle objects
17 18
Solution Testing methods that throw exceptions
public void testGridEmpty() {!
Write a local equivalence tester for the class you are try {!
testing new Grid(new int[0][0]);!
private void testRectangleEquality(Rectangle r1, Rectangle r2) {! fail("IllegalArgumentException should be thrown for
! [0][0] grid");!
// Test height and width!
! } !
assertEquals(“Not same height”, r1.getHeight(), r2.getHeight());!
assertEquals(“Not same width”,r1.getWidth(),r2.getWidth());! catch (IllegalArgumentException iae) {!
}!
//test passed: !
//correct exception thrown !
Aside: This test method terminates after the first
failure, so if both tests fail only the first is reported }!
}!
19 20
More assertions
•  See
http://junit.sourceforge.net/javadoc/org/junit/
Assert.html
•  For example,
–  assertArrayEquals
–  assertNull
–  assertNotSame
–  assertTrue
CHOOSING&TEST&CASES&
–  assertFalse
21
Choosing Test Cases Tes)ng*fundamentals*
•  Typical cases •  Understand what the unit should do – its
–  Sanity check that method code works as expected, but try to contract.
choose tricky cases anyway!
–  You will be looking for violations.
•  Special cases and Boundary cases –  Use positive tests and negative tests.
–  Most errors occur for boundary values, eg empty or full •  Test boundaries.
array, -1,0,1 etc. –  Zero, One, Full.
•  Search an empty collection.
•  Exceptional cases •  Add to a full collection.
–  Illegal input, divide by 0, un-initialized parameters
Objects First with Java - A
Practical Introduction using
BlueJ, © David J. Barnes,
23 Michael Kölling
Unit*tes)ng*
Plan your test cases using tables
•  Each unit of an application may be tested.
–  Method, class, module (package in Java). Inputs& Expected&Output&
•  Can (should) be done during development. TYPICAL*
height=3,*width=4* height=6,*width=2*
–  Finding and fixing early lowers development costs
hscale=2.0,*wscale=0.5*
(e.g. programmer time).
–  A test suite is built up. BOUNDARY&
height=3,*width=4*
height=3,*width=4* *
hscale=1.0,*wscale=1.0*
EXCEPTIONAL&
height=3,*width=4* height=1?,*width=0?*
Objects First with Java - A hscale=0.5,*wscale=0.0*
Practical Introduction using
BlueJ, © David J. Barnes,
Michael Kölling 26
Verbal*walkthroughs* Also, ask questions
•  Explain*to*someone*else*what*the*code*is* •  Useful when testing someone else’s class eg. a
doing.* library class
–  They*might*spot*the*error.* •  Ask: What happens if you do XXX ?
–  The*process*of*explaining*might*help*you*to*spot*it*
–  Is an exception thrown? If so, which one?
for*yourself.* –  Is null treated as zero?
•  GroupTbased*processes*exist*for*conduc)ng* –  Is null returned?
–  Something else?
formal*walkthroughs*or*inspec3ons.*
•  Write a test that determines the answer to your
question(s)
Objects First with Java - A
Practical Introduction using
BlueJ, © David J. Barnes,
Michael Kölling
28
More ways to test your code Pragmatic Unit Testing
Andrew Hunt and David Thomas (available online)
Acceptance Tests The Right-BICEP method (chapter 4)
•  Use a main method to execute a sequence of steps
(method calls) corresponding to client’s use cases •  Right - Are the results right?
•  Good for visual testing of methods with graphical displays •  B - Are all the boundary conditions CORRECT?
or user interfaces (terminal of graphic)
•  I - Can you check inverse relationships?
•  C - Can you cross-check results using other means?
Coverage Testing •  E - Can you force error conditions to happen?
•  How much of your code is executed by your test cases?
•  For example, try to execute all branches or all paths
•  P - Are performance characteristics within bounds?
through the code
29 30
Print*statements* Choosing a test strategy
•  The*most*popular*technique.* •  Be*aware*of*the*available*strategies.*
•  No*special*tools*required.* •  Choose*strategies*appropriate*to*the*point*of*
•  All*programming*languages*support*them.* development.*
•  Only*effec)ve*if*the*right*methods*are*documented.* •  Automate*whenever*possible.*
•  Output*may*be*voluminous!* –  Reduces*tedium.*
•  Turning*off*and*on*requires*forethought.*
–  Reduces*human*error.*
–  Makes*(re)tes)ng*more*likely.*
Objects First with Java - A Objects First with Java - A
Practical Introduction using Practical Introduction using
BlueJ, © David J. Barnes, BlueJ, © David J. Barnes,
Michael Kölling Michael Kölling
Review*
•  Errors are a fact of life in programs.
•  Good software development techniques can
JAVADOC
• 
reduce their occurrence.
Testing and debugging skills are essential.
DOCUMENTATION
•  Make testing a habit. CITS1001
•  Automate testing where possible.
•  Continually repeat tests.
•  Practice a range of debugging skills.
Objects First with Java - A
Practical Introduction using
BlueJ, © David J. Barnes,
Michael Kölling
2 3
Documentation Javadoc
•  Documentation is a contract between the •  Comments occurring between the special tags /** and */ are
treated as special javadoc comments
programmers and the users of a class
•  These can be automatically parsed (processed) to generate
•  Documentation should be developed at the same time, HTML documentation that can be read by a Web browser
and in the same place as the source code •  The resulting documentation is used to precisely define the
behaviour of the class and its methods
•  Java provides facilities to help with this, by allowing
•  The Java API itself is generated from source code comments by
source code comments to be automatically turned into javadoc
documentation using the javadoc feature •  But beware: only test cases can check whether the code actually
does what the documentation promises
4 5
Writing Javadoc comments /**
* Create a new bank account
* @param balance integer opening balance in cents
•  Place comments directly before a class, field (i.e. * @param name String identifying the account and owner
*/
variable), constructor or method declaration public BankAcc(String name, int balance) {
•  Critically important for public classes, fields, this.balance = balance;
this.name = name;
constructors and methods, but may also be used for }
private ones if desired
•  Comments can be written in HTML (the code used for
Web pages), and enhanced with special javadoc tags
such as BankAcc(String name, int balance)
Create a new bank account
@author, @version, Parameters:
@param, @returns, @throws balance integer opening balance in cents
name String identifying the account and owner
!
6
/**
* Creates and displays a SimpleCanvas of the specified size
* with a white background. The client specifies whether repainting
* after a drawing command should be manual or automatic.
*
* @param title title for the window
* @param width the desired width of the SimpleCanvas
* @param height the desired height of the SimpleCanvas
* @param autoRepaint true for automatic repainting
*/
public SimpleCanvas(String title, int width, int height, boolean
autoRepaint) { //code here }
SimpleCanvas.SimpleCanvas(String title, int width, int height, boolean
autoRepaint)
Creates and displays a SimpleCanvas of the specified size with a white
background. The client specifies whether repainting after a drawing command
should be manual or automatic.
Parameters:
title title for the window
width the desired width of the SimpleCanvas
height the desired height of the SimpleCanvas
autoRepaint true for automatic repainting
!
CITS1001 Object-Oriented Programming
and Software Engineering
School of Computer Science & Software Engineering
The University of Western Australia

CITS1001 IN-CLASS QUIZ QUESTIONS

Semester 1, 2014
CITS1001
1. What is abstraction?

a. When things are confusing and vague rather than simple and un-
derstandable.
b. The opposite of addition, as seen in mathematics.
c. A Java keyword that optimizes programs that do not use classes or
objects.
d. The ability to focus on a problem at a high level without worrying
about the minor details.
e. When alcohol was illegal in the United States in the early 20th
century.

2. How do objects provide abstraction?

a. Objects provide abstraction through the .provideAbstraction() method.


b. Public fields provide abstraction because they let the client directly
view an object’s data.
c. By giving us more powerful pieces of data that have sophisticated
behavior without having to manage and manipulate the data di-
rectly.
d. When one object converts into another type of object, it becomes
abstract.
e. Objects provide abstraction by declaring useful data inside them.

2
3. What is the di↵erence between the file MyProgram.java and the file
MyProgram.class?

a. A .java file is a much larger binary file and a .class file is a smaller
compressed version.
b. The .class file is for object-oriented programming and the .java file
is for procedural programming.
c. MyProgram.java is a source code file typed by the programmer,
and MyProgram.class is a compiled executable class file that is
run by the computer.
d. A .java file contains code written in the Java language, and a .class
file contains code written in the C++ language.
e. The programmer writes the .class file first, and the .java file is
generated automatically later.

4. Which of the following statements about constructors are true? Check


all that apply. Justify each choice.

a. A constructor is declared without a return type.


b. A constructor is the code that is called when you use the ’new’
keyword.
c. A constructor can be used instead of fields to represent the data
inside a class.
d. A class can have many methods but only one constructor.
e. A constructor wastes memory in the computer so it should be used
sparingly.
f. A constructor is a special method that creates an object and ini-
tializes its state.
g. Constructors are considered bad programming style and should be
avoided.

3
5. The declaration private Circle sun;

a. creates a field variable sun referring to a newly created Circle


object, which by default has the colour yellow.
b. creates a field variable sun with initial value null.
c. creates a field variable sun that is drawn in the middle of the canvas.
d. creates a field variable sun with an unspecified initial value.
e. causes a syntax error, as it is not permitted to declare a variable of
reference type without creating the associated object.

6. Which one of the following lines of Java code may cause a compilation
error?

a. boolean f = false;
b. int x = -1;
c. double y = -1;
d. int[] a = {1,1,2,3,5};
e. Book b = new Book;

7. Suppose a method in a BankAccount class is defined as:


public double computeInterest(int rate)
And suppose the client code has declared a BankAccount variable
named acct.
Which of the following would be a valid call to the above method?
(Give a brief reason to justify your choices)

a. double result = computeInterest(acct, 42);


b. int result = BankAccount.computeInterest(42);
c. new BankAccount(42).computeInterest();
d. double result = acct.computeInterest(42);
e. acct.computeInterest(42.0, 15);

4
8. Given the following variable declarations:

int x = 27;
int y = -1;
int z = 32;
boolean b = false;

What is the value of each of the following boolean expressions?

(a) !b
(b) b || true
(c) (x > y) && (y > z)
(d) (x == y) || (x <= z)
(e) !(x % 2 == 0)
(f) (x % 2 != 0) && b
(g) b && !b
(h) b || !b
(i) (x < y) == b
(j) !(x / 2 == 13) || b || (z * 3 == 96)
(k) (z < x) == false
(l) !((x > 0) && (y < 0))

5
9. The following method is intended to return true if the given non-
negative number is a multiple of 3 or 5, but not both. However, the
method has a logical error.

public boolean old35(int n) {


return ((n % 3 != 0) || (n % 5 != 0));
}

Which of the following JUnit assertion tests will detect the error?

a. assertEquals(true, old35(3));
b. assertEquals(false, old35(15));
c. assertEquals(false, old35(8));
d. assertEquals(true, old35(20));
e. assertEquals(false, old35(45));

10. We have two monkeys, a and b, and the parameter variables aSmile
and bSmile indicate if each is smiling. We are in trouble if they are
both smiling or if neither of them is smiling. Which of the following
statements returns true if and only if we are in trouble.

a. return ((aSmile == bSmile) || (aSmile != bSmile));


b. return ((aSmile && bSmile) || (!aSmile || !bSmile));
c. return (aSmile || bSmile);
d. return (aSmile && bSmile);
e. return (aSmile == bSmile);

6
11. What are the values in each of the variables after the following code
has been executed:

int x = 7;
int y = 5;
int z = 0;
z = x;
x = y;
y = z;

a. x is 5, y is 0, z is 7
b. x is 5, y is 5, z is 0
c. x is 5, y is 7, z is 7
d. x is 7, y is 5, z is 0
e. None of the above.

7
12. Consider the following Java method, which is written incorrectly. Un-
der what cases will the method print the correct answer, and when will
it print an incorrect answer? Rewrite the method so that it returns
the correct answer in all cases. (For an extra challenge, can you think
of a way to write the code correctly without any if/else statements?)

// This method should return how many of its three


// arguments are odd numbers.
public static void printNumOdd(int n1, int n2, int n3) {
int count = 0;
if (n1 % 2 != 0) {
count++;
} else if (n2 % 2 != 0) {
count++;
} else if (n3 % 2 != 0) {
count++;
}
System.out.println(count + " of the 3 numbers are odd.");
}

8
13. The following program contains 7 errors. Correct the errors and
rewrite a working version of the program. In the corrected version
of the program a call to test(7,42) should produce the terminal out-
put: a is the smallest!

public class Oops4 {


public void test(int a, int b) {
minimum(a, b);
if {smaller = a} {
System.out.println("a is the smallest!");
}
}

public int minimum(int a, int b) {


if (a < b) {
int smaller = a;
} else (a => b) {
int smaller = b;
}
return int smaller;
}
}

9
14. The following method attempts to return the median (middle) of three
integer values, but it contains logic errors. Find an example of cases
when the method returns an incorrect result? How can the code be
fixed? Determine what is wrong with the code, and write a corrected
version that works properly.

public int medianOf3(int n1, int n2, int n3) {


if (n1 <= n2) {
if (n2 < n3){
return n2;
} else {
return n3;
}
} else {
if (n1 <= n3) {
return n1;
} else {
return n3;
}
}
}

10
15. Which of the following is the correct syntax to construct an ArrayList
to store integers?

a. ArrayList list = new ArrayList();


b. ArrayList list<integer> = new ArrayList<integer>();
c. ArrayList<Integer> list = new ArrayList();
d. ArrayList<Integer> list = new ArrayList<Integer>();
e. ArrayList[int] list = new ArrayList[int]();

16. The following method is intended to count the number of marks that
are in the range low to high (inclusive). The method getMark returns
the mark from its StudentMark object.
The given method it is missing one line of code. What code should
replace the comment line (//missing line of code here) so that
the method returns the correct result ?

public int countNumInRange(int low, int high)


{
int count=0;
for (StudentMark sm : marks) {
//missing line of code here
{
count++;
}
}
return count;
}

a. if (low < sm.getMark())


b. if (high > sm.getMark())
c. if ((low <= sm.getMark()) || (sm.getMark() <= high))
d. if ((low <= sm.getMark()) && (sm.getMark() <= high))
e. if (low < high)

11
17. Consider the following class, where each object represents an employee
of a certain organisation. The instance variable supervisor represents
the supervisor of this employee (and is null for the CEO of the organ-
isation), while staff represents the sta↵ who directly report to this
employee. If this employee is an entry-level sta↵ member, then he/she
does not supervise anyone and has the value null for the variable
staff.

public class Employee {


private Employee supervisor;
private ArrayList<Employee> staff;

// irrelevant code omitted

public int m() {


if (staff == null) {
return 1;
} else {
int total = 0;
for (Employee ei : staff) {
total = total + ei.m();
}
return (total+1);
}
}
}

If Employee fred represents a sta↵ member called Fred, then what


does fred.m() calculate?

a. The number of levels above entry-level that Fred has reached.


b. The number of sta↵ subordinate to Fred (including Fred).
c. The number of sta↵ who report directly to Fred.
d. The number of entry-level sta↵ subordinate to Fred.
e. The number of sta↵ subordinate to Fred (excluding Fred).

12
18. Consider the task of writing a method named countFactors that ac-
cepts an integer (assumed to be positive) as its parameter and returns
a count of its positive factors. For example, the six factors of 12 are
1, 2, 3, 4, 6, and 12, so the call countFactors(12) should return 6.
The following is an attempt at solving the problem, but it is incorrect.
Determine what is wrong with the code, and write a corrected version
that works properly. Include brief comments to explain your changes.

public static int countFactors(int n) {


for (int i = 1; i <= n; i++) {
if (n % i == 0) { // a factor
return i;
}
}
}

13
19. What value does mystery(100) return?

public int mystery(int k){


while ( k>10 ) {
k = k/2;
}
return k;
}

a. 2
b. 6
c. 100
d. 50
e. 5

20. What values would the variables thecount and wordcount hold (re-
spectively) after executing the following Java statements.

HashMap< String, Integer > dictionary;


dictionary = new HashMap< String, Integer>();
dictionary.put("the", 100);
dictionary.put("of", 70);
dictionary.put("and", 70);
dictionary.put("the", 50);
int thecount = dictionary.get("the");
int wordcount = dictionary.size();

a. 290 and 4
b. 150 and 3
c. 100 and 4
d. 50 and 3
e. No values because this code would cause a run-time exception to
be thrown

14
21. If a method uses checked exceptions to deal with unexpected (but re-
coverable) run-time events, how is that fact communicated to potential
users of that method?

a. In its name
b. In its signature
c. In its arguments
d. In its body
e. In its return type

22. What happens when the following code is run in a directory that does
not contain file called missingfile.txt ? Assume that the class has
a field private List<String> lines;

Path fullname = Paths.get("missingfile.txt");


try {
lines = Files.readAllLines(fullname, Charset.forName("UTF-8"));
} catch (Exception e) {
System.out.println("File not found");
}

a. lines contains a List object with no elements


b. lines contains null
c. A java.io.IOException is thrown
d. A java.io.FileNotFoundException is thrown
e. None of the above

15
23. What is the value of array element a[99] after executing the following
statements?

int[] a = new int[100];


a[0] = 1;
for (int i = 1; i < a.length; i++) {
a[i] = 1 - a[i-1];
}

a. -2
b. -1
c. 0
d. 1
e. 2

24. What happens when the following code is run in a directory that does
not contain file called missingfile.txt ? Assume that the class has
a field private List<String> lines;

Path fullname = Paths.get("missingfile.txt");


try {
lines = Files.readAllLines(fullname, Charset.forName("UTF-8"));
} catch (Exception e) {
System.out.println("File not found");
}

a. lines contains a List object with no elements


b. lines contains null
c. A java.io.IOException is thrown
d. A java.io.FileNotFoundException is thrown
e. None of the above

16
25. Indicate what terminal output is produced when mystery2(42); is
called where the method is defined as follows.

public void mystery2(int n) {


if (n > 100) {
System.out.print(n);
} else {
mystery2(2 * n);
System.out.print(", " + n);
}
}

17
CITS1001 Code Samples
Rachel Cardell-Oliver
Semester 1 2014

Contents
1 Java Class File: Student.java 2

2 Code with Syntax Errors: TicketMachine.java 4

3 Corrected Code: TicketMachine.java 6

4 Code with Logic Errors: Calculator.java 9

5 JUnit Test Code: CalculatorTest.java 11

6 Collections Example: Membership.java 13

7 Collections Example: Club.java 16

8 Collections Example: ClubDemo.java 18

9 Object Interation: NumberDisplay.java 20

10 Object Interation: ClockDisplay.java 21

11 Example of HashMap use from the Zuul game 24

12 Game of Life: Life.java 26

13 Game of Life: LifeViewer.java 30

14 Sorting Algorithms: Sorter.java 34

1
1 Java Class File: Student.java
1 /⇤ ⇤
2 ⇤ Naive model o f a s t u d e n t w i t h a t o t a l p e r c e n t a g e mark
t h a t i s i n i t i a l l y 0 and can have new marks added t o
the t o t a l
3 ⇤ TODO This v e r s i o n has no v a l i d i t y c h e c k i n g f o r mark
values
4 ⇤
5 ⇤ @author Rachel C a r d e l l O l i v e r
6 ⇤ @ v er s i on January 2013
7 ⇤/
8 public c l a s s Student
9 {
10 // C o n s t a n t s
11 public f i n a l s t a t i c int MAX MARK = 1 0 0 ;
12
13 // I n s t a n c e v a r i a b l e s ( aka f i e l d s )
14 // s t u d e n t ’ s f u l l name
15 private S t r i n g name ;
16 // s t u d e n t ’ s o v e r a l l mark as a p e r c e n t a g e rounded t o
nearest integer
17 private int t o t al M a r k ;
18
19 /⇤ ⇤
20 ⇤ Constructor for o b j e c t s of c l a s s Student
21 ⇤/
22 public Student ( S t r i n g givenName )
23 {
24 // i n i t i a l i s e t h e i n s t a n c e v a r i a b l e s
25 name = givenName ;
26 totalMark = 0 ;
27 }
28
29 /⇤ ⇤
30 ⇤ G e t t e r method t o r e t u r n s t u d e n t mark
31 ⇤ @return t h e c u r r e n t mark f o r t h i s s t u d e n t
32 ⇤/
33 public int getTotalMark ( )
34 {
35 return t o t a l M a r k ;
36 }
37
38 /⇤ ⇤
39 ⇤ Method t o add newmark t o t h e c u r r e n t t o t a l mark .

2
40 ⇤ TODO no c h e c k s h e r e y e t f o r v a l i d marks
41 ⇤ @param newMark s c o r e t o be added t o t o t a l M a r k
42 ⇤/
43 public void addMark ( int newMark )
44 {
45 t o t a l M a r k = t o t a l M a r k + newMark ;
46 }
47
48 /⇤ ⇤
49 ⇤ Method t o p r i n t s t u d e n t d e t a i l s
50 ⇤/
51 public void p r i n t S t u d e n t D e t a i l s ( )
52 {
53 System . out . p r i n t ( ” Student name : ” + name + ” has
s c o r e d ” + t o t a l M a r k + ”%” ) ;
54 }
55 }

3
2 Code with Syntax Errors: TicketMachine.java
1 /⇤ ⇤
2 ⇤ TicketMachine models a n a i v e t i c k e t machine t h a t
issues flat fare tickets .
3 ⇤ The p r i c e o f a t i c k e t i s s p e c i f i e d v i a t h e c o n s t r u c t o r
4 ⇤ I t i s a n a i v e machine i n t h e s e n s e t h a t i t t r u s t s i t s
u s e r s t o i n s e r t enough money b e f o r e t r y i n g t o p r i n t a
ticket .
5 ⇤ I t a l s o assumes t h a t u s e r s e n t e r s e n s i b l e amounts .
6 ⇤
7 ⇤ @author David J . Barnes and Mi chael K o l l i n g
8 ⇤ With s y n t a x e r r o r s by Rachel C a r d e l l O l i v e r
9 ⇤ @ v er s i on 2 0 0 8 . 0 3 . 3 0
10 ⇤/
11 public c l a s s TicketMachine
12 {
13 // The p r i c e o f a t i c k e t from t h i s machine .
14 private int p r i c e ;
15 // The amount o f money e n t e r e d by a customer so f a r .
16 private int b a l a n c e ;
17 // The t o t a l amount o f money c o l l e c t e d by t h i s
machine .
18 private int t o t a l
19
20 /⇤ ⇤
21 ⇤ C r eat e a machine t h a t i s s u e s t i c k e t s o f t h e g i v e n
p r i c e . Note t h a t t h e p r i c e must be g r e a t e r than
z er o , and t h e r e a r e no c h e c k s t o e n s u r e t h i s .
22 ⇤/
23 public TicketMachine ( int t i c k e t C o s t )
24 {
25 price = ticketcost ;
26 balance = 0;
27 total = 0;
28 }
29
30 /⇤ ⇤
31 ⇤ Return t h e p r i c e o f a t i c k e t .
32 ⇤/
33 public int g e t P r i c e ( )
34 {
35 return p r i c e ;
36 }
37

4
38 /⇤ ⇤
39 ⇤ Return t h e amount o f money a l r e a d y i n s e r t e d f o r
the next t i c k e t .
40 ⇤/
41 public int g e t B a l a n c e ( )
42 {
43 return b a l a n c e ;
44 }
45
46 /⇤ ⇤
47 ⇤ R e c e i v e an amount o f money i n c e n t s from a
customer .
48 ⇤/
49 public void i n s e r t M on e y ( int amount )
50 {
51 b a l a n c e = b a l a n c e + amount ;
52 }
53
54 public int c a l c u l a t e C h a n g e ( ) {
55 int change = b a l a n c e p r i c e ;
56
57 /⇤ ⇤
58 ⇤ P r i n t a t i c k e t . Update t h e t o t a l c o l l e c t e d and
reduce the balance to zero .
59 ⇤/
60 public void p r i n t T i c k e t ( )
61 {
62 i f ( C a l c u l a t e Ch a n g e ) {
63 // S i m u l a t e t h e p r i n t i n g o f a t i c k e t .
64 System . out . p r i n t l n ( ”##################” ) ;
65 System . out . p r i n t l n ( ”# The BlueJ Li ne ” ) ;
66 System . out . p r i n t l n ( ”# T i c k e t ” ) ;
67 System . out . p r i n t l n ( ”# ” + p r i c e + ” c e n t s
. ”) ;
68 System . out . p r i n t l n ( ”##################” ) ;
69 System . out . p r i n t l n ( ) ;
70
71 // Update t h e t o t a l w i t h t h e b a l a n c e .
72 t o t a l = t o t a l + balance ;
73 // C l e a r t h e b a l a n c e .
74 balance = 0;
75 } else {
76 System . out . p r i n t l n ( ” Cannot p r i n t t i c k e t
b e c a u s e p r i c e <=0” ) ;
77 }
78 }

5
3 Corrected Code: TicketMachine.java
1 /⇤ ⇤
2 ⇤ TicketMachine models a n a i v e t i c k e t machine t h a t
issues flat fare tickets .
3 ⇤ The p r i c e o f a t i c k e t i s s p e c i f i e d v i a t h e c o n s t r u c t o r
4 ⇤ I t i s a n a i v e machine i n t h e s e n s e t h a t i t t r u s t s i t s
u s e r s t o i n s e r t enough money b e f o r e t r y i n g t o p r i n t a
t i c k e t . I t a l s o assumes t h a t u s e r s e n t e r s e n s i b l e
amounts .
5 ⇤
6 ⇤ @author David J . Barnes and Mi chael K o l l i n g
7 ⇤ With s y n t a x e r r o r s by Rachel C a r d e l l O l i v e r
8 ⇤ @ v er s i on 2 0 0 8 . 0 3 . 3 0
9 ⇤/
10 public c l a s s TicketMachine
11 {
12 // The p r i c e o f a t i c k e t from t h i s machine .
13 private int p r i c e ;
14 // The amount o f money e n t e r e d by a customer so f a r .
15 private int b a l a n c e ;
16 // The t o t a l amount o f money c o l l e c t e d by t h i s
machine .
17 private int t o t a l ;
18
19 /⇤ ⇤
20 ⇤ C r eat e a machine t h a t i s s u e s t i c k e t s o f t h e g i v e n
price .
21 ⇤ Note t h a t t h e p r i c e must be g r e a t e r than z e r o , and
t h e r e a r e no c h e c k s t o e n s u r e t h i s .
22 ⇤/
23 public TicketMachine ( int t i c k e t C o s t )
24 {
25 price = ticketCost ;
26 balance = 0;
27 total = 0;
28 }
29
30 /⇤ ⇤
31 ⇤ Return t h e p r i c e o f a t i c k e t .
32 ⇤/
33 public int g e t P r i c e ( )
34 {
35 return p r i c e ;
36 }

6
37
38 /⇤ ⇤
39 ⇤ Return t h e amount o f money a l r e a d y i n s e r t e d f o r
the next t i c k e t .
40 ⇤/
41 public int g e t B a l a n c e ( )
42 {
43 return b a l a n c e ;
44 }
45
46 /⇤ ⇤
47 ⇤ R e c e i v e an amount o f money i n c e n t s from a
customer .
48 ⇤/
49 public void i n s e r t M on e y ( int amount )
50 {
51 b a l a n c e = b a l a n c e + amount ;
52 }
53
54 public int c a l c u l a t e C h a n g e ( ) {
55 return ( b a l a n c e p r i c e ) ;
56 }
57
58 /⇤ ⇤
59 ⇤ Print a t i c k e t .
60 ⇤ Update t h e t o t a l c o l l e c t e d and r e d u c e t h e b a l a n c e
to zero .
61 ⇤/
62 public void p r i n t T i c k e t ( )
63 {
64 i f ( c a l c u l a t e C h a n g e ( ) >=0) {
65 // S i m u l a t e t h e p r i n t i n g o f a t i c k e t .
66 System . out . p r i n t l n ( ”##################” ) ;
67 System . out . p r i n t l n ( ”# The BlueJ Li ne ” ) ;
68 System . out . p r i n t l n ( ”# T i c k e t ” ) ;
69 System . out . p r i n t l n ( ”# ” + p r i c e + ” c e n t s . ” ) ;
70 System . out . p r i n t l n ( ”##################” ) ;
71 System . out . p r i n t l n ( ) ;
72
73 // Update t h e t o t a l c o l l e c t e d w i t h t h e
balance .
74 t o t a l = t o t a l + balance ;
75 // C l e a r t h e b a l a n c e .
76 balance = 0;
77 } else {
78 System . out . p r i n t l n ( ” Cannot p r i n t t i c k e t

7
b e c a u s e b a l a n c e t o o low ” ) ;
79 }
80 }
81 }

8
4 Code with Logic Errors: Calculator.java
1
2 /⇤ ⇤
3 ⇤ A simple c a l c u l a t o r
4 ⇤
5 ⇤ @author Rachel C a r d e l l O l i v e r
6 ⇤ @ v er s i on February 2013
7 ⇤/
8 public c l a s s C a l c u l a t o r
9 {
10
11 // s e t r e s u l t t o INITIAL VALUE when t h e c a l c u l a t o r i s
c r e a t e d or c l e a r e d
12 s t a t i c f i n a l int INITIAL VALUE = 0 ;
13 // s e t r e s u l t t o ERROR VALUE when an e r r o r o c c u r s
14 //TODO c o n s i d e r o t h e r e r r o r h a n d l i n g a p p r o a c h e s such
as e x c e p t i o n s
15 s t a t i c f i n a l int ERROR VALUE = 9 9 9 9 9 9 9 9 ;
16
17 private int r e s u l t ;
18
19 /⇤ ⇤
20 ⇤ c o n s t r u c t o r i n i t i a l i s e s r e s u l t t o INITIAL VALUE
21 ⇤/
22 public C a l c u l a t o r ( ) {
23 r e s u l t = INITIAL VALUE ;
24 }
25
26 /⇤ ⇤
27 ⇤ g e t t e r method f o r r e s u l t f i e l d
28 ⇤ @return t h e c u r r e n t r e s u l t v a l u e
29 ⇤/
30 public int g e t R e s u l t ( ) {
31 return r e s u l t ;
32 }
33
34 /⇤ ⇤
35 ⇤ add v a l u e t o c u r r e n t r e s u l t
36 ⇤ @param x i n t e g e r t o add
37 ⇤/
38 public void add ( int x ) {
39 result = result ⇤ x;
40 }
41

9
42 /⇤ ⇤
43 ⇤ s u b t r a c t v a l u e from c u r r e n t r e s u l t
44 ⇤ @param x i n t e g e r t o s u b t r a c t
45 ⇤/
46 public void s u b t r a c t ( int x ) {
47 result = result x;
48 }
49
50 /⇤ ⇤
51 ⇤ m u l t i p l y c u r r e n t r e s u l t by x
52 ⇤ @param x i n t e g e r m u l t i p l i e r
53 ⇤/
54 public void m u l t i p l y ( int x ) {
55 result = result ⇤ x;
56 }
57
58 /⇤ ⇤
59 ⇤ d i v i d e c u r r e n t r e s u l t by g i v e n d i v i s o r
60 ⇤ @param x i n t e g e r d i v i s o r
61 ⇤ c h e c k f o r d i v i d e by 0 and s e t r e s u l t t o
ERROR VALUE
62 ⇤/
63 public void d i v i d e ( int x ) {
64 i f ( x==0) {
65 r e s u l t = r e s u l t /x ;
66 } else {
67 r e s u l t = ERROR VALUE;
68 }
69 }
70
71 /⇤ ⇤
72 ⇤ c l e a r the r e s u l t accumulator
73 ⇤/
74 public void c l e a r ( ) {
75 //TODO add code h e r e
76 }
77 }

10
5 JUnit Test Code: CalculatorTest.java
1 import o r g . j u n i t . ⇤ ;
2 import s t a t i c o r g . j u n i t . A s s e r t . ⇤ ;
3
4 /⇤ ⇤
5 ⇤ The t e s t c l a s s c a l c u l a t o r T e s t .
6 ⇤
7 ⇤ @author Rachel C a r d e l l O l i v e r
8 ⇤ @ v er s i on March 2013 ( r e v i s e d from January 2013)
9 ⇤/
10 public c l a s s C a l c u l a t o r T e s t
11 {
12 private C a l c u l a t o r mycalc ;
13
14 /⇤ ⇤
15 ⇤ S e t s up t h e t e s t f i x t u r e .
16 ⇤
17 ⇤ C a l l e d b e f o r e e v e r y t e s t c a s e method .
18 ⇤/
19 @Before
20 public void setUp ( )
21 {
22 mycalc=new C a l c u l a t o r ( ) ;
23 }
24
25 /⇤ ⇤
26 ⇤ check constructor i n i t i a l i s a t i o n
27 ⇤/
28 @Test public void t e s t C o n s t r u c t o r ( ) {
29 a s s e r t E q u a l s ( mycalc . INITIAL VALUE , mycalc .
getResult () ) ;
30 }
31
32 /⇤ ⇤
33 ⇤ c h e c k normal c a s e f o r f i r s t add o p e r a t i o n
34 ⇤/
35 @Test public void testAdd ( ) {
36 mycalc . add ( 4 ) ;
37 a s s e r t E q u a l s ( 4 , mycalc . g e t R e s u l t ( ) ) ;
38 }
39
40 /⇤ ⇤
41 ⇤ c h e c k normal c a s e f o r f i r s t s u b t r a c t o p e r a t i o n
42 ⇤/

11
43 @Test public void t e s t S u b t r a c t ( ) {
44 mycalc . s u b t r a c t ( 4 ) ;
45 a s s e r t E q u a l s ( 4 , mycalc . g e t R e s u l t ( ) ) ;
46 }
47
48 /⇤ ⇤
49 ⇤ c h e c k normal c a s e f o r m u l t i p l y 2⇤4 = 8
50 ⇤/
51 @Test public void t e s t M u l t i p l y ( ) {
52 mycalc . add ( 2 ) ;
53 mycalc . m u l t i p l y ( 4 ) ;
54 a s s e r t E q u a l s ( 8 , mycalc . g e t R e s u l t ( ) ) ;
55 }
56
57 /⇤ ⇤
58 ⇤ c h e c k normal c a s e f o r d i v i d e 6/2 = 3
59 ⇤/
60 @Test public void t e s t D i v i d e ( ) {
61 mycalc . add ( 6 ) ;
62 mycalc . d i v i d e ( 2 ) ;
63 a s s e r t E q u a l s ( 3 , mycalc . g e t R e s u l t ( ) ) ;
64 }
65
66 /⇤ ⇤
67 ⇤ c h e c k e x c e p t i o n c a s e f o r d i v i d e by 0
68 ⇤/
69 @Test public void t e s t D i v i d e Z e r o ( ) {
70 mycalc . add ( 6 ) ;
71 mycalc . d i v i d e ( 0 ) ;
72 a s s e r t E q u a l s ( mycalc .ERROR VALUE, mycalc . g e t R e s u l t
() ) ;
73 }
74
75 /⇤ ⇤
76 ⇤ c h e c k c l e a r method c l e a r s t h e r e s u l t
77 ⇤/
78 @Test public void t e s t C l e a r ( ) {
79 mycalc . add ( 6 ) ;
80 a s s e r t E q u a l s ( 6 , mycalc . g e t R e s u l t ( ) ) ;
81 mycalc . c l e a r ( ) ;
82 a s s e r t E q u a l s ( mycalc . INITIAL VALUE , mycalc .
getResult () ) ;
83 }
84 }

12
6 Collections Example: Membership.java
1 /⇤ ⇤
2 ⇤ S t o r e d e t a i l s o f a c l u b membership .
3 ⇤
4 ⇤ @author David J . Barnes and Mi chael K l l i n g
5 ⇤ @ v er s i on 2 0 1 1 . 0 7 . 3 1
6 ⇤/
7 public c l a s s Membership
8 {
9 // The name o f t h e member .
10 private S t r i n g name ;
11 // The month i n which t h e membership was t a k e n o u t .
12 private int month ;
13 // The y e a r i n which t h e membership was t a k e n o u t .
14 private int y e a r ;
15 // The p a i d f o r l e n g t h o f membership i n y e a r s
16 private int l e n g t h ;
17
18 /⇤ ⇤
19 ⇤ C o n s t r u c t o r f o r o b j e c t s o f c l a s s Membership .
20 ⇤ @param name The name o f t h e member .
21 ⇤ @param month The month i n which t h e y j o i n e d . (1
. . . 12)
22 ⇤ @param y e a r The y e a r i n which t h e y j o i n e d .
23 ⇤/
24 public Membership ( S t r i n g name , int month , int year ,
int l e n g t h )
25 throws I l l e g a l A r g u m e n t E x c e p t i o n
26 {
27 i f ( month < 1 | | month > 1 2 ) {
28 throw new I l l e g a l A r g u m e n t E x c e p t i o n (
29 ”Month ” + month + ” out o f r a n g e . Must
be i n t h e r a n g e 1 . . . 12 ” ) ;
30 }
31 t h i s . name = name ;
32 t h i s . month = month ;
33 this . year = year ;
34 this . length = length ;
35 }
36
37 /⇤ ⇤
38 ⇤ @return The member ’ s name .
39 ⇤/
40 public S t r i n g getName ( )

13
41 {
42 return name ;
43 }
44
45 /⇤ ⇤
46 ⇤ @return The month i n which t h e member j o i n e d .
47 ⇤ A v a l u e i n t h e range 1 . . . 12
48 ⇤/
49 public int getMonth ( )
50 {
51 return month ;
52 }
53
54 /⇤ ⇤
55 ⇤ @return The y e a r i n which t h e member j o i n e d .
56 ⇤/
57 public int getYear ( )
58 {
59 return y e a r ;
60 }
61
62 /⇤ ⇤
63 ⇤ @return The l e n g t h o f membership p a i d f o r i n y e a r s
.
64 ⇤/
65 public int g et Le n g t h ( )
66 {
67 return l e n g t h ;
68 }
69
70 /⇤ ⇤
71 ⇤ I n c r e a s e membership l e n g t h by o f f e r amount .
72 ⇤ @param o f f e r The number o f y e a r s t o e x t e n d a l l
memberships
73 ⇤ No c h e c k i s made f o r p o s i t i v e o f f e r amount
74 ⇤
75 ⇤/
76 public void i n c r e a s e L e n g t h ( int o f f e r )
77 {
78 length = length + o f f e r ;
79 }
80
81 /⇤ ⇤
82 ⇤ @return A s t r i n g r e p r e s e n t a t i o n o f t h i s membership
.
83 ⇤/

14
84 public S t r i n g t o S t r i n g ( )
85 {
86 return ”Name : ” + name +
87 ” j o i n e d i n month ” +
88 month + ” o f ” + y e a r +
89 ” and has ” + l e n g t h + ” y e a r s o f
membership ” ;
90 }
91 }

15
7 Collections Example: Club.java
1 import j a v a . u t i l . A r r a y L i s t ;
2 /⇤ ⇤
3 ⇤ S t o r e d e t a i l s o f c l u b memberships .
4 ⇤
5 ⇤ @author RCO
6 ⇤ @ v er s i on December 2012
7 ⇤/
8 public c l a s s Club
9 {
10 A r r a y L i s t <Membership> c l u b ;
11
12 /⇤ ⇤
13 ⇤ C o n s t r u c t o r f o r o b j e c t s o f c l a s s Club
14 ⇤/
15 public Club ( )
16 {
17 c l u b = new A r r a y L i s t <Membership >() ;
18
19 }
20
21 /⇤ ⇤
22 ⇤ Add a new member t o t h e c l u b ’ s l i s t o f members .
23 ⇤ @param member The member o b j e c t t o be added .
24 ⇤/
25 public void j o i n ( Membership member )
26 {
27 c l u b . add ( member ) ;
28 }
29
30 /⇤ ⇤
31 ⇤ @return The number o f members ( Membership o b j e c t s )
in
32 ⇤ the club .
33 ⇤/
34 public int numberOfMembers ( )
35 {
36 return club . s i z e () ;
37 }
38
39 /⇤ ⇤
40 ⇤ P r i n t t h e d e t a i l s o f a l l c u r r e n t members t o
standard output .
41 ⇤/

16
42 public void l i s t M e m b e r s ( )
43 {
44 f o r ( Membership member : c l u b )
45 {
46 System . out . p r i n t l n ( member . t o S t r i n g ( ) ) ;
47 }
48 }
49
50 /⇤ ⇤
51 ⇤ Extend t h e membership o f a l l members by o f f e r
years
52 ⇤ @param o f f e r The number o f y e a r s t o e x t e n d a l l
memberships
53 ⇤ No c h e c k i s made f o r p o s i t i v e o f f e r amount
54 ⇤/
55 public void extendMembership ( int o f f e r )
56 {
57 f o r ( Membership member : c l u b )
58 {
59 member . i n c r e a s e L e n g t h ( o f f e r ) ;
60 }
61
62 }
63
64 /⇤ ⇤
65 ⇤ @return t h e number o f members whose membership has
or w i l l e x p i r e f o r a g i v e n y e a r
66 ⇤ @param t h i s y e a r The y e a r t o be c h e c k e d
67 ⇤/
68 public int numOverdue ( int t h i s y e a r )
69 {
70 int overdue = 0 ; // c o u n t e r f o r number o f o v e r d u e
members
71 f o r ( Membership member : c l u b )
72 {
73 i f ( ( member . getYear ( )+member . get Len gth ( ) ) <
thisyear )
74 {
75 overdue++;
76 }
77 }
78 return overdue ;
79 }
80 }

17
8 Collections Example: ClubDemo.java
1
2 /⇤ ⇤
3 ⇤ Demonstration o f t h e f u n c t i o n a l i t i e s o f a Club
4 ⇤
5 ⇤ @author Rachel C a r d e l l O l i v e r
6 ⇤ @ v er s i on January 2013
7 ⇤/
8 public c l a s s ClubDemo
9 {
10
11 private Club c l u b ;
12
13 /⇤ ⇤
14 ⇤ C o n s t r u c t o r f o r o b j e c t s o f c l a s s ClubDemo
15 ⇤/
16 public ClubDemo ( )
17 {
18 c l u b = new Club ( ) ;
19 }
20
21 /⇤ ⇤
22 ⇤ Add some members t o t h e c l u b , and t h e n
23 ⇤ show how many t h e r e a r e .
24 ⇤ F u r t h e r example c a l l s c o u l d be added i f more
functionality
25 ⇤ i s added t o t h e Club c l a s s .
26 ⇤/
27 public void demo ( )
28 {
29 System . out . p r i n t l n ( ” C r e a t e a c l u b with 3 members”
);
30 c l u b . j o i n (new Membership ( ” David ” , 2 , 2 0 0 4 , 5 ) ) ;
31 c l u b . j o i n (new Membership ( ” Michael ” , 1 , 2 0 0 4 , 1 0 ) )
;
32 c l u b . j o i n (new Membership ( ” Susan ” , 5 , 2 0 0 5 , 5 ) ) ;
33 System . out . p r i n t l n ( ”The c l u b has ” +
34 c l u b . numberOfMembers ( ) +
35 ” members . ” ) ;
36
37
38 // p r i n t o u t t h e c u r r e n t c l u b
39 System . out . p r i n t l n ( ) ;
40 System . out . p r i n t l n ( ” L i s t Current Membership ” ) ;

18
41 club . listMembers ( ) ;
42
43 // g i v e e v e r y o n e an e x t r a y e a r and re p r i n t t h e
current l i s t
44 System . out . p r i n t l n ( ) ;
45 System . out . p r i n t l n ( ” Extend a l l memberships by 1
year ” ) ;
46 c l u b . extendMembership ( 1 ) ;
47 club . listMembers ( ) ;
48
49 // c h e c k how many e x p i r e d memberships
50 System . out . p r i n t l n ( ) ;
51 System . out . p r i n t l n ( ” Check f o r e x p i r e d memberships
i n 2013 ” ) ;
52 System . out . p r i n t l n ( ” For 2013 t h e r e a r e ” + c l u b .
numOverdue ( 2 0 1 3 ) + ” overdue memberships ” ) ;
53
54 }
55 }

19
9 Object Interation: NumberDisplay.java
1
2 /⇤ ⇤
3 ⇤ The NumberDisplay c l a s s r e p r e s e n t s a d i g i t a l number
d i s p l a y t h a t can h o l d v a l u e s from z e r o t o a g i v e n
limit .
4 ⇤ The l i m i t can be s p e c i f i e d when c r e a t i n g t h e d i s p l a y .
5 ⇤ The v a l u e s range from z e r o ( i n c l u s i v e ) t o l i m i t 1.
6 ⇤ I f used , f o r example , f o r t h e s e c o n d s on a d i g i t a l
c l o c k , t h e l i m i t would be 60 , r e s u l t i n g i n d i s p l a y
v a l u e s from 0 t o 5 9 .
7 ⇤ When incremented , t h e d i s p l a y a u t o m a t i c a l l y r o l l s o v e r
t o z e r o when r e a c h i n g t h e l i m i t .
8 ⇤
9 ⇤ @author M i chael K o e l l i n g and David J . Barnes e x t e n d e d
by ( your name h e r e )
10 ⇤ @ v er s i on 2 0 1 1 . 0 7 . 3 1 e x t e n d e d on ( your d a t e h e r e )
11 ⇤/
12 public c l a s s NumberDisplay
13 {
14 private int l i m i t ;
15 private int v a l u e ;
16
17 /⇤ ⇤
18 ⇤ C o n s t r u c t o r f o r o b j e c t s o f c l a s s NumberDisplay .
19 ⇤ S e t t h e l i m i t a t which t h e d i s p l a y r o l l s o v e r .
20 ⇤/
21 public NumberDisplay ( int r o l l O v e r L i m i t )
22 {
23 limit = rollOverLimit ;
24 value = 0;
25 }
26
27 /⇤ ⇤
28 ⇤ Return t h e c u r r e n t v a l u e .
29 ⇤/
30 public int g e t V a l u e ( )
31 {
32 return v a l u e ;
33 }
34
35 /⇤ ⇤
36 ⇤ Return t h e d i s p l a y v a l u e ( t h a t i s , t h e c u r r e n t
v a l u e as a two d i g i t

20
37 ⇤ S t r i n g . I f t h e v a l u e i s l e s s than ten , i t w i l l be
padded w i t h a l e a d i n g z e r o ) .
38 ⇤/
39 public S t r i n g g e t D i s p l a y V a l u e ( )
40 {
41 i f ( value < 10) {
42 return ” 0 ” + v a l u e ;
43 }
44 else {
45 return ” ” + v a l u e ;
46 }
47 }
48
49 /⇤ ⇤
50 ⇤ S e t t h e v a l u e o f t h e d i s p l a y t o t h e new s p e c i f i e d
v a l u e . I f t h e new v a l u e i s l e s s than z e r o or o v e r
t h e l i m i t , do n o t h i n g .
51 ⇤/
52 public void s e t V a l u e ( int r e p l a c e m e n t V a l u e )
53 {
54 i f ( ( r e p l a c e m e n t V a l u e >= 0 ) && ( r e p l a c e m e n t V a l u e <
limit ) ) {
55 value = replacementValue ;
56 }
57 }
58
59 /⇤ ⇤
60 ⇤ Increment t h e d i s p l a y v a l u e by one , r o l l i n g o v e r
to zero i f the l i m i t i s reached .
61 ⇤/
62 public void i n c r e m e n t ( )
63 {
64 value = ( value + 1) % l i m i t ;
65 }
66 }

10 Object Interation: ClockDisplay.java


1
2 /⇤ ⇤
3 ⇤ The C l o c k D i s p l a y c l a s s implements a d i g i t a l c l o c k
d i s p l a y f o r a European s t y l e 24 hour c l o c k .
4 ⇤ The c l o c k shows h o u r s and minutes .
5 ⇤ The range o f t h e c l o c k i s 0 0 : 0 0 ( m i d n i g h t ) t o 2 3 : 5 9 (
one minute b e f o r e m i d n i g h t ) .
6 ⇤

21
7 ⇤ The c l o c k d i s p l a y r e c e i v e s ” t i c k s ” ( v i a t h e t i m e T i c k
method ) e v e r y minute and r e a c t s by i n c r e m e n t i n g t h e
display .
8 ⇤ This i s done i n t h e u s u a l c l o c k f a s h i o n : t h e hour
i n c r e m e n t s when t h e minutes r o l l o v e r t o z e r o .
9 ⇤
10 ⇤ @author M i chael K o e l l i n g and David J . Barnes e x t e n d e d
by ( your name h e r e )
11 ⇤ @ v er s i on 2 0 1 1 . 0 7 . 3 1 e x t e n d e d on ( your d a t e h e r e )
12 ⇤/
13 public c l a s s C l o c k D i s p l a y
14 {
15 private NumberDisplay h o u r s ;
16 private NumberDisplay minutes ;
17 private S t r i n g d i s p l a y S t r i n g ; // s i m u l a t e s t h e
actual display
18
19 /⇤ ⇤
20 ⇤ C o n s t r u c t o r f o r C l o c k D i s p l a y o b j e c t s . This
c o n s t r u c t o r c r e a t e s a new c l o c k s e t a t 0 0 : 0 0 .
21 ⇤/
22 public C l o c k D i s p l a y ( )
23 {
24 h o u r s = new NumberDisplay ( 2 4 ) ;
25 minutes = new NumberDisplay ( 6 0 ) ;
26
27 updateDisplay ( ) ;
28 }
29
30 /⇤ ⇤
31 ⇤ C o n s t r u c t o r f o r C l o c k D i s p l a y o b j e c t s . This
c o n s t r u c t o r c r e a t e s a new c l o c k s e t a t t h e time
s p e c i f i e d by t h e p a r a m e t e r s .
32 ⇤/
33 public C l o c k D i s p l a y ( int hour , int minute )
34 {
35 h o u r s = new NumberDisplay ( 2 4 ) ;
36 minutes = new NumberDisplay ( 6 0 ) ;
37 setTime ( hour , minute ) ;
38 }
39
40
41 /⇤ ⇤
42 ⇤ This method s h o u l d g e t c a l l e d once e v e r y minute
i t makes t h e c l o c k d i s p l a y go one minute f o r w a r d .
43 ⇤/

22
44 public void timeTick ( )
45 {
46 minutes . i n c r e m e n t ( ) ;
47 i f ( minutes . g e t V a l u e ( ) == 0 ) {
48 // i t j u s t r o l l e d o v e r !
49 hours . increment ( ) ;
50 i f ( h o u r s . g e t V a l u e ( ) == 0 ) {
51 dayofweek . i n c r e m e n t ( ) ;
52 }
53 }
54 updateDisplay ( ) ;
55 }
56
57
58 /⇤ ⇤
59 ⇤ S e t t h e time o f t h e d i s p l a y t o t h e s p e c i f i e d hour
and minute .
60 ⇤/
61 public void setTime ( int hour , int minute )
62 {
63 h o u r s . s e t V a l u e ( hour ) ;
64 minutes . s e t V a l u e ( minute ) ;
65 updateDisplay ( ) ;
66 }
67
68
69 /⇤ ⇤
70 ⇤ Return t h e c u r r e n t time o f t h i s d i s p l a y i n t h e
f or m at HH:MM.
71 ⇤/
72 public S t r i n g getTime ( )
73 {
74 return d i s p l a y S t r i n g ;
75 }
76
77 /⇤ ⇤
78 ⇤ Update t h e i n t e r n a l s t r i n g t h a t r e p r e s e n t s t h e
display .
79 ⇤/
80 private void u p d a t e D i s p l a y ( )
81 {
82 d i s p l a y S t r i n g = hours . getDisplayValue ( ) + ” : ” +
83 minutes . g e t D i s p l a y V a l u e ( ) ;
84 }
85
86 }

23
11 Example of HashMap use from the Zuul game
1 import j a v a . u t i l . HashMap ;
2
3 /⇤ ⇤
4 ⇤ This c l a s s i s p a r t o f t h e ”World o f Zuul ” a p p l i c a t i o n .
5 ⇤ ”World o f Zuul ” i s a v e r y s i m p l e , t e x t b a s e d a d v e n t u r e
game .
6 ⇤
7 ⇤ This c l a s s h o l d s an enumeration o f a l l command words
known t o t h e game .
8 ⇤ I t i s used t o r e c o g n i s e commands as t h e y a r e t y p e d i n .
9 ⇤
10 ⇤ @author M i chael K l l i n g and David J . Barnes
11 ⇤ @ v er s i on 2 0 1 1 . 0 8 . 0 9
12 ⇤/
13
14 public c l a s s CommandWords
15 {
16 // A mapping b e t w e e n a command word and t h e
CommandWord
17 // a s s o c i a t e d w i t h i t .
18 private HashMap<S t r i n g , CommandWord> validCommands ;
19
20 /⇤ ⇤
21 ⇤ Constructor i n i t i a l i s e t h e command words .
22 ⇤/
23 public CommandWords ( )
24 {
25 validCommands = new HashMap<S t r i n g , CommandWord
>() ;
26 validCommands . put ( ” go ” , CommandWord .GO) ;
27 validCommands . put ( ” h e l p ” , CommandWord .HELP) ;
28 validCommands . put ( ” q u i t ” , CommandWord . QUIT) ;
29 }
30
31 /⇤ ⇤
32 ⇤ Find t h e CommandWord a s s o c i a t e d w i t h a command
word .
33 ⇤ @param commandWord The word t o l o o k up ( as a
string ) .
34 ⇤ @return The CommandWord c o r r e s p o n d n g t o
commandWord , or UNKNOWN
35 ⇤ i f i t i s not a v a l i d command word .
36 ⇤/

24
37 public CommandWord getCommandWord ( S t r i n g commandWord)
38 {
39 CommandWord command = validCommands . g e t (
commandWord) ;
40 i f ( command != null ) {
41 return command ;
42 }
43 else {
44 return CommandWord .UNKNOWN;
45 }
46 }
47
48 /⇤ ⇤
49 ⇤ Check w h e t h e r a g i v e n S t r i n g i s a v a l i d command
word .
50 ⇤ @return t r u e i f i t i s , f a l s e i f i t i s n ’ t .
51 ⇤/
52 public boolean isCommand ( S t r i n g a S t r i n g )
53 {
54 return validCommands . c o n t a i n s K e y ( a S t r i n g ) ;
55 }
56
57 /⇤ ⇤
58 ⇤ P r i n t a l l v a l i d commands t o System . o u t .
59 ⇤/
60 public void showAll ( )
61 {
62 f o r ( S t r i n g command : validCommands . k e y S e t ( ) ) {
63 System . out . p r i n t ( command + ” ” ) ;
64 }
65 System . out . p r i n t l n ( ) ;
66 }
67 }

25
12 Game of Life: Life.java
1 /⇤ ⇤
2 ⇤ Java c l a s s f o r Conway ’ s Game o f L i f e
3 ⇤ @author PK, RCO
4 ⇤/
5
6 public c l a s s L i f e {
7
8 private boolean [ ] [ ] map ; // g r i d f o r L i f e
9 private boolean [ ] [ ] nextMap ; // g r i d f o r n e x t
generation
10 private int width ; // g r i d d i m e n s i o n s
11 private int h e i g h t ;
12
13
14 /⇤ ⇤
15 ⇤ Random c o n s t r u c t o r f o r game o f l i f e
16 ⇤
17 ⇤ @param w i d t h t h e x dimension o f t h e g r i d
18 ⇤ @param h e i g h t t h e y dimension o f t h e g r i d
19 ⇤ @param p r o b a b i l i t y i s t h e chance t h a t l i f e e x i s t s
i n any c e l l
20 ⇤/
21 public L i f e ( int width , int h e i g h t , double p r o b a b i l i t y
) {
22 map = new boolean [ width ] [ h e i g h t ] ;
23 nextMap = new boolean [ width ] [ h e i g h t ] ;
24 t h i s . width = width ;
25 this . height = height ;
26 initializeMap ( probability ) ;
27 }
28
29
30 /⇤ ⇤
31 ⇤ Life constructor for a given grid pattern
32 ⇤/
33 public L i f e ( boolean [ ] [ ] i n i t i a l ) {
34 map = i n i t i a l ;
35 width = map . l e n g t h ;
36 h e i g h t = map [ 0 ] . l e n g t h ;
37 nextMap = new boolean [ width ] [ h e i g h t ] ;
38 }
39
40 /⇤ ⇤

26
41 ⇤ f u l l y default Life constructor
42 ⇤/
43 public L i f e ( ) {
44 this (150 ,150 ,0.1) ;
45 }
46
47 /⇤ ⇤
48 ⇤ Construct a simple grid j u s t for t e s t i n g
49 ⇤/
50 public L i f e ( boolean t e s t o n l y ) {
51 t h i s . width = 1 0 ; // d e f a u l t magic numbers f o r
testing
52 t h i s . h e i g h t = 1 0 ; // u se d i f f ones t o t e s t
53 map = new boolean [ width ] [ h e i g h t ] ;
54 simpleMap ( ) ; // s e t up map f o r t e s t i n g
55 nextMap = new boolean [ width ] [ h e i g h t ] ;
56 //TODO nextMap i s i n i t i a l i s e d by n e x t G e n e r a t i o n
method
57 }
58
59 /⇤ ⇤
60 ⇤ p u b l i c map i n i t v e r s i o n j u s t f o r t e s t i n g
61 ⇤ TODO comment t h i s o u t or d e l e t e
62 ⇤/
63 public void simpleMap ( ) {
64 // c l e a r map
65 f o r ( int i =0; i <width ; i ++) {
66 f o r ( int j =0; j <h e i g h t ; j ++) {
67 map [ i ] [ j ]= f a l s e ;
68 }
69 }
70 // add some l i f e
71 map [ 4 ] [ 5 ] = true ;
72 map [ 5 ] [ 5 ] = true ;
73 map [ 6 ] [ 5 ] = true ;
74 map [ width 1 ] [ h e i g h t 1]=true ; // boundary c a s e
75 }
76
77 /⇤ ⇤
78 ⇤ F i l l a map w i t h new l i f e
79 ⇤ u s i n g prob as p r o b a b i l i t y t h a t l i f e e x i s t s i n any
cell
80 ⇤/
81 public void i n i t i a l i z e M a p ( double prob ) {
82 f o r ( int i =0; i <width ; i ++) {
83 f o r ( int j =0; j <h e i g h t ; j ++) {

27
84 i f ( Math . random ( ) < prob ) {
85 map [ i ] [ j ] = true ;
86 } else {
87 map [ i ] [ j ] = f a l s e ;
88 }
89 }
90 }
91 }
92
93
94 /⇤ ⇤
95 ⇤ game o f l i f e c u r r e n t p o p u l a t i o n c o u n t e r
96 ⇤
97 ⇤ @returns t h e number o f l i v e c e l l s i n map
98 ⇤/
99 public int p o p u l a t i o n ( ) {
100 int pop =0;
101 f o r ( int i =0; i <width ; i ++) {
102 f o r ( int j =0; j <h e i g h t ; j ++) {
103 i f (map [ i ] [ j ] ) pop++;
104 }
105 }
106 return pop ;
107 }
108
109 /⇤ ⇤
110 ⇤ c a l c u l a t e t h e n e x t g e n e r a t i o n o f l i f e and u p d a t e
map r e f e r e n c e
111 ⇤/
112 public void n e x t G e n e r a t i o n ( ) {
113 int n ;
114 // c a l c u l a t e n e x t map
115 f o r ( int i =0; i <width ; i ++) {
116 f o r ( int j =0; j <h e i g h t ; j ++) {
117 n = numNeighbours ( i , j ) ;
118 i f ( n <= 1 | | n >= 4 ) {nextMap [ i ] [ j ] =
false ;}
119 e l s e i f ( n == 2 ) {nextMap [ i ] [ j ] = map [ i ] [
j ];}
120 e l s e i f ( n == 3 ) {nextMap [ i ] [ j ] = true ; }
121 e l s e a s s e r t true : ”We s h o u l d not g e t h e r e
”;
122 }
123 }
124 // p o i n t map r e f e r e n c e t o t h e new g e n e r a t i o n
125 boolean [ ] [ ] swap = map ;

28
126 map = nextMap ;
127 nextMap = swap ;
128 }
129
130 /⇤ ⇤
131 ⇤ c ou n t number o f n e i g h b o u r s o u t o f 8 a d j a c e n t
squares
132 ⇤ a d j a c e n c y assumed t o wrap around g r i d a t t h e e d g e s
133 ⇤
134 ⇤ @param i g r i d c e l l column parameter ( w i d t h )
135 ⇤ @param j g r i d c e l l row parameter ( h e i g h t )
136 ⇤ @return number o f n e i g h b o u r s found
137 ⇤/
138 //TODO t h i s method j u s t made p u b l i c f o r t e s t , make
private helper later
139 public int numNeighbours ( int i , int j ) {
140 int n=0;
141 // unchecked e x c e p t i o n f o r i l l e g a l g r i d c e l l r e f s
142 i f ( ( i <0) | | ( i>=width ) | | ( j <0) | | ( j>=h e i g h t ) ) {
143 throw new I l l e g a l A r g u m e n t E x c e p t i o n ( ”
numNeighbours c e l l ”
144 +i+” , ”+j + ” out o f bounds ” ) ;
145 }
146
147 // c ou n t c l o c k w i s e from NW c o r n e r
148 int n o r t h =( h e i g h t+j 1)%h e i g h t ;
149 int s o u t h =( j +1)%h e i g h t ;
150 int e a s t =( i +1)%width ;
151 int west =(width+i 1)%width ;
152 // n o r t h row
153 i f (map [ west ] [ n o r t h ] ) n++;
154 i f (map [ i ] [ n o r t h ] ) n++;
155 i f (map [ e a s t ] [ n o r t h ] ) n++;
156 // e a s t n e i g h b o u r
157 i f (map [ e a s t ] [ j ] ) n++;
158 // s o u t h row
159 i f (map [ e a s t ] [ s ou t h ] ) n++;
160 i f (map [ i ] [ s o u t h ] ) n++;
161 i f (map [ west ] [ s o u t h ] ) n++;
162 // w e s t n e i g h b o u r
163 i f (map [ west ] [ j ] ) n++;
164 return n ;
165 }
166
167 /⇤
168 ⇤ s t a n d a r d s e t o f g e t t e r methods f o r a l l i n s t a n c e

29
variables
169 ⇤/
170 public boolean [ ] [ ] getMap ( ) { return map ; }
171
172 public int getWidth ( ) { return width ; }
173
174 public int g e t H e i g h t ( ) { return h e i g h t ; }
175
176 /⇤
177 ⇤ s t a n d a r d s e t o f s e t t e r methods f o r a l l i n s t a n c e
variables
178 ⇤/
179 public void setMap ( boolean [ ] [ ] map) {
180 t h i s . map=map ;
181 }
182
183 }

13 Game of Life: LifeViewer.java


1
2 /⇤ ⇤
3 ⇤ C l a s s t o v i s u a l i s e a game o f l i f e map
4 ⇤
5 ⇤ @author PK
6 ⇤ @ v er s i on R e v i s e d 2013
7 ⇤/
8
9 public c l a s s L i f e V i e w e r {
10 private L i f e l i f e ;
11 private int width ;
12 private int h e i g h t ;
13 private SimpleCanvas c ;
14 private s t a t i c int PAUSE = 1 0 ;
15
16 private f i n a l s t a t i c int CELL SIZE = 4 ;
17
18 private f i n a l s t a t i c j a v a . awt . C o l o r BACK COLOUR =
j a v a . awt . C o l o r . w h i t e ;
19 private f i n a l s t a t i c j a v a . awt . C o l o r CELL COLOUR =
j a v a . awt . C o l o r . b l u e ;
20 private f i n a l s t a t i c j a v a . awt . C o l o r GRID COLOUR =
j a v a . awt . C o l o r . b l a c k ;
21
22
23 public L i f e V i e w e r ( L i f e l i f e ) {

30
24
25 this . l i f e = l i f e ;
26 width = l i f e . getMap ( ) . l e n g t h ;
27 h e i g h t = l i f e . getMap ( ) [ 0 ] . l e n g t h ;
28
29 c = new SimpleCanvas ( ” L i f e ” , width ⇤CELL SIZE+1,
30 h e i g h t ⇤CELL SIZE+1, f a l s e )
;
31
32 display () ;
33 }
34
35 public L i f e V i e w e r ( ) {
36 t h i s (new L i f e ( ) ) ;
37 }
38
39 private void d i s p l a y ( ) {
40 erase () ;
41 drawCells () ;
42 // drawGrid ( ) ; l o o k s b e t t e r w i t h o u t g r i d l i n e s f o r
big grids
43 c . repaint () ;
44 }
45
46
47 private void e r a s e ( ) {
48 c . s e t F o r e g r o u n d C o l o u r (BACK COLOUR) ;
49 f o r ( int i =0; i <CELL SIZE⇤ h e i g h t ; i ++) {
50 c . drawLine ( 0 , i , CELL SIZE⇤ width , i ) ;
51 }
52 }
53
54 private void d r a w C e l l s ( ) {
55 boolean [ ] [ ] map = l i f e . getMap ( ) ;
56 c . s e t F o r e g r o u n d C o l o u r (CELL COLOUR) ;
57 f o r ( int i =0; i <width ; i ++) {
58 f o r ( int j =0; j <h e i g h t ; j ++) {
59 i f (map [ i ] [ j ] ) {
60 f o r ( int k=0;k<CELL SIZE ; k++){
61 c . drawLine ( i ⇤CELL SIZE+k , j ⇤
CELL SIZE ,
62 i ⇤CELL SIZE+k , ( j +1)⇤CELL SIZE )
;
63 }
64 }
65 }

31
66 }
67 }
68
69
70 private void drawGrid ( ) {
71 c . s e t F o r e g r o u n d C o l o u r (GRID COLOUR) ;
72
73 f o r ( int i =0; i<=width ; i ++) {
74 c . drawLine ( i ⇤CELL SIZE , 0 , i ⇤CELL SIZE , h e i g h t ⇤
CELL SIZE ) ;
75 }
76 f o r ( int j =0; j<=h e i g h t ; j ++) {
77 c . drawLine ( 0 , j ⇤CELL SIZE , width ⇤CELL SIZE , j ⇤
CELL SIZE ) ;
78 }
79 }
80
81
82 public void animate ( int n ) {
83 f o r ( int i =0; i <n ; i ++) {
84 l i f e . nextGeneration () ;
85 display () ;
86 c . w a i t (PAUSE) ;
87 }
88 }
89
90 public void s t e p ( ) {
91 l i f e . nextGeneration () ;
92 display () ;
93 }
94
95 public void randomize ( double p r o b a b i l i t y ) {
96 l i f e . initializeMap ( probability ) ;
97 display () ;
98 }
99
100 public void g l i d e r ( ) {
101 l i f e . setMap ( Examples . g l i d e r ( width , h e i g h t ) ) ;
102 display () ;
103 }
104
105 public void b l i n k ( ) {
106 l i f e . setMap ( Examples . b l i n k ( width , h e i g h t ) ) ;
107 display () ;
108 }
109

32
110 public void toad ( ) {
111 l i f e . setMap ( Examples . toad ( width , h e i g h t ) ) ;
112 display () ;
113 }
114
115 public void l i g h t W e i g h t S p a c e S h i p ( ) {
116 l i f e . setMap ( Examples . l i g h t W e i g h t S p a c e S h i p ( width ,
height ) ) ;
117 display () ;
118 }
119
120 public void dieHard ( ) {
121 l i f e . setMap ( Examples . dieHard ( width , h e i g h t ) ) ;
122 display () ;
123 }
124
125 public void a c o r n ( ) {
126 l i f e . setMap ( Examples . a c o r n ( width , h e i g h t ) ) ;
127 display () ;
128 }
129
130 public void g o s p e r ( ) {
131 l i f e . setMap ( Examples . g o s p e r ( width , h e i g h t ) ) ;
132 display () ;
133 }
134
135 public void b l o c k 1 ( ) {
136 l i f e . setMap ( Examples . b l o c k 1 ( width , h e i g h t ) ) ;
137 display () ;
138 }
139
140 public void b l o c k 2 ( ) {
141 l i f e . setMap ( Examples . b l o c k 2 ( width , h e i g h t ) ) ;
142 display () ;
143 }
144
145 }

33
14 Sorting Algorithms: Sorter.java
1
2 /⇤ ⇤
3 ⇤ U t i l i t y c l a s s o f example S o r t i n g a l g o r i t h m s
4 ⇤
5 ⇤ @author Rachel C a r d e l l O l i v e r
6 ⇤ @ v er s i on May 2011 r e v i s e d May 2012 C h e c k s t y l e c h e c k e d
May 2013
7 ⇤/
8 public c l a s s S o r t e r
9 {
10
11 /⇤ ⇤
12 ⇤ b u b b l e s o r t method
13 ⇤ @param a array of values to s o r t in place
14 ⇤/
15 public s t a t i c void b u b b l e S o r t ( int [ ] a )
16 {
17 f o r ( int p a s s = 1 ; p a s s < a . l e n g t h ; p a s s++) {
18 f o r ( int j = 0 ; j < a . l e n g t h p a s s ; j ++) {
19 if (a [ j ] > a [ j + 1]) {
20 int swap = a [ j + 1 ] ;
21 a [ j + 1] = a [ j ] ;
22 a [ j ] = swap ;
23 }
24 }
25 }
26 }
27
28 /⇤ ⇤
29 ⇤ i n s e r t i o n s o r t method
30 ⇤ @param a array of values to s o r t in place
31 ⇤/
32 public s t a t i c void i n s e r t i o n S o r t ( int [ ] a )
33 {
34 f o r ( int p a s s = 1 ; p a s s < a . l e n g t h ; p a s s++) {
35 int tmp = a [ p a s s ] ; // v a l u e t o be i n s e r t e d
36 int pos = p a s s 1 ; // p o s i t i o n o f s o r t e d so
far elements
37 while ( pos >= 0 && a [ pos ] > tmp ) {
38 a [ pos + 1 ] = a [ pos ] ; //move up o u t o f
order elements
39 pos ;
40 }

34
41 a [ pos + 1 ] = tmp ; // p u t v a l i n t h e r i g h t
place
42 }
43 }
44
45 /⇤ ⇤
46 ⇤ Sort the elements of the array into increas in g
o r d e r by
47 ⇤ s e l e c t i n g t h e s m a l l e s t e l e m e n t i n t h e a r r a y and
swapping i t
48 ⇤ w i t h t h e e l e m e n t i n pos 0 .
49 ⇤ Then c a l c u l a t e t h e p o s i t i o n o f t h e s m a l l e s t
element
50 ⇤ i n t h e a r r a y s t a r t i n g from p o s i t i o n 1 , and swap
the element
51 ⇤ t h e r e i n t o p o s i t i o n 1 , and so on f o r each p o s i t i o n
.
52 ⇤
53 ⇤ @param a i n t e g e r a r r a y t o be s o r t e d i n p l a c e
54 ⇤/
55
56 public s t a t i c void s e l e c t i o n S o r t ( int [ ] a )
57 {
58 int swappos ;
59 int min ;
60 f o r ( int i = 0 ; i < a . l e n g t h 1 ; i ++) {
61 min = a [ i ] ;
62 swappos = i ;
63 f o r ( int j = i + 1 ; j < a . l e n g t h ; j ++) { //
find s m a l l e s t in r e s t
64 i f ( a [ j ] < min ) {
65 min = a [ j ] ;
66 swappos = j ;
67 } // now swappos i s t h e s m a l l e s t e l e m e n t
i n i +1 t o l e n g t h
68 }
69
70 i f ( i != swappos ) { // swap i and swappos i f
necessary
71 int temp = a [ i ] ;
72 a [ i ] = a [ swappos ] ; // i e min
73 a [ swappos ] = temp ;
74 }
75 }
76 }
77

35
78 /⇤ ⇤
79 ⇤ p a r t i t i o n an a r r a y around t h e f e n c e a [ s t a r t ]
80 ⇤ @param a a r r a y t o be p a r t i t i o n e d
81 ⇤ @param s t a r t f i r s t p o s i t i o n o f a r r a y f r a g m e n t t o
sort
82 ⇤ @param f i n i s h l a s t p o s i t i o n o f a r r a y f r a g m e n t t o
sort
83 ⇤ @return r i g h t o f p a r t i t i o n
84 ⇤/
85 private s t a t i c int p a r t i t i o n ( int [ ] a , int s t a r t , int
finish )
86 {
87 int f e n c e = a [ s t a r t ] ;
88 int l e f t = s t a r t + 1 ;
89 int r i g h t = f i n i s h ;
90 while ( r i g h t >= l e f t ) {
91 while ( l e f t <= r i g h t && a [ l e f t ] <= f e n c e ) {
92 l e f t ++;
93 }
94 while ( r i g h t >= l e f t && a [ r i g h t ] >= f e n c e ) {
95 right ;
96 }
97 if ( right > l e f t ) {
98 int swap = a [ l e f t ] ;
99 a [ l e f t ] = a [ right ] ;
100 a [ r i g h t ] = swap ;
101 }
102 }
103 a [ start ] = a [ right ] ;
104 a [ right ] = fence ;
105 return r i g h t ;
106 }
107
108 /⇤ ⇤
109 ⇤ q u i c k s o r t h e l p e r method
110 ⇤ @param a a r r a y t o be s o r t e d
111 ⇤ @param s t a r t f i r s t p o s i t i o n o f a r r a y f r a g m e n t t o
sort
112 ⇤ @param f i n i s h l a s t p o s i t i o n o f a r r a y f r a g m e n t t o
sort
113 ⇤/
114 private s t a t i c void q u i c k S o r t ( int [ ] a , int s t a r t , int
finish )
115 {
116 if ( finish s t a r t > 0) {
117 int f e n c e P o s i t i o n = p a r t i t i o n ( a , s t a r t , f i n i s h )

36
;
118 quickSort (a , start , fencePosition 1) ;
119 quickSort (a , fencePosition + 1 , f i n i s h ) ;
120 }
121 }
122
123 /⇤ ⇤
124 ⇤ quicksort recursive sorting algorithm
125 ⇤ @param a a r r a y t o be s o r t e d
126 ⇤/
127 public s t a t i c void q u i c k S o r t ( int [ ] a )
128 {
129 quickSort (a , 0 , a . length 1) ;
130 }
131
132 /⇤ ⇤
133 ⇤ l i n e a r s e a r c h f o r key i n a r r a y o f d a t a
134 ⇤ @param d a t a a r r a y o f s o r t e d i n t s t o s e a r c h
135 ⇤ @param key i n t t o be s e a r c h e d f o r
136 ⇤ @return b o o l e a n t r u e i f v a l u e found and f a l s e
otherwise
137 ⇤/
138 public s t a t i c boolean l i n e r a r S e a r c h ( int [ ] data , int
key )
139 {
140 f o r ( int d i : data ) {
141 i f ( d i == key ) {
142 return true ;
143 }
144 }
145 return f a l s e ;
146 }
147
148 /⇤ ⇤
149 ⇤ binary search f o r value in a ⇤ sorted ⇤ array
150 ⇤ @param d a t a a r r a y o f s o r t e d i n t s t o s e a r c h
151 ⇤ @param key i n t t o be s e a r c h e d f o r
152 ⇤ @return b o o l e a n t r u e i f v a l u e found and f a l s e
otherwise
153 ⇤/
154 public s t a t i c boolean b i n a r y S e a r c h ( int [ ] data , int
key )
155 {
156 int l e f t = 0 ;
157 int r i g h t = data . l e n g t h 1;
158 while ( r i g h t l e f t > 1) {

37
159 int middle = ( l e f t + r i g h t ) / 2 ;
160 i f ( data [ middle ] >= key ) {
161 r i g h t = middle ;
162 } else {
163 l e f t = middle ;
164 }
165 }
166 return ( data [ l e f t ] == key | | data [ r i g h t ] == key ) ;
167 }
168 }

38

Potrebbero piacerti anche