Introductory Lecture - DMU

  • Doc File 380.00KByte

Module Information


• CSCI1003 Module booklet

• Two one hour weekly lectures

• One two hour staffed laboratory session

• Java 1.2

Assessment Notes

The assessment for this module is 100% coursework, held in a portfolio – see later) comprising three parts

1. ONE compulsory case study - the WeatherStation

2. ONE of two other case studies - Linear Search / HashTable OR StringTokeniser

3. ONE of two other case studies - Swing classes OR Applets

The actual assessment is via a viva-voce examination of the work you complete and submit

• Completing the compulsory case study will make it possible to gain a grade F to C+

• Completing 2 above can increase your grade by 0,1,2 or 3 grade points

• Completing 3 above can increase your grade by 0,1,2 or 3 grade points

• The above makes it possible to gain all grades up to A+. An A* grade will be awarded for flair and understanding as identified at the viva voce examination.


You find the course and work straightforward but demanding

On 1 you gain a grade C-

On 2 you gain 2 extra grade points taking your grade to C+

On 3 you gain 1 extra grade point taking your final grade to B-

At the viva you show good understanding - your grade is increased to a B or even B+

You find the course and work straightforward and easy

On 1 you gain a grade C

On 2 you gain 3 extra grade points taking your grade to B+

On 3 you gain 2 extra grade point taking your final grade to an A

At the viva you show clear sound understanding - your grade is increased to an A+ or even A*

You find the course and work difficult

On 1 you gain a grade D +

On 2 you gain 1 extra grade points taking your grade to C-

On 3 you gain 0 extra grade point leaving your final grade at C-

Your viva suggests you are capable of better - your grade is increased to a C

You find the course and work very difficult

On 1 you gain a grade U

On 2 you gain 1 extra grade points taking your grade to D-

On 3 you gain 0 extra grade point leaving your final grade at D-

Your viva suggests this is a fair grade and is unchanged OR at best becomes a D

The WeatherStation will be assessed using the following criteria

|Criteria |Grade |

|Implementing the WeatherStation |C+ |

|Implementing the Alarm and Monitor class |C |

|Implementing the MultiMaxMinNumberStore |C- |

|Implementing the MultiNumberStore |D+ |

|Implementing the MaxMinNumberStore classes |D |

|Implementing the MaxNumber and MinNumberStore classes |D- |

|Implementing the NumberStore class |U |

|Testing the String, Integer and NumberStore classes only |F |

Details of the three criteria for the other case studies will be given later.

The Portfolio

This is a crucial document.

The amount of work you do will determine the type of folder you use for your portfolio. An A4 ring-binder may be most appropriate.

• It will contain a record of the work you have completed as proof that you have done the work.

• It will be used by your tutor, at the viva-voce examination, as the basis of questions to ask.

• It will be used by you to revise for the viva-voce examination as it will contain YOUR notes.

• It must be kept up to date.

• It will be checked in week 5 for completeness.

• It will be submitted before the viva in week 11.

A formative phase test will be given part way through the module. This will not contribute marks towards the grade for the module but will be deigned to help students identify any gaps in their knowledge and understanding.

The viva voce examination will provide you with the opportunity to explain your work and understanding of the solutions you have written. It will last about 30-40 minutes.

Teaching Notes

Although lectures are the usual means of teaching supported by tutorials this module uses taught laboratories to support the practical element of the course.

The first 20-30 minutes of each 2-hour laboratory session will be normally used to explain not only the learning outcomes of the laboratory session but also to explain some key ideas from the previous week’s lectures.

Initial laboratories will explain how to use the java environment and how to test programs.

Learning Notes

Writing programs takes a long time. You will not be able to learn what is expected, complete the work or pass the module using just the 4 hours taught each week. You will be expected to spend a minimum of 2-4 hours per week at a computer completing the set exercises and coursework. In addition you will need to spend time reading, preparing and ensuring that you understand all of your work.

The work set in laboratories will be on the content of the lectures from the previous week.

Introduction to the module

This first lecture explains the week by week plan, the resources provided and the learning, teaching and assessment methods used on the module. It also lists all of the key elements of Object Oriented Software Design and Development that it will be assumed students will have acquired on completion of this module

Learning Outcomes

Students should be able to

• explain the learning outcomes of the module and the learning plan

• explain the assessment scheme and the portfolio required

• write down and explain the key Object Oriented concepts required by this module.

Learning Resources

• Sections of the CSCI1003 Module booklet

• Definitions of terms used in the module.

Learning Notes

This is both an introductory and summary lecture. It is important that students understand that this module will provide all knowledge and skills requited to complete this module successfully.

The following lists the words the definitions of which you will be provided.

Class, object, method, message, operation, state, attribute, private, public, protected, parameter, receiver, association, aggregation, composition, inheritance, subclass, superclass, class diagram. Model, interaction diagram, object diagram, delegation, responsibility, collaboration, self-delegation, Use-case, use-case scenario, use-case narrative.

Teaching Resources and Notes

A class diagram, object diagram, interaction diagram and sample code are provided as the teaching resources. These diagrams include examples of all object-oriented elements used by this module.

Definitions, of Object Oriented terms. with examples taken from the Bank case study, are provided for use nd reference throughout the module.

The Class Diagram of a Bank includes attributes and operations (+ - #); associations; navigability, multiplicity, name, roles etc.; inheritance, abstract class, sub-classes and super-classes; aggregation and composition plus concepts such as an association class for transactions.

The Object Diagram shows three accounts in the AccountBase with two owned by one customer and the third by another; the Bank and the accounts and customers bases and two transactions, one a deposit and the other a transfer.

The Interaction Sequence Diagram shows a transfer of funds between two BankAccounts including the creation of associated transactions which might be used in the printing of a bank statement.

The lecture will simply use the diagrams as vehicles to introduce and explain all object oriented concepts covered by this module.

Definitions of Object Oriented Terms

|Term |Definition and Example |

|Abstract Class |A class from which instances may not be created (typically a generalisation high in the class hierarchy) |

| |in the bank example BankAccount could possibly be abstract if when debiting a sub class is always responsible|

| |for checking for sufficient funds ( overdrawn or not) |

|Aggregation |A special form of association that specifies a whole-part relationship between the aggregate (the whole) and |

| |a component (the part) |

| |accounts is an AccountBase, it contains many account objects |

|Association |A structural relationship that describes a set of links, in which a link is a connection among objects. A |

| |relationship that expresses the meaning of the link between objects. |

| |a customer owns some accounts |

|Term |Definition and Example |

|Class |A description of a set of objects that share the same attributes, operations, relationships and semantics |

| |(meaning). |

| |Transaction class |

|Composition |This is a form of aggregation with strong ownership. When the multiplicity of the part is fixed then the |

| |part must be created when the whole is created and be destroyed when the whole is destroyed. Parts where the|

| |multiplicity is not fixed may be created independently of the whole and added but must be destroyed when the |

| |whole is destroyed. Such parts may be removed from the whole before the whole is destroyed. |

| |a bank is composed of a collection of customers and accounts |

|Concrete Class |A class from which instance may be created (typically a specialisation lower in the class hierarchy) |

| |a customer may have both savings and a current accounts, |

| |(in the bank example BankAccount could possibly be abstract) |

|Delegation |The ability of an object to issue a message to another object in response to a message |

| |a customer object delegates the displaying of account details to its account(s) |

|Generalisation / |A generalisation/specialisation relationship is one in which objects of the specialised element (the child) |

|Specialisation |are substitutable for objects of the generalised element (the parent) |

| |a customer is a special kind of a person, a person with some accounts |

|Inheritance |This is the mechanism by which more-specific elements incorporate the structure and behaviour of more-general|

| |elements. |

| |a customer inherits from Person the ability to display its name, age and gender |

|Instance |A concrete (actual) manifestation of an Abstraction (class) that has a state and to which a set of operations|

| |can be applied possibly to change that state. |

| |savings account number 1235 is owned by Bob, a customer of the bank, this savings account can be debited - if|

| |there is any money in it |

|Interaction Sequence Diagram |A diagram that represents a dynamic view of a system. It shows, in time sequence, an interaction consisting |

| |of a set of objects and their relationships, including the messages that are dispatched. |

|Message |A specification of a communication between objects which results in a method being applied to the receiver of|

| |the message. |

| | |

| |a savings account is sent a message to debit £100 from itself |

|Method |The implementation of an operation that can be applied to an object |

| |program code that when executed debits an amount of money from an account |

|Multipicity |A specification of the range of allowable values/numbers that an object or collection of objects may take. |

| |a customer can have between 0 and 5 accounts |

|Multiple Inheritance |A semantic variation of generalisation in which a child may have more than one parent |

| |NO EXAMPLE – Not supported by Java (except via interfaces) |

|Navigation |A specification of the direction in which an association between objects may operate. |

| | an account knows about its customer, it can request a customer to display its details |

|Operation |the implementation of a service that can be requested from any object of the class in order to affect |

| |behaviour |

| |getBalance() is an operation of an account |

|Responsibility |A contract or obligation of an object. |

| |an account is responsible for knowing its balance |

|Single Inheritance |A semantic variation of generalisation in which a child may have only one parent |

| |Current and Savings |

|SubClass |In a generalisation relationship this is the specialisation of another (the parent) class |

| |a savings account is a specialised sub class of a more general account class |

|SuperClass |In a generalisation relationship this is the generalisation of another (the child) class |

| |an account class is a general super class of a more specialised account classes |

|Use-Case |A description of a set of sequences of actions, including variants, that a system performs that yields an |

| |observable result of value. |

| |a customer attempts to debit his savings account |

|Use-Case Scenario |A description of a specific variant of a given Use-Case |

| |a customer successfully debits his savings account |

|Use-Case Narrative |A 'real' narrative (story) describing how a Use-Case scenario might occur. |

| |Bob debits £100 from his savings account |

Bank Class Diagram

Notes on the Diagram

The Transaction class is an association class that is needed to represent the association “transfers money to” between one BankAccount and another. The two attributes that are needed are the amount being transferred and the other account involved. For a deposit the amount is positive and for a withdrawal it is negative. For a cash transaction the account attribute is nil.

Attributes only are shown for clarity.

- private

# protected

+ public

$ class attribute

UPPERCASE static (constant)

Learning Note

Annotate the diagram to highlight the associations, inheritance, aggregations and compositions, multiplicities and naviagabilities.

Bank Object Diagram


These diagrams are useful if a snapshot view of the system is required.

• Some objects are named (the two Customers and three Accounts) and some are not (the three Transactions) simply to show that either will work.

• All objects are linked by references.

• Primitive types (char, double etc.) are shown as actual values.

• All three accounts began with balances of £100.00.

• The top transaction is a cash deposit.

• The other two transactions show a transfer of £50 from ba2 to ba3

• acc1 and acc3 are Current accounts and acc2 is a Savings account.

• cust1 (Jane) has 2 accounts – ba1 and ba2

• cust2 (Anil) has 1 account – ba3.

Bank Interaction Sequence Diagram


This diagram although not incorrect in meaning is not ‘true’ UML. It tries to show too much. This has been done is order that the delegation and responsibilities of each class can be discussed. e.g.

• the deposit message sent from ba1 to ba2 is followed by the details of a possible implementation of this method.

• the withdraw method sent from ba1 to itself shows the details of a possible implementation of this method.

In BOTH cases the detail should be omitted and a separate ISD should be drawn for each method.

The Weather Station Case Study

This module is based around a number of case studies. One of these, the WeatherStation, will be implemented. as a major part of the assessment for this module. This lecture introduces the weather station case study.

Learning Outcomes

Students should be able to:

• explain all aspects of the weather station case study class diagram

• explain all aspects of the weather station documentation

Learning Resources

• UML and HTML documentation for the weather station classes

• An implementation of the weather station and test programs in java for testing purposes.

Learning Notes

Understanding the case study is essential. It is very difficult to implement a solution to a problem if you do not understand the problem itself.

This lecture will explain the case study and show how the implementation provided can be tested.

Lecture Notes

Unmanned weather stations at a particular locations around the world typically measure elements of the weather such as wind speed, temperature and precipitation (rain or snow fall) over a period of time. Each feature may be measured, for example, at hourly intervals each day over a period of a few weeks, months or years requiring the previous readings to be stored for analysis and prediction purposes. In the event of severe weather (high winds above an acceptable threshold or low temperatures below a threshold) an alarm might be raised.

Such a weather station is taken as the case study to be implemented through a number of classes as part of a java package. The design of the system has been done and has been represented as a UML class diagram showing all attributes and methods. An implementation has been constructed. The HTML documentation created using the javadoc utility is provided for guidance and the compiled code is available for testing purposes.

Teaching Notes

The class diagram has been designed to produce some intermediate classes that would be useful in their own right such as the MaxNumber and MinNumber classes and the MultiNumberStore.

The NumberStore is a simple class that stores a current value and a previous value with the associated get and set and display methods plus two constructor operators. It has been devised as a first class that may be created and tested straightforwardly. It is possible to discuss issues such as the initial values of current and previous when a NumberStore is created and their validity. If a NumberStore is created with no value and a default value of 0 is assigned how can this be differentiated from one created with an initial value of 0. When created a NumberStore has no previous value so what value should be assigned by default? Undoing the setting of a value is an operation NOT allowed. Sample classes that do allow “undo” are shown but are not part of the scenario. The issues of “undo” may be ignored but students may wish to think about them outside the lecture.

The MaxMinNumberStore extends the NumberStore by recording the highest and lowest values stored. This has been implemented by the introduction of two classes MaxNumber and MinNumber. The MaxNumber class stores a single value that is updated (if necessary) by the setMaxNumber methods to hold the max values passed to it. The MinNumber class performs the same function for a minimum value. These classes may be written and tested in isolation prior to associating them with a NumberStore via two attributes to form a MaxMinNumberStore. This introduces component testing and integration testing.

The MultiNumberStore also extends the NumberStore but by simply replacing the previous int attribute by an ArrayList allowing multiple previous value to be stored. This list could be processed in many ways such as finding the mean average value but no such processing is carried out in this case study. The change of “type” of the previous attribute means that methods such as getPrevious and toString need to be over-ridden. A couple of new methods getAllPrevious and getAllValues are also introduced to extend the behaviour of the class.

A MultiMaxMinNumberStore extends the MultiNumberStore to add the attributes to store the max and min values. Note that it would have been possible to do without the MultiNumberStore and create the MultiMaxMinNumberStore as an extension (subclass) of the MaxMinNumbnerStore. However the MultiNumberStore was seen as having potential use as a class in its own right (a design decision).

An Alarm is a simple concept. The Alarm class simply stores two threshold values. Any values above and below these cause an alarm to be raised. A value passed to an Alarm object is compared with the two threshold values and if it lies above the max or below the min then and alarm is raised which in this case is simply the display (and return) of a message. Discussion of the merits of the return string compared with the display string (both of which are implemented) by deciding where the responsibility for making the alarm know resides – with the object that send the value or with the alarm itself – is best left till later in the module.

When an Alarm is added to a MultiMaxMinNumberStore a Monitor is created. This enables values to be recorded over a period of time and an alarm to be raised whenever the current value lies out of range. This could be used in a number of other applications such as a Chemical Plant to detect levels of gas etc. or a hospital ICU detecting patient vital signs or speed of production on a production line.

In this case study the collection of three monitors for precipitation (rain, snow, hail etc), temperature and windspeed in a WeatherStation is chosen. Only the temperature monitor uses the minimum value feature of the Monitor class as the concept of too low a level of windspeed or rainfall was not seen as meaningful in this application.


Testing programs is a difficult but essential part of programming. Difficult because the objective is to find faults in the code which the programmer believes do not exist. Essential because the production of faulty software can be critical. The first lab sessions will be concerned with testing a given implementation to the case study. Designing test cases and test data is an important task that may be discussed here. The following are not rigorous definitions.

Black Box testing – testing the program against the specification of the methods

White Box testing – testing each route through each control structure of each method

Glass box testing – testing the program knowing the boundary conditions within each method

The following program is designed to test the NumberStore class.

Note that the program uses a class called TextDataReader2. This allows data to be read from a file.


Classes related in some way may be organised into a library which is java is called a Package.

Packages in the java language itself include

util with classes and methods for many standard concepts including collections such as a Stack

io with classes and methods for input and output, streams, files etc

javax including the swing classes

applet, math etc…

When writing classes a package is a useful way in which to organise work.

• Classes in a package are stored in a directory with the same name as the package.

• Each class may be imported using the directory name

• Each class definition has as its first line the name of this package

• The directory in which the package may be found must appear in the java CLASSPATH.


• must be stored in a directory

• classes must be prefaced with package

• a class may be imported with import

** This program tests a class NumberStore in the hierarchy. The objective is to predict results from the given test

data files then plan tests for other test cases.



import java.util.*;



public class NumberStoreTest

{ public static void main (String[] args) throws IOException

{// Create and display the NumberStore in its initial state

NumberStore ns = new NumberStore();


// Enter the name of the file with data in and open for reading.

TextDataReader2 kbd = new TextDataReader2();

System.out.print("Enter file name: ");

String filename = kbd.readString();

TextDataReader2 in = new TextDataReader2(filename);

// OR

// Get filename from String args[1] and open for reading

// TextDataReader2 in = new TextDataReader2(args[0]);

int n; // n will store each int as it is read from the file

n = in.readInt(); // Get first data value

while (!in.endOfStream()) // Test for end of data


ns.setValue(n); // Store the value read

System.out.println(ns); // Display the NumberStore

n = in.readInt(); // get next data value


in.close(); // Close the data file

System.out.println("Final state is " + ns);



Test Data file named “NSTestData1.txt “contains the data

23 34 45 56 -13 -23 4

There is very little to be tested in the behaviour of the NumberStore class

Predicted results are

Value 0 previous 0

Enter file name: NSTestData1.txt

Value 23 previous 0

Value 34 previous 23

Value 45 previous 34

Value 56 previous 45

Value -13 previous 56

Value -23 previous -13

Value 4 previous -23

Final state is Value 4 previous -23

Testing the MaxMinNumberStore

To test another class from the NumberStore hierarchy it is simply necessary to

• change the name of the class to MaxMinNumberStoreTest

class MaxMinNumberStoreTest

• edit the line of code that constructs the type of NumberStore and to save the file under a new name. “”

• change the name of the MaxMinNumberStore variable to mmns.

MaxMinNumberStore mmns = new MaxMinNumberStore();

The test data needs to test more this time as the max and min values need exercising.

As well as using the test data we have in NSTestData1.txt we may ask questions such as what happens if

• there is a data file no data?

• all data values are the same?

• the max value is first and the min value the last data item?

• the min value is first and the max value the last data item?

Questions such as the following are not relevant in this case as we know that there is no validation of data. What would happen if

• the data were of a number type other than int?

• the data were of a type other than a number type – e.g. char or String?

Weather Station Class Diagram.

Classes shaded in are to be implemented

Java primitive types and operations

This lecture introduces Java types and operations on those types.

Learning Outcomes

Students should be able to:

• Understand the notion of variables, types and the need for declaration

• Declare variables of types

• byte

• char

• short

• int

• long

• float

• double

• boolean

• Explain the difference between a variable, its identifier and its contents

• Use the assignment statement to assign a value to a variable

• Explain and be able to use the following operators - /, *, %, +, -, !, !=, ==, =, &&, ++, --

• Combine these operators in expressions

• Explain the concept of precedence and know the precedence for operators in Java

Learning Resources

• CSCI1003 Module booklet

• Module week by week plan

• JPadPro

Learning Notes

This module provides much in the way of the basics for developing Java programs. The use of variables and appropriate use of data types in expressions is essential to all Java applications.

Teaching Notes

This is not all the data types or operators in Java. During the lectures this should be emphasised to the students.

Lecture Material

Data types and variable declaration

Java supports a number of primitive data types. A variable is the name used for a memory location for a particular data type. All variables must be declared with a name and data type before being used. In Java we declare variables, for example, in the following way:

int j; // This declares a variable j of type integer

float fl; // This declares a variable fl of type float

char ch; // This declares ch as a single character

boolean bool; // Declares bool to be of type boolean – true or false

Each declaration will then reserve memory for the variable as in the following table:

|Type |Size |

|byte |8 bits |

|char |16 bits |

|short |16 bits signed integer |

|int |32 bits signed integer |

|long |64 bits signed integer |

|float |32 bits floating point |

|double |64 bits floating point |

|boolean |1 bit true or false |

The type of variable chosen will depend on the application and the use of the variable in the program. Typically when using integers, for example, int will suffice (32 bits allows for quite a lrrge number!!). For ‘real’ numbers float will usually suffice.

When declaring variables in Java they can also be given initial values. This is good practice where possible. For example, the following code declares and initialises four variables.

int j = 2;

float fl = 3.0f; // the f is required to indicate float

char ch = ‘y’;

boolean bool = true;

The assignment statement

To give a value to a variable we use an assignment statement. The assignment takes the form:

Variable_name = value;

For example:

i = 3;

f = 3.5f;

c = ‘y’;

will assign the value 3 to i, 3.5 to f and the character y to c.

Operators, Expressions and Operator Precedence

There are a number of operators in Java. The next table shows the main operators and their associated precedence.

|Precedence |Operator |Operand type |Operation |

|1 |++ |arithmetic |**pre or post increment |

|1 |-- |arithmetic |**pre or post decrement |

|1 |! |boolean |**NOT (logical complement) |

|2 |* |arithmetic |multiply |

|2 |/ |arithmetic |divide |

|2 |% |arithmetic |remainder |

|3 |+ |arithmetic |add |

|3 |- |arithmetic |subtract |

|3 |+ |string |string concatenation |

|4 |< |arithmetic |less than |

|4 | |arithmetic |greater than |

|4 |>= |arithmetic |greater than or equal |

|5 |== |any primitive or object |is equal to |

|5 |!= |any primitive or object |not equal to |

|6 |&& |boolean |AND |

|7 ||| |boolean |OR |

|8 |?: |boolean,any,any |conditional operator |

|9 |= |any |assignment |

|10 |*=,/=,%=,+,-= |any |**assignment with operation |

By precedence we mean the order. The smaller the number t he higher the precedence. For example if the multiplication operator appears in a statement with the AND operator (&&) the multiplication will be performed first. Operators at the same precedence level are carried out from left to right except for those marked with a ** which are performed right to left. You should use brackets to impose the order with which you want things to be done.

/* We have two integers i and j */

i = 3;

j = 5;

/* And two assignments */

x = 3.0;

y = 4.0;

Using the values of i, j, x and y from above what would be the result after each of the following expressions is evaluated:

i*j + i

x+x*y - y

(x+x)*y - y


These operators - arithmetic, relational and logical are combined in expressions to be evaluated. The use of relational and Boolean operators results in a Boolean expression (true or false).

Example expressions

x==3 || y == 4

This is evaluated to be true if either x has the value 3 or y has the value 4. (As a warning you must use == rather than = since the use of = will simply set x to the value 3 whilst == is testing whether x has the value 3)

a < 4

This evaluates to true if the variable a has a value smaller than 4 or false if the value is exactly 4 or greater than 4.

Now let us suppose that we have four variables i, j, x and y with the following values:

/* We have two integers i and j */

i = 4;

j = 6;

/* And two 'real' numbers */

x = 2.0;

y = 5.0;

What would be the result of the following (TRUE or FALSE)?

i >= 4

j != 4

(i*3 + 3) (x*x+y)

The conditional operator

The conditional operator ?: works as an if then else statement in the following way:

(boolean)? result1: result2

where the boolean is evaluated to true or false. If it is true it carries out result1 otherwise it does result2. For example: x = (bool ? 2 : 5); will assign the value 2 to x if bool is true . If bool is false then x takes the value 5.

Assignment with Operation

The assignment with operation operators, such as +=, are useful shorthand. For example, j += 2; is equivalent to j = j + 2; The statement s *= 3; is s = s*3;

Some more examples:

a = a + x may be written a += x // increment a by x

c /= 2 is the same as c = c / 2 // divide c by two

Increment & Decrement

Incrementing by exactly 1 may take four forms:

a = a + 1

a +=1

a++ // postfix increment

++a // prefix increment

The difference between a++ and ++a

a++ uses a in the expression and then increments it afterwards.

++a increments a first and then evaluates the expression.

e.g. Assume

int a = 3;

x = a++ * 5;

is equivalent to the two statements multiply by 5 then add 1 to a

x = a * 5;

a = a +1;

This results in x == 15, a == 4 where as

x = ++a * 5;

is equivalent to add 1 to a, then multiply by 5

a = a +1;

x = a * 5;

resulting in x == 20, a == 4.

There are identical decrement operators (subtracting 1 from a variable). Given

int a = 3;

what would be the effect of the following?

x = a-- * 5;

x = --a * 5;

On their own the ++ or -- shorthand is convenient. Within expressions it becomes difficult to understand and does not aid program comprehension. Avoid using these operators within expressions.

Special characters (escape sequence)

Java interprets the following sequences as special characters:

\n Newline. Cursor to start of next line

\t Tab

\r Carriage return. Cursor to beginning of current line

\\ Backslash

\' Single quote

\" Double quote

\u#### Unicode character. #### is a hexadecimal representation.

e.g. \u0041 = 'A'


System.out.println("\'A\'" + "\t=\t" + "\u0041");


'A' = A

Now see how some of these operators look in Java – make sure you understand each line:

class csci1003a


public static void main (String args[])


int i = 3;

int j = 4;

int k = 5;

int m;

float x = 3.0f;

float y = 5.0f;

float z;

boolean b = true;

System.out.println("the value of i is " + i);

i *=3;

System.out.println("the value of i is " + i);

j = i*k + k;

System.out.println("the value of j is " + j);

j = i*(k+k);

System.out.println("the value of j is " + j);

m = (b ? 4: 6);

System.out.println("the value of m is " + m);

b = false;

m = (b ? 4: 6);

System.out.println("the value of m is " + m);

j += 5;

k /= 2;

z = x/(y+y);

System.out.println("j = " + m + " k = " + k + " z = " + z );



The output from the above program is:

the value of i is 3

the value of i is 9

the value of j is 50

the value of j is 90

the value of m is 4

the value of m is 6

j = 6 k = 2 z = 0.3

Constructing the NumberStore class

Much of this module involves writing classes using UML class and other diagrams that specify the design the classes and code.

This lecture shows how to write a simple class with two attributes but with no associations, aggregation or inheritance.

The class forms the basis of most of the further work for this module

Learning Outcomes

Students should be able to

• explain the steps in creating a java class file

• explain what is meant by a package

• explain the steps to test a java class file

Learning Resources

• A class diagram for the class in the context of the package to which it belongs

• The HTML documentation for the NumberStore class involved

Learning Notes

Students will be expected to copy the code written by the tutor in the lecture and make a note of the steps to follow in order to create the class file in laboratory sessions. Students should write the java code, in the space provided in this booklet, and make any notes on the page facing the code. Students will need to take the code written here to their laboratory session in the following week.

Teaching Notes

Students should see, and copy down, the class being written live by the lecturer either by hand or using a laptop and projector and suitable environment. It is important that students are not given the code in electronic format as it is the actual process of entering the code using the editor that is important.

It is a good idea to have the code ready written BUT NOT ON AN OHP.

Stress the steps taken and details such as the location of files, the use of upper and lower case and the main syntax of java etc.

Students can make notes on the page facing the code

Lecture Notes

The class to be implemented is shown below.

Refer also to the complete package class diagram for the WeatherStation case study

The starter template for the class is given on the next page.

Add, by hand, the java code to implement this class.

/* CSCI1003 Java Programming Case Study 1

* The Students Weather Station Package

* Author:

* Login:

* Diet:

* Date:

* Program Details:



package mypackage;;

public class NumberStore

{ // Attributes

protected int value;

protected int previous;

// Constructor

public NumberStore()

{ value = 0;

previous = 0;


// Constructor

public NumberStore(int value)

{ this.value = value;

previous = 0;


// Accessing method

public int getValue()

{ return value;


// Accessing method

public int getPrevious()

{ return previous;


// Modifying method

public void setValue( int value)

{ previous = this.value;

this.value = value;


/** Returns a String of the format "Value 4 previous 0 " */

public String toString()

{ return "Value " + value + " previous " + previous;



Lecture Notes ctd.

The class is to form part of a package so the class begins with a statement to indicate this.

The name of package is the same as the name of the directory where the package classes are held.

This directory must lie in a directory named in the CLASSPATH system variable.

The package for students should lie in their home directory.

The suggested name is mypackage.

There are two protected int attributes – protected as there will be subclasses that need access to these attribute values. Had there been no subclasses these attributes would have been private.

First written are the two contructors – one parameterless to over-ride the default constructor and one with a parameter to set the initial value. The previous value is set to 0. There is no alternative at this stage. These are not methods but operators and have the same name as the class and begin with an upper case letter.

The toString( ) method should be written next to simply return a string “Value = 0”.

The class could then be tested.

import mypackage.NumberStore;

public class MyNumberStoreTest


public static void main (String args[])


NumberStore ns1 = new NumberStore();

NumberStore ns2 = new NumberStore(4);





Then the setValue method is written. This updates the previous attribute then sets the current attribute to the value passed as parameter.

The two get methods to return the attribute values are written.

The above program can test these methods simply by adding the lines






Finally the class should be tested with the given test program that was used in week 2 to test the implementation of this class provided.

Control (1) – Selection

This lecture describes how Java can be used to choose courses of action – selection.

Learning Outcomes

Students should be able to:

• understand the notion of selection

• use the if statement in Java

• use the if else construct in Java

• use the switch construct in Java

• write a simple program in Java that uses a selection of the above

Learning Resources

• CSCI1003 Module booklet

• Module week by week plan

• JPadPro

Learning Notes

This lecture provides the syntax for the very important notions of selection and control in Java.

Lecture Material

The if-statement

Branching in a Java program may be achieved using an if-statement. An if-statement has two branches. A test condition dictates which branch is executed. The result of a test condition must be a boolean value: true or false. If the condition is true then the first bra

The structure and syntax of an if statement is given below.

if (condition is true)

then execute this statement;


// the condition is false

execute this statement;

Note that the condition is in brackets. As usual semicolons terminate the statements in each branch. Indentation is used to highlight the control keywords and show that the branches are subordinate statements. This makes the structure of the program easier to identify.

Conditional statement

The else branch of an branching statement is optional.

if (condition)

then execute this statement;

This is equivalent to:

if (condition)

then execute this statement;


; // do nothing nch is followed. If the condition is false then the alternative (else) branch is followed.

Sometimes this is called a one-armed if-statement, or a conditional statement: it is executed only if the condition is true.

Example 1: A conditional statement.


if mark is at least 60 then

output a passed message

Java code

if (mark >= 60)



if the mark is at least 60 then

add 1 to the total number of passes

output a passed message

Java code

if (mark >= 60) {

numberOfPasses = numberOfPasses + 1;



In the second example there is more than one statement guarded by the condition. To implement this we must block  the statements. A block is created by enclosing the statements within braces i.e. a pair of curly brackets { } also known as braces. Note the indentation style, and the positioning of the braces.

Example 2: if-else statement

The if-else construct gives two alternative paths.

if ( mark >= 60) {

numberOfPasses = numberOfPasses + 1;






It is important to test all pathways through a program, i.e. at sometime every statement must be executed at least once.

What test values for 'mark' would you use in testing this fragment of code?

if ( mark >= 70)



if (mark >= 50)




As well as random values of mark, it is usual to test the algorithm with boundary values. These are values that are in some sense critical in the conditions that are in the statement. For example one would test the code with values of mark = 69, 70, 71, 49,50, and 51.

Common logical errors are to:

• use > instead of >=, or vice-versa

• use < instead of , or vice-versa

• use == instead of !=

The conditions in the if and if-else constructs can be quite complex, for example incorporating some of the operators already described. For example:

if (a > 3 && b == 2) c = 7;

if (a > 3 || b == 2) c = 7;

if (a*4 4.32) c = 7;

The switch statement

If there are a number of possible courses of action depending on the state of a variable then the switch statement is useful.



case value1 : // some code goes here


case value2 : // some code goes here


case value3 : // some code goes here


// as many case statements as required

default :

// default code to handle the situation where the variable is

//not one of the values in the case statements





case 1 :

tax = income*basic_rate;

System.out.println(“Your tax is ”);


case 2 :

tax = income*higher_rate;

System.out.println(“Your tax is ”);


default :

System.out.println(“You pay no tax!! ”);


Now write some Java code that carries out selection on the following:

A program is required to work out a student’s grade based on a percentage.

If a student gets less than 40% they get an ‘F’, 40-49 a ‘D’, 50-59 a ‘C’, 60-69 a ‘B’ and 70+ an ‘A’.


Calculate a student’s grade based on a percentage mark


class csci1003b


public static void main (String args[])


int mark;

char grade;

mark = 32;

if (mark < 40) grade = 'F';

else if (mark < 50) grade = 'D';

else if (mark < 60) grade = 'C';

else if (mark < 70) grade = 'B';

else grade = 'A';

System.out.println("the grade is " + grade);



Now write some code using the switch statement to display an appropriate message given a student’s grade.


Use of the switch statement


class csci1003d


public static void main (String args[])


char grade = 'C';


case 'A':

System.out.println("Congratulations the grade is " + grade);


case 'B':

System.out.println("Well done, the grade is " + grade);


case 'C':

System.out.println("Not bad, the grade is " + grade);


case 'D':

System.out.println("Not very good, the grade is " + grade);


default :

System.out.println("I am afraid you failed");





Constructing the MaxMinNumberStore class

A subclass of NumberStore called MaxMinNumberStore is required to extend the behaviour of the NumberStore class by adding the ability to record both the maximum and minimum values stored. The way that this is to be implemented is by the creation two associated classes MaxNumber and MinNumber that record one value representing the largest (or smallest) value passed to them.

This lecture shows how to construct and test the MaxNumber class then to create the MaxMinNumberStore class with only the maxNumber attribute.

Learning Outcomes

Students will be able to

• explain how to construct and test a simple class

• explain how to construct a subclass associated with another class.

Learning Resources

• The HTML documentation for the three classes involved

Learning Notes

Two major features of Object Oriented programming are inheritance and association. This lecture introduces the practical aspects of implementing both of these features.

Teaching Notes

The two classes MaxNumber and MinNumber are very similar. The lecture should focus on the MaxNumber class and its association with the MaxMinNumberStore subclass of NumberStore and allow students to appreciate the symmetry with the MinNumber class.

Elements that should be stressed include:

• the use of the if statement

• the use of extends

• the fact that the MaxMinNumberStore class methods over-ride those of the superclass NumberStore

• the use of super in the constructor method and the toString method in MaxMinNumberStore.

• the construction of the maxNumber attribute in the MaxMinNumberStore constructor

• the use of the method to set the max value in the over-ridden setValue method

Lecture Notes

The class MaxNumber has one private int attribute maxValue. It could be protected and would need to be if there were subclasses that needed access to this attribute. The class is created in a similar way to NumberStore by:

• making it part of the package

• giving it one attribute

• writing the two constructor methods. The parameterless constructor should initialise the maxValue attribute to a suitable value. This value should be as low as possible. The suggested value is the lowest value permitted by the int type. This is found via the Integer wrapper class attribute Integer.MIN_VALUE;

• writing the toString method

• writing the setMaxValue method. This will need to compare the value passed as parameter with that of the maxValue attribute and update the latter if the parameter has a higher value.

• writing the getMaxValue method.

The MaxNumber class should be tested with as used in a laboratory session in a previous week.

The MinNumber class may be created by making a copy of the file and editing the code as necessary.

The MaxMinNumberStore class is a subclass of NumberStore so will extend it.

This lecture will show how to add one of the two additional attributes, max which is an object of class MaxNumber.

As MaxNumber is part of the package mypackage it is visible to all other classes in the package and so does NOT need to be imported in order for it to be used.

The MaxNumber class

/* CSCI1003 Java Programming Case Study 1 The students Weather Station Package


* Author:

* Login:

* Diet:

* Date:

* Program Details:



package mypackage;

/** A MaxNumber object records the maximum whole number value sent to it.

public class MaxNumber

{ /** The attribute representing the maximum value */

private int maxValue;

/** Constructs a MaxNumber with the value set to the MIN_VALUE of an int */

public MaxNumber()

{ maxValue = Integer.MIN_VALUE;


/** Constructs a MaxNumber with the value set to that specified */

public MaxNumber(int initial)

{ maxValue = initial;


/** Returns the maximum value */

public int getMaxValue()

{ return maxValue;


/** Updates the maximum value to the value specified if necessary */

public void setMaxValue( int value)

{ if (value > maxValue)

{ maxValue = value;}


/** Returns the String in the format "max 100" */

public String toString()

{ return "max " + maxValue;



The MaxMinNumberStore class

/* CSCI1003 Java Programming Case Study 1 The students Weather Station Package


* Author:

* Login:

* Diet:

* Date:

* Program Details:



package mypackage;

public class MaxMinNumberStore extends NumberStore

{ /** The maximum value stored */

private MaxNumber max;

/** The minimum value stored */

private MinNumber min;

/** Constructs a MaxMinNumberStore with the current, previous values set to zero and

* max and min values set to the default values specified by MaxNumber and MinNumber */

public MaxMinNumberStore()

{ super();

max = new MaxNumber();

min = new MinNumber();


/** Constructs a MaxMinNumberStore with the current value set to that specified

* the previous value set to zero and both the max and min values set to the current value */

public MaxMinNumberStore(int value)

{ super(value);

max = new MaxNumber(value);

min = new MinNumber(value);


/** Returns the largest value that has been stored */

public int getMaxValue()

{ return max.getMaxValue();


/** Returns the smallest value that has been stored */

public int getMinValue()

{ return min.getMinValue();


/** Sets the current value stored in the NumberStore to the value specified

* and updates the max and min values if necessary */

public void setValue( int value)

{ super.setValue(value);




/** Returns the String of the format "Value 4 previous 0 max 100 min -5" */

public String toString()

{ return super.toString() + " " + max + " " + min;



The Java Collection classes, ArrayList & Wrapper Class Interfaces

Learning Outcomes

Students should be able to:

• Explain the notion of a collection

• Explain how ArrayList works

• Use ArrayList to solve problems

• Explain the notion of Wrapper classes

Learning Resources

• CSCI1003 Module booklet

• Module week by week plan

• JpadPro

• The Java API

Learning Notes

Clearly, ArrayList is only one example class for handling collections. Students should be made aware of this and encouraged to use the API to look at others.


Collections are important structures in Java programming. We often have to deal with a set or group of objects or values. Collection classes have a variety of methods that allow objects to be added, retrieved, and removed from the collection. There are many ways that objects can be organised (stored) in a collection: list, stack, queue, or tree, are some examples of data collections.

In Java, then, a collection is a data structure that holds other objects, known as its elements. The collection interfaces provide various operations that can be performed on collections. Two methods of particular interest are the add and iterator methods.

The add method

The add method adds an object to the collection. The add method returns true if adding the object actually changed the collection; false, if the collection is unchanged. For example, if you try to add an object to a set and the object is already present, then the add request is rejected since sets reject duplicates.

The iterator method

The iterator method returns an object that implements the Iterator interface-- we will describe that interface in a moment. You can use the iterator object to visit the elements in the container one by one.

The Iterator interface has three fundamental methods:

Object next()

boolean hasNext()

void remove()

By repeatedly calling the next method, you can visit the elements from the collection one by one. If you want to inspect all elements in a container, you request an iterator and then keep calling the next method while hasNext returns true.

Iterator iter = c.iterator();

while (iter.hasNext())

{ Object obj =;

do something with obj


Because the collection and Iterator interfaces are generic, you can write utility methods that operate on any kind of collection. For example, here is a generic print method that prints all elements in a collection.

public static void print(Collection c)

{ System.out.print("[ ");

Iterator iter = c.iterator();

while (iter.hasNext())

System.out.print( + " ");



Here is a method that adds all objects from one collection to another:

public static boolean addAll(

Collection to, Collection from)

{ Iterator iter = from.iterator();

boolean modified = false;

while (iter.hasNext())

if (to.add(

modified = true;

return modified;


Recall that the add method returns true if adding the element modified the collection. You can implement these utility methods for arbitrary collections because the Collection and Iterator interfaces supply fundamental methods such as add and next.

The List Interface

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.


ArrayList is a resizable-array implementation of the List interface. It implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added an ArrayList, its capacity grows automatically.

The Java documentation for the ArrayList can be found of the following page.

|Constructor Summary | |

|ArrayList() | |

|          Constructs an empty list. | |

|ArrayList(Collection c) | |

|          Constructs a list containing the elements of the specified collection, in the order they are returned by the | |

|collection's iterator. | |

|ArrayList(int initialCapacity) | |

|          Constructs an empty list with the specified initial capacity. | |


|Method Summary | |

| void |add(int index, Object element) |

| |          Inserts the specified element at the specified position in this list. |

| boolean |add(Object o) |

| |          Appends the specified element to the end of this list. |

| boolean |addAll(Collection c) |

| |          Appends all of the elements in the specified Collection to the end of this list, in the order that they |

| |are returned by the specified Collection's Iterator. |

| boolean |addAll(int index, Collection c) |

| |          Inserts all of the elements in the specified Collection into this list, starting at the specified |

| |position. |

| void |clear() |

| |          Removes all of the elements from this list. |

| Object |clone() |

| |          Returns a shallow copy of this ArrayList instance. |

| boolean |contains(Object elem) |

| |          Returns true if this list contains the specified element. |

| void |ensureCapacity(int minCapacity) |

| |          Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the |

| |number of elements specified by the minimum capacity argument. |

| Object |get(int index) |

| |          Returns the element at the specified position in this list. |

| int |indexOf(Object elem) |

| |          Searches for the first occurence of the given argument, testing for equality using the equals method. |

| boolean |isEmpty() |

| |          Tests if this list has no elements. |

| int |lastIndexOf(Object elem) |

| |          Returns the index of the last occurrence of the specified object in this list. |

| Object |remove(int index) |

| |          Removes the element at the specified position in this list. |

|protected  void |removeRange(int fromIndex, int toIndex) |

| |          Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, |

| |exclusive. |

| Object |set(int index, Object element) |

| |          Replaces the element at the specified position in this list with the specified element. |

| int |size() |

| |          Returns the number of elements in this list. |

| Object[] |toArray() |

| |          Returns an array containing all of the elements in this list in the correct order. |

| Object[] |toArray(Object[] a) |

| |          Returns an array containing all of the elements in this list in the correct order. |

| void |trimToSize() |

| |          Trims the capacity of this ArrayList instance to be the list's current size. |

The following program creates a shopping list by adding some elements to an ArrayList and then gets them for display purposes (note that we use an array here which you come onto later in the module).

/* The Shopping List */

import java.util.*;

public class ShoppingList

{ private String food[] = {"coffee", "milk", "sugar"};

public ShoppingList()

{ ArrayList sList = new ArrayList()

for (int k = 0; k < food.length; k++)


System.out.println("\n Shopping List\n");

for (int k = 0; k < sList.size(); k++)

System.out.println(sList.get(k) + " ");


public static void main (String args[])


new ShoppingList();



The next program takes the list, removes sugar and adds cat food and a bottle of wine.

/* The Shopping List */

import java.util.*;

public class ShoppingList

{ private String food[] = {"coffee", "milk", "sugar"};

public ShoppingList()

{ ArrayList sList = new ArrayList();

for (int k = 0; k < food.length; k++)


System.out.println("\n Shopping List\n");

for (int k = 0; k < sList.size(); k++)

System.out.println(sList.get(k) + " ");

// now remove sugar from the list and add cat food


sList.add("Cat Food");

sList.add("Bottle of Wine");

System.out.println("\n New Shopping List\n");

for (int k = 0; k < sList.size(); k++)

System.out.println(sList.get(k) + " ");


public static void main (String args[])


new ShoppingList();



Wrapper Classes

Java Collection classes are containers for objects. Java primitive types such as int, char, boolean etc. are NOT objects. Java provides some classes which provide objects as ‘wrappers’ for these primitive types.

The class java.lang.Integer  is a class that can be used to ‘wrap’ an int value in an 'Object cloak'.

Integer intObj = new Integer(6);

This statement creates an object of class Integer. The attribute of an Integer object is the value it wraps. This value cannot be modified Class Integer does, however, provide some useful methods: Two that are used a lot are:

public static int parseInt(String s)

//converts a string to an integer,

public int intValue()

//Returns the value of Integer object as an int.

There are two constructors.

• One takes an integer as a parameter.

• The other takes a string representation of an integer.

public Integer(int value)

public Integer(String s)

Constructing the MultiNumberStore class

A NumberStore that stores many previous values rather than just the most recent one would provide data for analysis. In this case study the analysis is not performed but the store of multiple previous values is implemented.

This requirement provides a typical and useful application of a java collection class. Using such a class provides methods for adding, displaying and otherwise processing the data. In this example an ArrayList is chosen but a Vector or an Array would be possible.

Learning Outcomes

Students should be able to

• use a java collection class to solve a problem.

• explain the behaviour of java collection class methods

• explain the use of iterators with java collection classes

• explain the use of Wrapper classes in connection with java collection classes

• implement and explain a MultiNumberStore class

Learning Resources

• Java HTML documentation for the java collection class ArrayList

• Java HTML documentation for class ListIterator.

Learning Notes

There are three major concepts in this lecture: collection classes, iterators and wrapper classes all of which are needed to implement a class containing an aggregation. The class MultiNumberStore extends the original NumberStore by over-riding some methods and adding others.

Teaching Notes

There is a lot to cover in this lecture but the essential goal is to have written the code for most (if not all) of the MultiNumberStore class.


• Discussion of the collection class hierarchy is important but should be limited.

• Discussion of the Interface classes is important but should be limited.

• Brief explanations of comparable, serializable and clonable may be given but only for background and completeness.

• The protected boolean attribute hasValue deals with a NumberStore with no current value. Set to true or false by the constructor operators.

• Both constructors create a new ArrayList which is empty. There is no need for a boolean hasPrevious attribute as inspection of the ArrayList size will demonstrate if it has a previous value via a hasPrevious method that returns true or false.

• An ArrayList can hold objects BUT NOT primitive types and hence the Wrapper class Integer is used.

• The methods to setValue and getPrevious need to use the Wrapper casting methods to convert from int to Integer and from Integer to int.

• The setValue method sets hasValue to true.

• The toString method is supplemented by two further methods each returning a String object representing just the ArrayList of previous data (getAllPrevious) and the current value plus all previous data (getAllData)

Lecture Notes

The Java collection class hierarchy is shown below

implements means that the class must implement methods specified by an Interface – Java’s mechanism for allowing multiple inheritance.

Collections include HashTable, Stack, LinkedList, Tree etc.

The ArrayList is chosen for its functionality and simplicity.

class java.lang.Object

class java.util.AbstractCollection (implements java.util.Collection)

2. class java.util.AbstractList (implements java.util.List)

3. class java.util.AbstractSequentialList

4. class java.util.LinkedList (implements java.lang.Cloneable, java.util.List,

5. class java.util.ArrayList (implements java.lang.Cloneable, java.util.List,

6. class java.util.Vector (implements java.lang.Cloneable, java.util.List,

7. class java.util.Stack

8. class java.util.AbstractSet (implements java.util.Set)

9. class java.util.HashSet (implements java.lang.Cloneable,, java.util.Set)

10. class java.util.TreeSet (implements java.lang.Cloneable,, java.util.SortedSet)

class java.util.AbstractMap (implements java.util.Map)

12. class java.util.HashMap (implements java.lang.Cloneable, java.util.Map,

13. class java.util.TreeMap (implements java.lang.Cloneable,, java.util.SortedMap)

14. class java.util.WeakHashMap (implements java.util.Map)

class java.util.Arrays

class java.util.BitSet (implements java.lang.Cloneable,

class java.util.Calendar (implements java.lang.Cloneable,

18. class java.util.GregorianCalendar

class java.util.Collections

class java.util.Date (implements java.lang.Cloneable, java.parable,

class java.util.Dictionary

22. class java.util.Hashtable (implements java.lang.Cloneable, java.util.Map,

23. class java.util.Properties

package mypackage;

import java.util.ArrayList;

import java.util.ListIterator;

/** A MultiNumberStore object records the current data value and all

previous values that are all whole numbers

public class MultiNumberStore extends NumberStore

{/** All previous values stored */

protected ArrayList previous;

protected boolean hasValue;

/** Constructs a NumberStore with the no current value set and no

previous values */

public MultiNumberStore()

{ hasValue = false;

previous = new ArrayList();


/** Constructs a NumberStore with the current value set to that

specified and no previous values */

public MultiNumberStore(int value)

{ this.value = value;

hasValue = true;

previous = new ArrayList();


/** Returns the current value stored or zero if none */

public int getValue()

{ if (hasValue)

return value;


return 0;


/** Returns the most recent previous value that was stored. If none

then 0 is returned */

public int getPrevious()

{ if (hasPrevious())

return ((Integer) previous.get(0)).intValue();


return 0;}

/** Sets the current value stored in the NumberStore to the value

specified and records the previous value if there was one */

public void setValue( int value)

{ if (hasValue)

previous.add(0,new Integer(this.value));

this.value = value;

hasValue = true;


/** Returns true if there is previous data */

protected boolean hasPrevious()

{ return (previous.size() > 0);


/** Returns the String of the format "Value 4 previous 0 " */

public String toString()

{ String str = "Value " ;

if (hasValue)

str += value + " - previous ";


str += "None - previous ";

if (this.hasPrevious())

str += this.getPrevious();


str += "None";

return str;


/** Returns all previous values in a String of the format


public String getAllPrevious()

{ String previousData = "< ";

ListIterator it = previous.listIterator();

while (it.hasNext())

previousData += + " ";

previousData += ">";

return previousData;


/** Returns the current and all previous values in a String of the

format */

public String getAllData()

{ String allData = "< " + value + " ";

ListIterator it = previous.listIterator();

while (it.hasNext())

allData += + " ";

allData += ">";

return allData;



Arrays and Iteration using for loops

Learning Outcomes

Students should be able to

• Explain and use one-dimensional arrays

• Use for loops to process the elements of an array

• Explain potential error states with array bounds and loop bounds

• Explain the syntax of arrays and the basic for loop

Learning Resources

Original programs for lecture demonstrations (prior to any changes made during lectures) are available on: csci1003.arrays&loops

Learning Notes

Arrays are available in most programming languages, so it is worthwhile to learn about them now, especially as most other languages do not have the variety of data structures provided with the Java api, nor the readily available methods to manipulate them. However, you must not assume that arrays are implemented in exactly the same way in all languages, even though the principles are the same.

Iteration techniques, using loops, are also available in all structured programming languages. Java has three types of loops, of which one is described in this lecture.

Teaching Notes

Concentrate on one-dimensional arrays. Tables will be covered in the next lecture.

Discuss potential problems with array bounds:

First element is index 0

Last element is index length-1

Run time error if attempt to use index out of bounds

Must not assume arrays are implemented in all languages in the same way:

They don’t all start at index 0

Some allow negative indexes

They don't all automatically initialise the values of primitive types to 0.

Some languages (including C) do not give run-time error when attempting to access elements outside array bounds.

It is always safest for the programmer to initialise all variables (including array elements) rather than rely on the programming language doing it for you.

See also discussion questions with example program at end of Learning Materials.

Teaching Material


An Array is a linear collection of values or object references. Most programming languages have arrays.

• An array is conceptually similar to an ArrayList.

For example, an array of 10 integers:

| |0 |1 |2 |3 |4 |5 |6 |7 |8 |9 |

|num |34 |2 |-9 |45 |100 |-99 |23 |62 |0 |51 |

• The items are in a list or table,

• Items are accessed by their position in the list.

Unlike an ArrayList, there are no useful methods associated with an array. The programmer must manipulate it explicitly. Arrays have a special syntax (notation) to create new instances and to access components (or elements)

Like primitive types, arrays are treated in a special way in the Java language. Nevertheless, an array variable is a reference to an object.

Array Notation

| |0 |1 |2 |3 |4 |5 |6 |7 |8 |9 |

|num |34 |2 |-9 |45 |100 |-99 |23 |62 |0 |51 |

Square brackets are used to access components of the array.

num[ 0 ] is 34

num[ 1 ] is 2

num[ 2 ] is -9

num[ 3 ] is 45

num[ 4 ] is 100

num[ 5 ] is -99

num[ 6 ] is 23

num[ 7 ] is 62

num[ 8 ] is 0

num[ 9 ] is 51

• In Java, the numbering of array elements always starts with index 0.

An array is a mapping from the index range (e.g. 0..9) to a value. The components of an array may be primitive values or objects (more correctly object references).

Declaration and instantiation

int[] num ; // an array of integers

This declaration indicates that num refers to an array object. But the array has not been created yet.

num = new int[10]; // create an array of 10 integers

• This statement allocates computer memory for an array with 10 components.

• num.length is 10

• Once created, the size of an array cannot be altered.

• Each component of this array is an integer, and is automatically initialised to zero.

• NOTE in num.length length is a built in attribute of an array num not a method of the class Array

| |0 |1 |2 |3 |4 |5 |6 |7 |8 |9 |

|num |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |

• The 10 elements of the array are indexed with 0..9 .

• num is a reference  to the array object, (its address in memory).

Array Of Objects

The components of an array may be primitive types or object references. But only the type of values in the array declaration may be stored in the array. The following declarations are for an array of four NumberStore objects.

NumberStore[] store ;

store = new NumberStore[4] ;

| |0 |1 |2 |3 |

|store |null |null |null |null |

• The array of NumberStore is automatically initialised with null references. The NumberStore instances have not been created!

• To construct each NumberStore instance we need to invoke the constructor on each component of the array.

store[0] = new NumberStore();

store[1] = new NumberStore();

store[2] = new NumberStore();

store[3] = new NumberStore();

More shortcuts:

| |0 |1 |2 |3 |4 |5 |6 |7 |8 |9 |

|Num |0 |0 |0 |0 |0 |0 |0 |0 |0 |0 |

This array could have been declared and created in one statement:

int[] num = new int[10] ;

• Every instance of an array has a length attribute, i.e. an array knows  its size.


Note: num[num.length - 1] is the last element in the array.

The statements:

int[] num = new int[10] ;

num[ 0 ] = 34; num[ 1 ] = 2; num[ 2 ] = -9;

num[ 3 ] = 45; num[ 4 ] = 100; num[ 5 ] = -99;

num[ 6 ] = 23; num[ 7 ] = 62; num[ 8 ] = 0;

num[ 9 ] = 51;

create and define this array

| |0 |1 |2 |3 |4 |5 |6 |7 |8 |9 |

|num |34 |2 |-9 |45 |100 |-99 |23 |62 |0 |51 |

A quicker way to create and initialise an array is this:

int[] num = { 34, 2, -9, 45, 100, -99, 23, 62, 0, 51 };

Usually values are read into arrays from data streams or generated in a program, but this is handy for testing, or setting up look-up tables.

Array processing.

In order to process each element of an array (say, array a) in turn, we use a loop which steps through the indexes of the array. So we need to process the elements from a[0] up to and including a[a.length - 1].

Java provides three ways of writing loops. The easiest to use when processing arrays is the for loop and its general form for processing all the elements in an array a is:

for (int i=0; i < a.length; i++){

...process a[ i ]...;


Here is an example program using a one-dimensional array and for loops to process all the elements.

1 class ArrayDemo1 {

2 public static void main (String[] arg) {

3 //create an array of int values and print it out

4 int[] a = {2, 3, 5, 8, 13, 21, 1, 3, 7, 9};


6 System.out.print("a = ");


11 //find the minimum value in the array

12 int amin = a[0];

13 System.out.println("Current value of amin = " + amin);

14 for (int i=1; i ................

In order to avoid copyright disputes, this page is only a partial summary.

Online Preview   Download