Sunteți pe pagina 1din 223

CDOP3103

Introduction to Object-Oriented Approach

Copyright © Open University Malaysia (OUM)


CDOP3103
INTRODUCTION TO
OBJECT-ORIENTED
APPROACH
Karin Kolbe
Dr Geoffrey Phipps
Assoc Prof Dr Nantha Kumar Subramaniam
Marini Abu Bakar
Dr Sufian Indris
Norleyza Jailani
Roziah Latih

Copyright © Open University Malaysia (OUM)


Project Director: Prof Dato’ Dr Mansor Fadzil
Open University Malaysia

Module Writers: Karin Kolbe


Dr Geoffrey Phipps
The Open University of Hong Kong

Assoc Prof Dr Nantha Kumar Subramaniam


Open University Malaysia

Marini Abu Bakar


Dr Sufian Indris
Norleyza Jailani
Roziah Latih
University Kebangsaan Malaysia

Enhancer: Hidayah Elias

Developed by: Centre for Instructional Design and Technology


Open University Malaysia

First Edition, August 2008


Second Edition, August 2017
Third Edition, April 2018
Copyright © The Open University of Hong Kong and Open University Malaysia,
April 2018, CDOP3103
All rights reserved. No part of this work may be reproduced in any form or by any means without
the written permission of the President, Open University Malaysia (OUM).

Copyright © Open University Malaysia (OUM)


Table of Contents
Course Guide ixăxix

Topic 1 Introduction to Object Orientation 1


1.1 Object Orientation 2
1.2 Object-oriented Concepts 4
1.2.1 Objects 4
1.2.2 Encapsulation 10
1.2.3 Object Interfaces 11
1.2.4 Sending Message 14
1.2.5 Class 16
1.2.6 Inheritance 19
1.3 Object-oriented Systems Modelling and UML 22
Summary 24
Key Terms 26

Topic 2 Static Modelling with UML 27


2.1 Use Case 28
2.1.1 Levels and Types of Requirements 29
2.1.2 Challenges of Writing Requirements 30
2.1.3 Types of Roles 33
2.2 Writing Use Cases 34
2.2.1 Goals and Levels of Use Cases 38
2.3 Use Case Diagrams 41
2.4 Activity Diagrams 43
2.5 Potential Problems with Use Cases 45
2.5.1 How to Deal with Hundreds of Use Cases 46
2.6 Relating Use Cases 47
2.6.1 The Include Relationship 49
2.6.2 The Extend Relationship 52
2.6.3 The Generalise Relationship 54
2.6.4 Business Rules and Use Cases 55
2.7 Analysis Class Diagram 58
2.7.1 Conceptual Classes 61
2.7.2 Identification of Conceptual Classes 62
2.7.3 Issues in Identifying Conceptual Classes 65
2.7.4 Specification Conceptual Classes 65
2.7.5 Associations 66
2.7.6 Identifying Associations 67

Copyright © Open University Malaysia (OUM)


iv  TABLE OF CONTENTS

2.7.7 Multiplicity 70
2.7.8 Aggregation and Composition Relationships 71
2.7.9 Other Issues of Association 72
2.7.10 Attributes 73
Summary 76
Key Terms 77

Topic 3 Dynamic Modelling with UML 78


3.1 State Diagrams 79
3.1.1 Showing Super States 82
3.2 Collaboration Diagram 83
3.3 Sequence Diagram 86
3.4 Designing For Responsibilities 88
Summary 92
Key Terms 93

Topic 4 Introduction to Java 94


4.1 Java Environment 95
4.2 Characteristics of Java 96
4.3 Tools To Develop Java Programs 97
4.4 Writing Java Programs 98
4.5 Writing Text-based Application Using Structured 99
Approach
Summary 104
Key Terms 104

Topic 5 Basic Constructs of Java 105


5.1 Data Types 106
5.1.1 Integer 106
5.1.2 Real 107
5.1.3 Characters 108
5.1.4 Boolean 110
5.2 Variables, Declaration and Constant 111
5.2.1 Name of Variable 112
5.2.2 Variable Declaration 114
5.2.3 Constant 115
5.2.4 Comment 116
5.3 Assignment Statement, Initial Value and Changing 118
Numeric Value
5.3.1 Assignment Statement 118
5.3.2 Initial Value 119
5.3.3 Changing Numeric Value 120

Copyright © Open University Malaysia (OUM)


TABLE OF CONTENTS  v

5.4 Operator 122


5.4.1 Arithmetic 123
5.4.2 Multiple Assignments 124
5.4.3 Addition and Reduction 124
5.4.4 Relational Operators 125
5.4.5 Boolean Operators 128
Summary 130
Key Terms 130

Topic 6 Control Structure and Method 131


6.1 Control Structure 132
6.2 Selection Structure: If, Else, Switch, Break 132
6.2.1 The If, Else Statements 133
6.2.2 Switch Statement 139
6.3 Repetitive Structure: While, Do-while, For 142
6.3.1 The While and Do-while Statement 143
6.3.2 The For Statement 144
6.3.3 The Break and Continue Statements 146
6.3.4 Nested Loops 147
6.3.5 Compound Statements 148
6.4 Method 151
6.4.1 Types of Method in Java 151
6.4.2 Creating a Method 152
6.4.3 Calling a Method 155
6.4.4 Method Overloading 157
Summary 158
Key Terms 159

Topic 7 Array, String and Input Reading 160


7.1 Array 161
7.1.1 Array Declaration 162
7.1.2 Array as Object 164
7.2 String 168
7.2.1 String Declaration 169
7.2.2 String Operation 169
7.3 Using Scanner to Capture Input 173
7.4 Output Formatting 174
Summary 175
Key Terms 176

Answers 177

Copyright © Open University Malaysia (OUM)


vi  TABLE OF CONTENTS

Copyright © Open University Malaysia (OUM)


COURSE GUIDE

Copyright © Open University Malaysia (OUM)


Copyright © Open University Malaysia (OUM)
COURSE GUIDE  ix

COURSE GUIDE DESCRIPTION


You must read this Course Guide carefully from the beginning to the end. It tells
you briefly what the course is about and how you can work your way through
the course material. It also suggests the amount of time you are likely to spend in
order to complete the course successfully. Please keep on referring to the Course
Guide as you go through the course material as it will help you to clarify
important study components or points that you might miss or overlook.

INTRODUCTION
CDOP3103 Introduction to Object-oriented Approach is one of the courses
offered at Open University Malaysia (OUM).

COURSE AUDIENCE
This course is offered to all students undertaking the Diploma in Information
Technology (DIT). This module aims to introduce the concepts of object
orientation, systems modelling using UML and basic Java programming.

As an open and distance learner, you should be acquainted with learning


independently and being able to optimise the learning modes and environment
available to you. Before you begin this course, please ensure that you have the
right course materials, and understand the course requirements as well as how
the course is conducted.

STUDY SCHEDULE
It is a standard OUM practice that learners accumulate 40 study hours for every
credit hour. As such, for a three-credit hour course, you are expected to spend
120 study hours. Table 1 gives an estimation of how the 120 study hours could be
accumulated.

Copyright © Open University Malaysia (OUM)


x  COURSE GUIDE

Table 1: Estimation of Time Accumulation of Study Hours

Study
Study Activities
Hours
Briefly go through the course content and participate in initial discussions 5
Study the module 60
Attend 3 to 5 tutorial sessions 10
Online participation 12
Revision 18
Assignment(s), Test(s) and Examination(s) 15
TOTAL STUDY HOURS ACCUMULATED 120

COURSE OUTCOMES
By the end of this course, you should be able to:

1. Explain the fundamental concepts of object orientation;

2. Describe how systems modelling can be done using UML in order to


develop object-oriented systems;

3. Write UMLÊs use case, draw use case diagrams, activity diagrams, analysis
diagrams, sequence diagrams, collaboration diagrams and state diagrams
for a given problem; and

4. Write Java programs in a structured manner.

COURSE SYNOPSIS
This course is divided into 7 topics. The synopsis for each topic can be listed as
follows:

Topic 1 will introduce the concepts of object orientation. In particular, you will
learn about the object and its characteristics, class, message passing mechanisms
between objects, object interface, encapsulation and inheritance. Besides that, you
also will be introduced to how UML is fit to develop object-oriented systems.
Specifically, you will be shown some of the main UML diagrams that can be used
to perform static and dynamic modelling. This topic includes many examples to
reinforce your understanding on object orientation.

Copyright © Open University Malaysia (OUM)


COURSE GUIDE  xi

Topic 2 explains how a system can be modelled from two angles ă static and
dynamic aspects. The static characteristic of a system is essentially the structural
aspect of the system. The static characteristics define what parts the system is
made up of. In this topic we will briefly introduce to you some of the UML
notations used to visualise the static features of system using use case, use case
diagrams and analysis class diagrams.

Topic 3 will focus on dynamic modelling using UML. Software design is about
behaviour and behaviour is dynamic. The ways in which a system behaves in
response to certain events or actions are the dynamic characteristics of a system.
Therefore, an emphasis on dynamic models is very important in designing a
system.

Topic 4 gives an overview about Java including its advantages. The types of Java
programs with their sample codes will be elaborated in this topic. In addition,
learners will be exposed to how to compile and execute a Java program.

Topic 5 includes two basic blocks of programming ă data and instructions. To


work with data, you need to understand variables and data types; to work with
instructions, you need to understand control structures and subroutines. This
topic will focus on how variables, data types and its related concepts can be
implemented in Java.

Topic 6 discusses the two basic aspects of programming ă data and instructions,
as highlighted in Topic 2. As mentioned before, to work with data, you need to
understand variables and data types; to work with instructions, you need to
understand control structures and methods. This topic will focus on control
structures (such as if-else statements, switch-case statements and loops) and
methods.

Topic 7 highlights three important constructs in Java that enable us to write


complete and comprehensive Java programs. These include programs that will
process the marks of 100 students and determine the highest and lowest marks;
determine number of characters in a string; and enable a user to key in data
during program run-time. The constructs of array, string and input reading will
be discussed in this topic.

Copyright © Open University Malaysia (OUM)


xii  COURSE GUIDE

ADDITIONAL READING
There will be a number of additional „short‰ readings for certain topics as shown
in the following table. These readings are provided as part of your course
package in myINSPIRE.

Topic Reading
Topic 1 ă
Topic 2 Reading 2.1 ă Reading 2.4
Topic 3 Reading 3.1 ă Reading 3.2
Topic 4 ă
Topic 5 ă
Topic 6 ă
Topic 7 ă

It is compulsory for learners to read these readings as it will give them a solid
understanding of the particular concepts related to the course. These readings are
part of the syllabus. Hence, it can be used for tests and in the final examination.

TEXT ARRANGEMENT GUIDE


Before you go through this module, it is important that you note the text
arrangement. Understanding the text arrangement will help you to organise your
study of this course in a more objective and effective way. Generally, the text
arrangement for each topic is as follows:

Learning Outcomes: This section refers to what you should achieve after you
have completely covered a topic. As you go through each topic, you should
frequently refer to these learning outcomes. By doing this, you can continuously
gauge your understanding of the topic.

Self-Check: This component of the module is inserted at strategic locations


throughout the module. It may be inserted after one sub-section or a few sub-
sections. It usually comes in the form of a question. When you come across this
component, try to reflect on what you have already learnt thus far. By attempting
to answer the question, you should be able to gauge how well you have
understood the sub-section(s). Most of the time, the answers to the questions can
be found directly from the module itself.

Copyright © Open University Malaysia (OUM)


COURSE GUIDE  xiii

Activity: Like Self-Check, the Activity component is also placed at various


locations or junctures throughout the module. This component may require you
to solve questions, explore short case studies, or conduct an observation or
research. It may even require you to evaluate a given scenario. When you come
across an Activity, you should try to reflect on what you have gathered from the
module and apply it to real situations. You should, at the same time, engage
yourself in higher order thinking where you might be required to analyse,
synthesise and evaluate instead of only having to recall and define.

Summary: You will find this component at the end of each topic. This component
helps you to recap the whole topic. By going through the summary, you should
be able to gauge your knowledge retention level. Should you find points in the
summary that you do not fully understand, it would be a good idea for you to
revisit the details in the module.

Key Terms: This component can be found at the end of each topic. You should go
through this component to remind yourself of important terms or jargon used
throughout the module. Should you find terms here that you are not able to
explain, you should look for the terms in the module.

References: The References section is where a list of relevant and useful


textbooks, journals, articles, electronic contents or sources can be found. The list
can appear in a few locations such as in the Course Guide (at the References
section), at the end of every topic or at the back of the module. You are
encouraged to read or refer to the suggested sources to obtain the additional
information needed and to enhance your overall understanding of the course.

PRIOR KNOWLEDGE
No prior knowledge required.

ASSESSMENT METHOD
Please refer to myINSPIRE.

Copyright © Open University Malaysia (OUM)


xiv  COURSE GUIDE

REFERENCES
Booch, G., Rumbaugh, J., & Jacobson, I. (1999). The unified modeling language
user guide. Upper Saddle River, NJ: Addison-Wesley.

Böhm, C., & Jacopini, G. (1966). „Flow diagrams, Turing Machines and
Languages with only Two Formation Rules‰, Comm. of the ACM, 9(5): 366ă
371.

Chitnis, M., Tiwari, P., & Lakshmi Ananthamurthy. (2002). UML Overview.
Available from:
http://www.developer.com/design/article.php/1553851

Eck, D. J. (2009). Introduction to programming using Java. Orange Grove Texts


Plus.

Larman, C. (2002). Applying UML and patterns: An introduction to object-


oriented analysis and design and the unified process (2nd ed.). Upper
Saddle River, N.J.: Prentice Hall PTR.

ONLINE DISCUSSION
Online discussion with your tutors and fellow students is one of the important
components of teaching and learning activities at OUM. To help you to go
through your online discussion, OUM has developed myINSPIRE. The system
has a number of functionalities which enable the students to access OUMÊs
digital library as well as communicate with the tutors and their fellow students.
We strongly advise you to use this system.

Assignment
For CDOP3103 ă Introduction to Object-oriented Approach, you are required to
do one assignment. The objective of the assignment is:

1. To provide a mechanism for you to check your progress and make sure that
you have met certain learning objectives;

2. To provide you with the chance to demonstrate your understanding of the


course materials; and

3. To provide an opportunity for you to apply what you have learned by


completing some tasks and case studies.

Copyright © Open University Malaysia (OUM)


COURSE GUIDE  xv

How to Do Your Assignments


Please carefully read through the assignment question to make sure you
understand what is required before attempting an assignment. If you do not
understand an assignment or the instructions, please contact your tutor. Once
you have completed each assignment, you must send it to your tutor. Please
make sure that each assignment reaches your tutor on or before the deadline (see
the following assignment schedule). You must be careful when you are using
other references in your assignments. Please do not commit plagiarism. If you
commit plagiarism, you will be penalised severely. Plagiarism is theft of
somebody elseÊs work or ideas. This applies just as much to using the work of
other students as it does to authors of books. However, you may include
parenthetical references to the works you cite, for example, (Stott, 2002). You
should include a section at the end of your assignment called „References‰ where
the full name, title, date and place of the publication of any references that you
have used appear. The way to cite a reference is:

Stott, V. (2002). Web server technology (2nd ed.). London, England: ABC
Publishing.

Assignment Schedule
The assignment will be posted to myINSPIRE before Tutorial 1.

Learners are required to submit the assignment during Tutorial 4. Learners will
get their assignment marks from their tutors during Tutorial 5. Please make sure
to ask for the marks during Tutorial 5. The tutor will post his feedback of your
assignment answer online via myINSPIRE.

Tutorials
The course includes five tutorial meetings of two hours each ă 10 contact hours in
total. The tutorials are conducted to provide an opportunity for you to meet your
tutors and discuss important points in the module. In addition, you have an
opportunity to share your study experiences and difficulties in your peer-to-peer
group discussions. Although the tutorials are not compulsory, you are
encouraged to attend the tutorial meetings as far as possible. It is strongly
recommended that you attend all tutorials, as they will provide considerable
assistance in your study of this course. Moreover, you will have the chance to
meet with other distance learners who are taking the same course.

Copyright © Open University Malaysia (OUM)


xvi  COURSE GUIDE

Tutorial Guideline (for Tutors)


The following chart gives a general guideline on the topics to be discussed in
each tutorial:

Table 2

Topic Tutorial
1 Tutorial 1
2 Tutorial 2
3 Tutorial 3
4 Tutorial 4
5 Tutorial 4
6 Tutorial 5
7 Tutorial 5

Case Studies
Topic 2 ă Topic 3 in this module will make use of the following two case studies.
You are required to read and understand the following case studies prior to
learning Topic 2 and Topic 3.

Case Study 1: VictoriaÊs Videos


(This is an introduction to VictoriaÊs Videos, an example that you will use in
many activities and discussions in Topic 2 and Topic 3.

VictoriaÊs Videos is a large video shop with thousands of members and videos. It
is a single shop and Victoria has no plans to expand to multiple branches.

Victoria maintains a stock of approximately 50,000 videos ă each year roughly a


third of the videos are sold or destroyed and new ones are bought. Every video
has a classification (general G, parental guidance PG, mature audiences MA, and
restricted R). Members must be over 18 to borrow R videos. Every video also has
a category: Romance, General, Sci-Fi, Foreign Language and Children.

Copyright © Open University Malaysia (OUM)


COURSE GUIDE  xvii

You have to be a member to borrow a video. There are approximately 10,000


members, and the number increases by approximately 2,000 each year, but some
members have not borrowed for years. When a new person requests to become a
member, they must show their driverÊs license or other photo ID. The minimum
age is 16 years old. A member can borrow any number of videos, as long as they
have no overdue videos, and it is also possible to reserve a video. There are fines
for overdue videos.

The length of time that a video can be borrowed depends on the video. New
releases are only lent out overnight, current releases are for three-day hire and
the rest are for a week.

MembersÊ birthdays are marked with a special letter inviting them to borrow any
video of their choice for a week for free.

Every three months the shop does a stocktake. Any missing videos are updated
to show them as „Missing‰.

The system Victoria has includes three very good intelligent cash register
terminals to handle all the financial transactions. These terminals handle the
credit card facilities, cash reconciliation, banking and interface with the
accounting system.

However, the current computer system runs on very old hardware (Windows 95)
and is written in an obscure programming language that nobody understands. It
is a very slow and unfriendly system that requires a fair bit of training for new
staff. So Victoria has decided to invest in a completely new system with current
hardware, operating system and software. Hardware and operating system
decisions have not been made.

While she is doing this, she wants to add a data warehouse so that management
can get various statistical reports. For example, they would like to see which
types of videos are most popular or unpopular, who are the best customers, how
many overdue videos there are and so on.

In addition, in the current system, a barcode reader is required to scan the videos,
and members need to present their ID cards to take the video out. This causes
problems when members forget to bring their cards, so Victoria would like to
explore other options.

Copyright © Open University Malaysia (OUM)


xviii  COURSE GUIDE

The following is the functional decomposition of the targeted new system for
VictoriaÊs Videos:

As there are always new staff members joining the shop, the new system has to
be easy to learn and use.

Case Study 2: NextGen POS System


(This is an introduction to NextGen POS System, an example that you will use in
some of the activities and discussions in Topic 2 and Topic 3. This case study was
adapted from Larman (2002).

The case study is the NextGen point-of-sale (POS) system. In this case study, we
shall see that there are many interesting requirements and design problems to
solve. This is a realistic problem as organisations really do write POS systems
using object technologies. A POS system is a computerised application used (in
part) to record sales and handle payments and it is typically used in a retail store.
It includes hardware components such as a computer and a bar code scanner and
software to run the system. It is interfaced to various service applications such as
third party tax calculators and inventory control. These systems must be
relatively fault-tolerant. A POS system must increasingly support multiple and
varied client-side terminals and interfaces. These include a web browser, a
regular PC which supports graphical user interface (GUI), touch screen input,
wireless PDAs and so forth.

Furthermore, we are creating a commercial POS system that we will sell to


different clients with disparate needs in terms of business rule processing. Each
client will desire a unique set of logic to execute at certain predictable points in
scenarios of using the system, such as when a new sale is initiated or when a new
line item is added. Therefore, we will need a mechanism to provide this
flexibility and customisation. Using an iterative development strategy, we are
going to proceed through requirements, object-oriented analysis, design and
implementation.

Copyright © Open University Malaysia (OUM)


COURSE GUIDE  xix

TAN SRI DR ABDULLAH SANUSI (TSDAS)


DIGITAL LIBRARY
The TSDAS Digital Library has a wide range of print and online resources for
the use of its learners. This comprehensive digital library, which is accessible
through the OUM portal, provides access to more than 30 online databases
comprising e-journals, e-theses, e-books and more. Examples of databases
available are EBSCOhost, ProQuest, SpringerLink, Books247, InfoSci Books,
Emerald Management Plus and Ebrary Electronic Books. As an OUM learner,
you are encouraged to make full use of the resources available through this
library.

Copyright © Open University Malaysia (OUM)


xx  COURSE GUIDE

Copyright © Open University Malaysia (OUM)


Topic  Introduction
to Object
1 Orientation
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Differentiate between algorithmic and object-orientation approaches;
2. Identify examples to describe the object-orientation approach;
3. Describe the important object-oriented concepts;
4. Explain how Unified Modelling Language (UML) can be used for
modelling object-oriented systems; and
5. Identify a few UML diagrams used for systems modelling.

 INTRODUCTION
Writing a big and complex program is not an easy task. There are approaches
such as spiral, prototype, waterfall, modular and object-oriented approaches
that software developers may apply in the development process. One approach
used by human beings to solve complexity problems is the divide and conquer
approach. This approach can also be used in designing computer programs. In
this approach, the main problem is decomposed or broken into smaller problems
or subproblems, each of which is then solved independently.

Copyright © Open University Malaysia (OUM)


2  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

Another approach used in designing programs is the algorithmic approach. In


this approach, the program to be designed is broken into modules, each of which
represents a specific task to be performed. The algorithmic approach is the
basis of structured programming. A general technique used in structured
programming is the top down design technique. In this technique, the program is
divided into smaller and smaller programs until each program is big enough to be
coded independently.

Figure 1.1 shows this approach for the Student Information System. The solution
designed is based on the algorithmic approach. One important thing in the
algorithmic approach is that it concentrates on the process aspect of the program.

Figure 1.1: Student information system using algorithmic approach

EXERCISE 1.1

A company manufacturing cosmetic products takes orders through the


telephone. Use the algorithmic approach to design a solution to process
the orders received through the telephone.

1.1 OBJECT ORIENTATION


Java is an object-oriented language. This language is very suitable for
programmers who use the object-oriented programming paradigm to develop
programs. Object-oriented programming is different from structured programming
as mentioned earlier. This is because object-oriented programming focuses
on object orientation while structured programming focuses on algorithmic
solutions. Basically, object-oriented programming is about designing programs
with a collection of objects that interact with one another to perform tasks.
Objects can communicate with each other by passing messages in the same way
people pass messages to each other. Objects can send or receive messages or
information. An object can be viewed as an agent that provides certain services to
its clients. To request an object to perform one of its services, a message must be
sent to it.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION  3

To illustrate, let us take the lunch preparation problem. We will propose a


solution that is quite different from the one shown in Figure 1.1. In this solution,
the tasks involved in preparing the lunch are assigned to a group of objects
(agents). Every task must be assigned to an object. The object and the task to be
performed are determined as follows:

(a) Waiter object is responsible for integrating all the relevant activities;

(b) French fries cook object is responsible for frying the french fries;

(c) Sandwich maker object is responsible for preparing the sandwich; and

(d) Hot drink machine object is responsible for preparing hot drinks.

Figure 1.2 shows the solution based on the object-oriented approach.

Figure 1.2: Lunch preparation based on an object-orientation approach

Notice how the previously mentioned objects use the message-sending


mechanism to cooperate with each other in preparing the lunch. First, the
Waiter object receives a lunch message from the customer. In response, the
object implements the message as follows:

(a) A packet of french fries message is sent to the French Fries cook object;

(b) Chicken sandwich message is sent to the Sandwich maker object; and

(c) A cup of hot chocolate drink message is sent to the Hot drink
machine object.

Copyright © Open University Malaysia (OUM)


4  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

EXERCISE 1.2

Use the object-oriented approach to design a solution for the problem in


Exercise 1.1.

1.2 OBJECT-ORIENTED CONCEPTS


To understand the object-oriented features in Java, we need to know several
object-oriented concepts. Understanding these concepts will give us more insight
on object-oriented programming.

1.2.1 Objects
An object is the most important thing in the object-oriented paradigm. Objects in
an object-oriented software collaborate and work together by sending messages
to implement the behaviour of the software.

What is an object? We can define an object as a thing that has state, behaviour
and identity. All these three properties will be explained in more detail. A few
object examples are given as follows:

(a) A car with plate number JEU 875;

(b) The carÊs steering; and

(c) The carÊs front left wheel.

Let us now learn in detail the properties of an object.

(a) Object Has State


Every object has properties that collectively represent its state. For example,
consider the vending machine object. The following are a few properties of
the object:

(i) Number of can drinks that are not yet sold;

(ii) Total money in the machine; and

(iii) Total money that was inserted by the customer when buying.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION  5

Every object property is associated with a value and this value is usually
dynamic. For example, the total money in the vending machine will change
after buying a drink. However, there are also properties with static values.
For example, the serial number of the vending machine is a constant. This
value is not always a number value but can be an object reference. For
example, the car object has a property, where its value is a reference to its
four wheels.

Object properties are also called object attributes. An object state is all the
object attributes plus their values. Figure 1.3 shows the current state of a
Box object. Notice that the content attribute value is a reference to another
object.

Figure 1.3: Object and its state

An object behaviour is influenced by its state. This will be explained later.

EXERCISE 1.3

Identify four attributes of a car object. Give an example of an objectÊs


state.

(b) Object Has Behaviour


Object behaviour is an objectÊs response when the object receives a
message. There are probably two types of actions that occur which change
the state of the object that receives the message or the state of the object that
sends the message.

Again, let us take the vending machine object. One of the messages that it
probably receives is ă release the can drink selected by the buyer. This
message will be sent to the vending machine when the buyer pushes a
button on the machine. The message received causes the object to show a
behaviour, that is, the drink can selected by the buyer is released. This
behaviour actually changes the vending machine’s state since the total
number of can drinks in the machine is one less now.

Copyright © Open University Malaysia (OUM)


6  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

In object orientation, when an object receives a message, it will display a


behaviour resulting from its response to the message. In the example just
now, the message release a can drink is sent to the vending machine.
When the object receives the message, it will respond by releasing a can
drink. Refer to Figure 1.4.

Figure 1.4: Message sending and object response

Besides changing the state, an object can also send messages to other objects
in response to a received message. Figure 1.5 shows the cooperation
between audience, television and remote control objects. When the
button for Channel 5 is pressed on the remote control, the audience
object will send the message change Channel TV(5) to the remote
control object, to change the television channel to Channel 5. The
following are message sequences sent to the television when the remote
control object receives the message:

(i) Message open communication channel


This causes the television object to open a communication channel
between it and the remote control object;

(ii) Message change Channel TV(5)


The television object will change to Channel 5 when the message
is received; and

(iii) Message close communication channel


The communication channel that was opened just now is now closed
by the television object.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION  7

Figure 1.5: ObjectÊs response to a message sent by another object

EXERCISE 1.4

State the message sent when the following events occur.

(a) User pushes the button fast forward on a video device.

(b) User sets the temperature to 20 degree Celsius on an air


conditioner.

(c) Object Has Identity


Every object has an identity that distinguishes it from other objects (see
Figure 1.6).

Figure 1.6: Object identity

The importance of this property can be understood by relating to the role of


a key in a database. In a database, the key has an important role because it
enables the records to be identified uniquely. Figure 1.7 shows several
records in a database. One of it stores the data about a computer and three
other records store data about three computer users.

Copyright © Open University Malaysia (OUM)


8  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

The record that stores the computer data has two fields, idComputer and
idUser. The idComputer field represents the key because with this, every
computer in the database is assigned a unique ID value. This enables the
computers in the database to be distinguished from one another. The
idUser field stores a reference to the record that stores data on users who
use the computer.

There are three fields in the record that stores the user data. The idUser
field stores the user ID value; it is the key for this record. The remaining
two fields store the login name and the user password. The idUser field
value is used to join the user record with the computer record. Figure 1.7
shows that computer with the ID 34 is joined to the user with ID 110. That
means that computer 34 is used by the user whose login name is azra.

Figure 1.7: Database record

Actually, the computer and user object identities in the database are
represented each with idComputer and idUser. For example, there is no
other computer in the database with value 34 for the idComputer field as
you can see in Figure 1.7.

Try to imagine a situation where the user identities are exchanged, say the
values of idUser for user azra and user nada are exchanged (see Figure 1.8).
This exchange of identities happened without the knowledge of computer
34 which still refers to user 110 (now user identity is nada).

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION  9

This situation can compromise the reliability of the database system. Let us
look at Figure 1.8.

Figure 1.8: Exchanging identity

In object orientation, the attributes for object identities such as


idComputer and idUser in Figure 1.7 and Figure 1.8 do not have to be
defined. This is because every object already has its own built-in identity
which no one can change. Hence, the problem of identity changes does not
arise.

(d) Object State and Object Behaviour Relationship


A close relationship exists between an objectÊs state and its behaviour. The
cumulative effect of an objectÊs behaviour can be represented by its current
state. For example, the total money in a can drink vending machine
represents the objectÊs cumulative behaviour towards all the buying that
occurs.

An objectÊs behaviour is influenced by the objectÊs state. For example,


assume that the number of cans in the machine is zero, that is, all the cans
in the machine have been sold out. If the machine receives a message to
release a can drink, the object certainly cannot fulfill this request because of
its state. This response will be different from the one when the object is in a
state where the number of cans is not zero.

Copyright © Open University Malaysia (OUM)


10  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

EXERCISE 1.5

State how an objectÊs state can influence its behaviour for every event
listed in Exercise 1.4.

1.2.2 Encapsulation
Imagine this scenario. You enter a restaurant. After reading the menu given by
the waiter, you order a plate of fried rice. The waiter goes to the kitchen to
convey your order to the restaurant cook. After about 15 minutes, the waiter
comes back with the fried rice that you just ordered.

In this scenario, you as the restaurant customer do not need to know about the
process that happens in the kitchen to prepare the fried rice. In another words,
you do not need to know about how the fried rice is prepared in the restaurant.
You do not need to know whether the restaurant cook used his grandmotherÊs
secret fried rice recipe or whether the fried rice was bought from the sundry shop
next to the restaurant. As far as you are concerned, your order has been fulfilled
(you got your fried rice). In object orientation, we say that the restaurant
encapsulates the implementation of the fried rice and thus hides the food
preparation from the customer (that is the client).

This encapsulation is achieved through information hiding where the


implementation information is hidden from the knowledge of the client.

The objectÊs attributes are usually encapsulated too. The encapsulated attribute is
hidden from the client. Therefore, the attributeÊs value also cannot be accessed by
the client (whether it is reading or changing the value). In this example, the
restaurant attribute that is encapsulated from the client is the cook who works in
the restaurant. The restaurant management will definitely not allow the client to
access this attribute directly. If this attribute is not encapsulated, the restaurant
cook can be changed without the knowledge of the management.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION  11

As another example, think of a car. We know how to get from destination A to B


without knowing how the engine works under the bonnet or seeing it works.

EXERCISE 1.6

Give three examples of information that can be encapsulated in an ATM


machine.

1.2.3 Object Interfaces


Every object that receives a message will respond accordingly. However, not all
messages are understood by the object. For example, the message release a
can drink is understood by the vending machine; however, it will not
understand the message supply a packet of fried rice! Therefore, every
object is integrated with a message list that can be understood. This message list
is called the objectÊs interface.

The object interface is a protocol that must be used to interact with other objects.
It lists all the messages received by an object. For example, consider the Square
object interface shown in Figure 1.9.

Figure 1.9: Square object interface

Copyright © Open University Malaysia (OUM)


12  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

The Square object interface states the messages that can be sent to the object (see
Table 1.1).

Table 1.1: Square Object Interface Statement

Message Purpose
area() When the object receives this message, it will calculate its
area and return the result.
circumference() When the object receives this message, it will calculate its
circumference and return the result.
setwidth(width) When the object receives this message, it will change its
width to the new parameter value.
setHeight(height) When the object receives this message, it will change its
height to the new parameter value.

Because the object interface is general, the information encapsulated in the object
is not revealed in the interface. For example, the Square object interface in
Figure 1.9 does not state the details used by the object to calculate area and
circumference. It also does not reveal the hidden attributes to the client.

An object interface acts like a message menu for the object. A message menu
consists of a list of messages that we can send to an object. If the object is sent a
message that is not listed in its interface, no response can be expected from the
object because it does not understand the message.

Figure 1.10 shows the relationship between the object and its client and the
connection between the object interface and the encapsulated information in
the object. The figure shows the Square object receiving the message
circumference() from the client. Because the message circumference() is
listed in the interface, the object will respond when this message is received.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION  13

Figure 1.10: Interface and object encapsulation

As explained earlier, an object also encapsulates the implementation when it


responds to a received message. Figure 1.10 shows the Square object responding
to the message circumference() which is encapsulated. Thus, the client does
not know how the Square object is going to implement its response to the
message sent by the client. For example, the client does not know the formula
used by the object to calculate the circumference. Moreover, the client does
not know whether the Square object has changed the formula as long as the
value returned is correct.

EXERCISE 1.7
1. Give an example of interface for an ATM machine.

2. What should be done when client calls the setHeight(value)


interface?

Copyright © Open University Malaysia (OUM)


14  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

1.2.4 Sending Message


An object communicates with other objects using the message-sending
mechanism. We have already explained that an object understands only the
messages listed in its interface. When the object receives a message that it
understands, it will respond accordingly. For example, when a Square object
receives the message area(), it will calculate its area using the width and
height attribute values and then return the calculated result to the message
sender.

Figure 1.11 shows graphically the message-sending mechanism. The box symbol
represents the object. The line that connects both the objects in the figure is the
link between the objects. This link represents a relationship that enables the
message to be sent from one object to another object. There is a message-sending
symbol on the line that consists of the message name and an arrow that states the
direction of the message sent. In message sending, the object that sends the
message is sometimes called the client.

Figure 1.11: Sending message to an object

The object that does not interact with any other object is useless in object-oriented
systems. Communication between objects is very important in object-oriented
software because the software must modell the collaboration of objects. For
example, Figure 1.12 shows the communication that occurs between the objects
to change a studentÊs course grade in a student information system.

Figure 1.12: Objects Collaborating in Message Sending

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION  15

This task involves three objects, which are the Database Manager object,
Database File object and Student Record object. In this example, the
student record that consists of student information is represented by Student
Record. The Database File object is linked to every Student Record object.
The Database Manager objectÊs aim is to manage all the transactions on the
Database File object.

In Figure 1.12, every message (except message changeGrade that is received by


the Database Manager object) is numbered. The purpose of numbering the
messages is to show the sequence of message sending. The numbering system
used is based on the message sending level. For example, after the
DatabaseFile object receives message 2 (that is, the message changeGrade
(“N12973”,“M20200”,“A”)from the Database Manager, it will send the
following messages according to the sequence given as follows:

Message 2.1: message accessRecord(“N12973”)


This message is sent to itself to get Student Record object
for a particular student for the subsequent processing;

Message 2.2: message changeGrade(“M20200”,“A”)


This message is sent to the Student Record object that is
obtained from the message sent before to change the grade
for a particular course.

The object collaboration shown in Figure 1.12 begins when the message
changeGrade(“N12973”,“M20200”,“A”) is received from the Database
Manager object. This message is not numbered in the figure because this is the
starting point. The Database Manager objectÊs first response is to open the file
that has the record to be changed.

This is done by sending the message open() to the Database File object.
Then, the Database Manager object sends the message changeGrade
(“N12973”,“M20200”,“A”) to the Database File object. In response, the
Database File object does two things. First, it sends the message
accessRecord(“N12973”) to itself to access the Student Record object that
has the student information for the student number N12973.

Second, the Database File object sends the message changeGrade


(“M20200”,“A”) to the Student Record object so that course grade for
M20200 is changed to A for the particular student. After the update action by
the Student Record object, the Database Manager object finally sends the
message close() to the Database File object to close the file.

Copyright © Open University Malaysia (OUM)


16  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

1.2.5 Class
A big and complex object-oriented software system usually involves many
objects, attributes and behaviours. An example of the system is the student
record system in a university. In this system, the student is modelled as an object.
The system development certainly cannot specify the attributes and behaviours
of every student object as there may be too many students (see Figure 1.13).

Figure 1.13: Individual student object specification

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION  17

This problem can be handled by using the class concept. The entire student object
can be grouped into one category. This category enables us to define the
attributes and behaviours of every object in the category. For example, all
students have the attributes name, age, address, gender and so on. There is also
the behaviour for every student. For example, every student object will respond
when it receives a message to update its address attribute. With the class concept,
we do not have to define this for every object in the system individually.

Instead, we define a category for the objects and their attributes and behaviours.
For example, we can define the Student category to contain all the student
objects in the student record system. In object orientation, the object category like
this is called a class. Class is the template that enables the creation of an object.
Every object in the Student class has the same attributes and behaviours
defined in the class (see Figure 1.14).

Copyright © Open University Malaysia (OUM)


18  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

Figure 1.14: Class Specification for all the Student Objects

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION  19

Figure 1.14 shows a Student class that has two parts:

(a) Attribute list for every object in the class; and

(b) Behaviour list for every object in the class. Every behaviour that is listed
contains text that describes the objectÊs response.

The object created from a class is sometimes called a member of the class. The
Student class defined in Figure 1.14 states that every member has the attributes
name, birth date and so on. Also, it lists the messages understood by its
members, that is, changeAddress(newAddress), addCourse(newCourse)
and so on. Besides, it also describes its memberÊs behaviour when receiving a
message.

EXERCISE 1.8
Given in Figure 1.15 are several objects. Put them into suitable classes.
For every class that you have identified, state its members.

Figure 1.15: Several objects

1.2.6 Inheritance
To determine the classes for an object-oriented software system, we must actually
categorise the objects involved in the system. An object category can be further
refined into subcategories.

Figure 1.16 shows the Shape class specification. Every object from this class has
the attributes color and location. Besides, the Shape class objects can also
understand the message setColor(newColor), which is to set the color of the
object attribute to newColor. Take note for programming, we use US spelling to
write the coding.

Copyright © Open University Malaysia (OUM)


20  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

Figure 1.16: Shape class specification

Figure 1.17 also shows the Shape class with two subcategories (subclasses),
which are Square and Circle. The objects in these categories are part of the
Shape category and have the Shape properties and behaviours. Therefore, the
Square and Circle objects not only have the attributes and behaviours in their
respective subcategory definition but they also have the attributes and
behaviours in the Shape category definition. For example, the Square object has
the following attributes and behaviours:

Attributes

color (from Shape class definition)


location (from Shape class definition)
width (from Square class definition)
height (from Square class definition)

Behaviours

changeColor(newColor) (from Shape class definition)


setWidth(newWidth) (from Square class definition)
setHeight(newHeight) (from Square class definition)

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION  21

Figure 1.17: Class and its subclasses

The object-oriented term for the object subcategory is subclass. Thus, there are
two subclasses under the Shape class ă Square and Circle classes. The
relationship that exists between the Shape class and both the subclasses is called
inheritance, because every attribute and behaviour in the Shape class definition
will be included (inherited) in the subclasses definition.

Subclasses have all the characteristics and behaviours inherited from the
superclass, but have added characteristics and behaviours for themselves. For
example, after we have created Student class, we could also define another
class for Diploma students, MasterÊs students, etc. in which all will inherit the
Student superclass. It would involve a lot of effort to create a brand new class.

However, it would be easier if we could take an existing class, clone it and then
make modifications to the clone to reflect the extra functionality. Another
example is the employee records system. You could create a generic employee

Copyright © Open University Malaysia (OUM)


22  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

class with states and actions that are common to all employees. Then more
specific classes could be defined for salaried, commissioned and hourly
employees. The generic class is known as the parent (or superclass or base class)
and the specific classes as children (or subclasses or derived classes). The concept
of inheritance greatly enhances the ability to reuse codes as well as making
design a much simpler and cleaner process.

EXERCISE 1.9
Build two inheritance hierarchies using the classes identified in Exercise
1.8.

1.3 OBJECT-ORIENTED SYSTEMS MODELLING


AND UML
In the previous subtopics, you have learned all the important concepts that you
should know when dealing with object-oriented approach to develop software. A
system including an object-oriented system needs to be examined from various
angles and its features need to be modelled in order to develop an effective
system. A software system can be said to have two distinct characteristics: a
structural, „static‰ part and a behavioural, „dynamic‰ part. The meaning of
„static‰ and „dynamic‰ parts of software are as follows (Chitnis, Tiwari &
Ananthamurthy, 2002):

(a) Static: The static characteristic of a system is essentially the structural aspect
of the system. The static characteristics define what parts the system is
made up of.

(b) Dynamic: This is the behavioural features of a system. For example, the
ways a system behaves in response to certain events or actions are the
dynamic characteristics of a system.

The static modelling which models the structural part of the system and dynamic
modelling which models the behaviour part of the system need to be performed
by the system analyst before developing a system. This is to ensure that an
effective system can be developed. The static modelling and dynamic modelling
are the subsets that make up the systems modelling which is the key aspect of
most systems development methodologies.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION  23

Systems modelling for object-oriented systems makes extensive use of the


Unified Modeling Language (UML). UML was the result of the collaboration
between three methodologists: Jim Rumbaugh, Grady Booch and Ivar Jacobson.
What they published in 1994 was an amalgamation of their own notations plus
the notations of several other authors.

UML defines standardised models and notations for expressing different aspects
of an OO design. Version 1.1 was submitted to the Object Management Group
(OMG) in 1997 and they published it as Version 1.2. Version 1.4 is current. A
major revision for Version 2.0 is in progress. At the core of the UML is the model,
which in the context of a software development process is a simplification of
reality that helps the project team understand certain aspects of the complexity
inherent in software.

The UML was designed to help the participants in software development efforts
build models that enable the team to visualise the system, specify the structure
and behaviour of that system, construct the system and document the decisions
made along the way. While this standard is not perfect for all situations, it does
mean that all practitioners are able to read each otherÊs diagrams. Most IT
professionals use only a tiny part of UML.

Figure 1.18: Overview of the main UML diagrams according to the phases of software
development life-cycle
Copyright © Open University Malaysia (OUM)
24  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

The main UML diagrams that can be used for static modelling are:

(a) Use case;

(b) Use case diagram; and

(c) Analysis class diagram.

These three UML diagrams will be elaborated in Topic 2.

On the other hand, the main UML diagrams that can be used for dynamic
modelling are:

(a) State diagram;

(b) Sequence diagram; and

(c) Collaboration diagram.

These three UML diagrams will be elaborated in Topic 3.

 Writing a big and complex program is not an easy task.

 One approach used by human beings to solve complexity problems is the


divide and conquer approach.

 This approach can also be used in designing computer programs. In this


approach, the main problem is decomposed or broken into smaller problems
or subproblems, each of which is then solved independently.

 Object-oriented programming is different from structured programming.

 This is because object-oriented programming focuses on object orientation


while structured programming focuses on algorithmic solutions.

 Basically, object-oriented programming is about designing programs with a


collection of objects that interact with one another to perform tasks.

 An object can be viewed as an agent that provides certain services to its


clients.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION  25

 To request an object to perform one of its services, a message must be sent to


it.

 The object interface is a protocol that must be used to interact with other
objects. It lists all the messages received by an object.

 Objects hide their implementation from the client. This is known as


encapsulation.

 An object is the most important thing in the object-oriented paradigm.


Objects in an object-oriented software collaborate and work together by
sending messages to implement the behaviour of the software.

 Objects have state, behaviour and identity.

 There is close relationship between behaviour and its state.

 Class is the template that enables the creation of an object. Every object
created from a class has the same attributes and behaviours defined in the
class.

 A class can inherit another class.

 A class that inherits another class is known as subclass. Subclasses have all
the characteristics and behaviours inherited from the superclass, but have
added characteristics and behaviours for themselves.

 A system including object-oriented systems needs to be examined from


various angles and its features need to be modelled in order to develop an
effective system.

 A software system can be said to have two distinct characteristics: a


structural, „static‰ part and a behavioural, „dynamic‰ part.

 The static modelling and dynamic modelling are the subsets that make up the
systems modelling, which is the key aspect of most systems development
methodology.

 Systems modelling for object-oriented systems makes extensive use of the


Unified Modeling Language (UML).

Copyright © Open University Malaysia (OUM)


26  TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

Algorithmic approach Object orientation


Attribute Static modelling
Class Subclass
Dynamic modelling Superclass
Message Unified Modeling Language (UML)
Object

Copyright © Open University Malaysia (OUM)


Topic  Static
Modelling
2 with UML
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. State the meaning of static modelling;
2. Write a use case for a given problem;
3. Draw a use case diagram for a given problem;
4. Draw an activity diagram for a given problem;
5. Describe the link between use cases and business rules;
6. Identify the issues in drawing an analysis class diagram;
7. Draw an analysis class diagram for a given problem; and
8. Differentiate use case, use case diagram and analysis class diagram.

 INTRODUCTION
Before developing a system, it is important for the system developer to understand
the system thoroughly. This is done to ensure that the developed system will
behave as expected. Software developers normally will create the model of the
system prior to developing the system. The model will highlight important aspects
of the system such as data flow and interaction between the modules. so that the
implementation can be done without any bugs or defects. An object-oriented
system which is developed using object-oriented programming normally will be
modelled using object modelling techniques. UML is the common „tool‰ used to
perform object modelling in developing object-oriented systems. UML was the
result of the collaboration between three methodologists: Jim Rumbaugh, Grady
Booch and Ivar Jacobson.

Copyright © Open University Malaysia (OUM)


28  TOPIC 2 STATIC MODELLING WITH UML

Systems can be modelled from two angles: static and dynamic aspects. The static
characteristic of a system is essentially the structural aspect of the system. The
static characteristics define what parts the system is made up of. In this topic, we
will briefly introduce to you some of the UML notations used to visualise the static
features of system using the use case, use case diagram and analysis class diagram.
The next topic will touch on using UML to perform dynamic modelling of a
system.

2.1 USE CASE


Badly defined requirements are a major cause of system failures. The requirements
for a system cover a large spectrum, from business needs to specific technologies
as well as what the system „must do‰, such as calculate tax. This topic starts with
a discussion of the different levels and types of requirements. We then focus
on what the system „must do‰, or its functional requirements. Functional
requirements are described by use cases. Use cases are the core of object-oriented
analysis and design.

In addition to use cases, you will learn about three UML diagrams that are used in
conjunction with use cases. Use case diagrams give a pictorial view of the actors
and use cases. Activity diagrams show how some use cases interact to achieve a
business task or process. Use case package diagrams logically group the use cases
to make it easier to understand the big picture.

The requirements for the system are the outcome of this process and represent an
agreement between the system development team members, customers and users.
Note that the requirements will tell what the system will do, rather than how it
will do it. Writing the requirements involve:

(a) Defining the purpose of the system, prioritising its functionality and
specifying its context (that is, who are its users and what systems interact
with it).

(b) Identifying external interfaces, both human and system-to-system. The


technology of an existing system with which the system must interface can
constrain its requirements and design.

(c) Identifying major functionality that must be provided by the system and
describing it.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  29

(d) Documenting assumptions upon which the requirements are based. If the
assumptions change, then so might the requirements.

(e) Communicating with users, clients, business analysts and developers so that
the system that is developed meets the clientsÊ expectations.

The requirements may also involve „proof of concept‰ prototypes, which early on
in the life cycle of the development process confirm or shape the direction of the
solution. The prototypes can be an implemented mockup of some function in the
system, or could simply be sketches of the GUI through which scenarios can be
navigated and confirmed.

2.1.1 Levels and Types of Requirements


An organisation might start a new system development project for a number of
reasons: new business requirements, replacing an old system, the merging of two
existing systems due to acquisition and mergers and others. In most cases, systems
development activities are driven by business needs. Hence, you need to
understand the different levels of requirements for the system you are going to
develop. These are:

(a) Business requirements  These define the high-level processes that occur in
an organisation. For example, in terms of a banking system, what is the
purpose of developing a new banking system? Is it going to replace an old
system or is it going to be used in a new line of business?

(b) System requirements  What the computer system must do for its users.
These are the functional requirements of the system.

(c) Internal requirements  Relating to technology, personnel, hardware


platform requirements and others. These are the non-functional
requirements.

To explain the differences between functional and non-functional requirements,


consider the example of building a house. Imagine that you have inherited a piece
of land and you want to build a house on it. So you contact an architect and sit
down to discuss your requirements. How many rooms do you require? Do you
want the dining room next to the kitchen? How big should the garden be? We can
consider these as the functional requirements of the house. There are other
requirements too ă such as the quality of the bathroom taps, amount of natural
light and the total budget for the project. These are non-functional requirements.

Copyright © Open University Malaysia (OUM)


30  TOPIC 2 STATIC MODELLING WITH UML

Alistair Cockburn, in Writing Effective Use Cases, suggests that only a third of
requirements are functional. Some requirements can be regarded as both
functional and non-functional.

EXERCISE 2.1

Characterise the following requirements as functional, non-functional or


both.

(a) Customers receive a special discount on their birthdays.

(b) Use the Java J2EE architecture.

(c) Each POS terminal is able to process 100 sales items per minute.

(d) Produce a report on demand of all transactions greater than


$100,000.

(e) Each user is able to see personalised menu options.

EXERCISE 2.2

VictoriaÊs Videos
In this exercise, we will use VictoriaÊs Videos system, which you were
introduced to in the Course Guide as the basis for some activities.

Have another look at the case study and list two functional requirements
and two non-functional requirements for the system.

2.1.2 Challenges of Writing Requirements


Experienced system developers will tell you that one of the main causes of project
failure is poorly conducted requirements analysis. Writers of requirements face a
number of challenges, not all of them technical. Communication, human and
business issues also have to be taken into account. The following are possible
challenges:

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  31

(a) Problem Domain Complexity


The biggest challenge is finding out about the problem domain (the
environment in which the system will operate, for example, our video shop).
This is especially true if the domain is a new one. Other domain related
challenges include ascertaining the systemÊs role within the domain,
achieving immersion in the problem domain, translating what you learn
about the domain requirements specifications and system responsibilities.
Obviously, the bigger and more complex the system required, the more
challenging your task.

(b) Person-to-person Communication


You need effective communication in order to extract information from
clients and users about the problem domain, to obtain information from
clients and users about the system requirements, to convey your
understanding of the system back to clients and users for their affirmation,
to convey requirements information to developers, managers and testers and
finally to convey the need for changes to the requirements which may have
been established. For successful requirements analysis, groups involved
need to convey information to one another effectively.

(c) Constant Change


As we have already said, changing requirements are an inevitable aspect of
the software development life cycle. Even though requirements may be
frozen at a particular point, a system and peopleÊs understanding of it will
continue to evolve. This evolution may be due to improved understanding
of the problem domain by analysts and developers, improved understanding
of the system solution on the part of users, or simply competition, regulators,
approvers, technologies or politics. Recognising that requirements will
always change is a core concept of iterative development.

(d) Writing Requirements


As you know, the goal of requirements analysis is to describe what the
system should do (the requirements) and get developers and the customer to
agree on that description. To achieve this, we define the system and its
surroundings and the behaviour it is supposed to perform. Customers and
potential users are important sources of information.

Copyright © Open University Malaysia (OUM)


32  TOPIC 2 STATIC MODELLING WITH UML

The requirements analysis is progressively presented in the Use Case Model


for the functional requirements. The Use Case Model is important for both
the customer, who needs the model to validate that the system will become
what is expected, and for the developers, who need the model to get a better
understanding of the requirements for the system. A Use Case Model is
written so that both the customer and the developers understand it.

The Use Case Model consists of actors and use cases. Actors represent the
entities external to the system, either users or other systems. Use cases
represent the functional behaviour of the system. Actors help define the
system and give you a clearer picture of what it is supposed to do. We will
look at actors further on in the next subtopic.

A use case represents events triggered by actors and describes how the
system must respond. Because use cases are developed according to the
actorsÊ needs, the system is more likely to be relevant to the users.

Figure 2.1 shows the main steps of building and delivering some
functionality. Use cases live through the entire system life cycle and act as a
unifying thread. The same Use Case Model is used during all subsequent
workflows. This topic covers the first three steps in more detail. However,
Step 4 is not covered in the syllabus.

Figure 2.1: The main steps of building and delivering some functionality

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  33

2.1.3 Types of Roles


There are three kinds of roles or actors:

(a) Primary ă A person in this role directly uses the system to enter, view process
or extract information. Depending on the user interface, these people will use
a keyboard, a mouse, buttons on a machine or talk to a voice activated
system. Examples in the case study are the checkout clerk and backroom
stock handler.

(b) Secondary  A person in this role does not directly use the system, but uses
or generates data for the system. A classic example is a person who receives
reports from a system, particularly in another department in the
organisation. This person may or may not access the system to get the report,
but is a user of the information (typically, these roles are overlooked in the
requirements analysis.) An example in the case study is the managers.

(c) External  Any system that receives or generates data for the system  these
are external systems. For example, tax office systems, bank, accounts
systems.

Note that this taxonomy differs slightly from UML and in Larman (2002).
Particularly, in UML, users and external systems are treated the same. It is true
that they are both external to the system, but treating people and computers in the
same way is not conducive to building usable systems. Furthermore, our
experience shows that frequently the needs of the secondary actors are often
omitted. Often the need for reporting is known, but instead of the needs being
closely examined, the standard response is to simply add an end-user reporting
tool. Very rarely does this simplistic approach satisfy. If senior management does
not receive any benefits from a system, then the project may be terminated.

EXERCISE 2.3

Identify possible actors for VictoriaÊs Videos system and categorise them
as primary, secondary or external.

Copyright © Open University Malaysia (OUM)


34  TOPIC 2 STATIC MODELLING WITH UML

2.2 WRITING USE CASES


We already have a good understanding of actors (as well as the roles actors will
play) in the Use Case Model. Actors are entities outside of the system that will
interact with the system. What is inside the system is represented by use cases in
the Use Case Model. Use cases are a way to discover and document functional
requirements. They describe system behaviour from the userÊs perspective. Use
cases are written in plain language so both the users and the IT staff can
understand them. Each use case must achieve something useful for the user. Use
cases define a promise or contract of how a system will behave (Larman, 2002).

There are three types of format for writing use cases. The format to be considered
depends on the need. The explanation for these three types of use cases format are
given as follows:

(a) Brief use case ă It has one paragraph summary and is normally used for main
success scenarios. Here is an example of a brief format use case for Process
Sale (modified from Larman, 2002):

Process Sale:
1. Customer arrives at POS checkout with goods and/or services to
purchase.
2. Cashier starts a new sale.
3. Cashier enters item identifier.
4. System records sale line item and presents item description, price
and running total.
5. Price calculated from a set of price rules.
6. System presents total with taxes calculated.
7. Cashier tells customer the total, and asks for payment.
8. Customer pays and system handles payment.
9. System logs completed sale and sends sale and payment information
to the external accounting system (for accounting and commissions)
and inventory system (to update inventory).
10. System presents receipt. Customer leaves with receipt and goods (if
any).

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  35

(b) Casual use case ă It is an informal paragraph which has multiple paragraphs
that cover various scenarios. The Handle Returns given in Reading 2.2 is the
example.

(c) Fully dressed ă This is the most comprehensive case that shows all the
steps and variations. It has supporting sections, such as preconditions and
success guarantees. However, a detailed discussion about a fully dressed use
case is beyond the scope of this syllabus.

Writing a use case is, to a certain extent, like writing a report and as you will know
if you have ever written a report, it is much easier if you can follow some kind of
format. Most companies and organisations have report templates for people to
refer to. Similarly, for use cases there are templates that system analysts can refer
to. One of the most popular use case templates was developed by Alistair
Cockburn. However, use case templates are not covered in this course.

EXERCISE 2.4

1. Write the use case „borrow videos‰.

2. Why do you think this is a good use case to begin with?

In Exercise 2.4, we gave you the name of a use case, but of course, normally you
have to work out the use cases yourself. Deciding where one use case ends and
another use case begins takes a bit of practice. When you first start writing down
possible use cases, do not be too concerned about getting this right. Once you get
further into writing the use cases you will be able to work out the boundaries.

EXERCISE 2.5
In Exercise 2.3, you listed the actors for VictoriaÊs Videos. Now you need
to work through the list of actors, from most important to least important,
and list their use cases. Do not be too concerned about getting the names
of the use cases perfect. Just write them down. Later you can change the
names, delete use cases or add use cases.

Copyright © Open University Malaysia (OUM)


36  TOPIC 2 STATIC MODELLING WITH UML

EXERCISE 2.6

Using your list from Exercise 2.5, select the next most important use case
of the most important actor and write a brief format of the use case.

Now select another use case and also write it in a brief format.

If all system development activities are business-driven, those writing the


requirements must aim for goals that will bring value to the organisation. This
means that a use case:

(a) Must deliver something of value to an actor;

(b) Typically represents a major piece of functionality that is complete from


beginning to end;

(c) Represents the goal of an interaction between an actor and the system; the
goal represents a meaningful and measurable objective for the actor;

(d) Records a set of paths (scenarios) that take an actor from a trigger event (start
of the use case) to the goal (success scenarios). The Process Sale use case given
in Subtopic 2.2 is an example of success scenario; and

(e) Records a set of scenarios that traverse an actor from a trigger event toward
a goal but fall short of the goal (alternate scenarios). The format to write an
alternate scenario is as follows:

condition:
handling

Example of alternate scenarios for Process Sale are given as follows (Larman, 2002)
based on the previous format:

3a: Invalid item identifier found: condition


1. System signals error and rejects entry handling

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  37

3b: There are multiple of same item:


1. Cashier can enter item category identifier and the quantity

Write the condition as something that can be detected by the system or an actor.
The previously mentioned examples only have one handling for the conditions.
There can be more than one handling for certain conditions.

Remember that a use case may have a main success scenario and some alternate
scenarios. Sometimes, when we have a large and complicated system to develop,
there will be lots of different scenarios. It would be impossible to discover all the
possible scenarios at the very beginning. Hence, when you first start writing use
cases for a system, it is best to ignore all the alternate scenarios and only think
about everything going well  the „sunny day scenario‰. Alternative scenarios can
be added later after you have identified all the success scenarios. Of course,
successful scenarios can also be revised and changed in later stages.

EXERCISE 2.7
We have written up a main success scenario for the borrow videos use
case in Exercise 2.4. Try to think up a few alternate scenarios and present
them in a brief format similar to the main success scenario. Compare
your answer with your coursemates.

A model such as a Use Case Model helps system developers to build their systems
in a systematic manner. Poor system development tends to be done by developers
who cannot judge what they should be doing at each phase of the development
cycle. A common mistake is to jump into the system design before a good
requirements analysis is available. The black-box use cases approach is usually
adopted to help system developers avoid making the same mistake twice. Let us
now discuss the term. Something is a black box if we cannot see the inner workings
of it.

Copyright © Open University Malaysia (OUM)


38  TOPIC 2 STATIC MODELLING WITH UML

For example, from a car driverÊs perspective, a car is a black box. The car either
moves properly or it does not. If there is a problem, then the car mechanic comes
and, with a white-box view, lifts the car bonnet and looks at the engine and
internals. Hence, in the black-box approach of use cases writing, we do not care
about how the system will perform the tasks but just focus on what we should
expect from the system. In other words, we are only focusing on the
responsibilities of the system. Examples of black box use cases are shown in
Table 2.1.

Table 2.1: Example of Black Box Use Case

Black Box Style Not Black Box Style


The system updates the student The system writes the new marks to a database
marks The system generates a SQL UPDATE statement
for the task

Sometimes confusion will still arise even if we adopt the black-box approach,
because different people have a different understanding of „what the system
does‰. For example, a cashier might think of his goal as „logging in‰, but in fact,
this is just the mechanism that achieves the higher-level goal of identifying and
authenticating himself. When writing use cases, keep the user interface out and
focus only on actor intent.

EXERCISE 2.8
Now take the three use cases from Exercises 2.4 and 2.6 and rewrite them
in the essential two-column format. (Yes, writing use cases is hard work,
but the more you write, the easier it gets. It is not good enough to just
look at the answers. You must practise).

2.2.1 Goals and Levels of Use Cases


Now you have an idea of what a use case is and, in general terms, know how it
should be written. Now, let us stand back a bit and ask a fundamental question:
What should the goal of the use case be? As we noted earlier, different users have
different goals. For example, the general manager of the retail store is expecting
the retail system in his company to streamline the whole retailing process. The
cashier, on the other hand, may expect the same system to read the barcodes of
items correctly and efficiently.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  39

Well, which one of these two requirements should be turned into a use case? In
fact, neither of them would make a good use case. The general managerÊs goal is
at too high a level while the cashierÊs goal is too low. So what level of user goals
can be transformed into use cases? The general guideline is to look at elementary
business processes (EBPs). The following Reading 2.1 will explain to you the
concept of EBP. It also gives a very lively example of how a system analyst
investigates the user goal of the cashier through a series of questions and identifies
the appropriate goal level for writing a use case.

READING 2.1
Now download Reading 2.1 from myINSPIRE to learn about goals and
scopes of the use case.

Information systems are rather abstract entities that consist of software,


hardware and applications. However, even though we cannot visualise the whole
information system, for the purpose of use cases we need to define a boundary for
it. It is similar to building a house, when we need to perform a land survey to fix
the boundary of the site on which the house is going to be built. A clearly defined
system boundary helps in the correct identification of the right actors to use cases,
which in turn helps the system analyst to obtain the goals. The four-step procedure
proposed to define use cases is listed as follows:

(a) Define the right system boundary;

(b) Identify the primary actors;

(c) Identify the actorsÊ goals; and

(d) Define and name the use cases.

READING 2.2
Now download Reading 2.2 from myINSPIRE to learn more about the
four-step procedure to define use cases as listed just now.

Copyright © Open University Malaysia (OUM)


40  TOPIC 2 STATIC MODELLING WITH UML

EXERCISE 2.9
For VictoriaÊs Videos, up to now we have tried to identify the actors
and some brief use cases. However, all these were produced by our
imagination. In a real system, the proper way to do requirements analysis
is to carry out a combination of many activities such as:

(a) Read any documentation that has been collected.

(b) Look at any systems that currently exist. Look at screens and
reports. See if you can track some real examples all the way
through. For example, for an insurance system, you could see how
a policy is created, and then later how a claim might be processed.

(c) Talk to the parties concerned. Commonly you begin by conducting


some user requirements workshops. Use the initial actor analysis
work as a guide to who should attend the workshop. For the first
workshops, it is best to have more people rather than less as you
need the broadest possible range of views. Later, you can have
much smaller workshops to concentrate on particular areas.

Prepare a list of questions that you would like to ask various people from
VictoriaÊs Videos.

It is important that you understand the use case model as it is a crucial element in
requirementÊs analysis and it is one of the earliest tasks in the whole system
development project. The future success of the project depends on getting the use
case right. As it is sometimes helpful to approach a topic from a different angle,
we would like you to reinforce your understanding of the Use Case Model by
working through the next reading by Cockburn.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  41

ACTIVITY 2.1

Internet Reading
Cockburn, A. Structuring use case with goals at
http://alistair.cockburn.us/Structuring+use+cases+with+goals

2.3 USE CASE DIAGRAMS


Consider the saying „A picture paints a thousand words‰. Sometimes a visual
illustration can represent complicated ideas in a simple and easy way. A use case
diagram can provide a static view of a system to allow us to have an overview of
the system and the relationship between the use cases as well as the actors of the
system. Briefly, to draw a use case diagram, we should have the following items:

(a) Functionalities to be represented as an use case;

(b) Actors can be defined as something that interacts with the system. It can be
human users, some internal or external applications; and

(c) Relationships among the use cases and actors.

The following figure is the simple UML notation to depict a use case.

Figure 2.2: Use case diagram notation

Copyright © Open University Malaysia (OUM)


42  TOPIC 2 STATIC MODELLING WITH UML

A collection of use case diagrams will form a context that show the scope of the
system and the relationship between the actors and the use cases. It serves as a
diagrammatic summary of the behaviour of the system. According to Larman
(2002), use case diagrams are only secondary in use case writing. System
developers should not spend too much time drawing use case diagrams. Writing
use case text should be the primary focus.

Figure 2.3: Use case for banking system

READING 2.3
Now download Reading 2.3 from myINSPIRE to learn about use case
diagrams in detail.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  43

EXERCISE 2.10
By using the example of the use case diagram shown in this exercise as a
guide, draw a use case diagram for VictoriaÊs Videos.

2.4 ACTIVITY DIAGRAMS


For many applications, it is extremely important to see how all the use cases fit
together to achieve something overall. This is particularly true when there are
many different people involved in an overall activity. For example, one of the main
challenges to businesses that sell products via the Internet is to work out the whole
fulfillment side. Taking the order and the money is the easy bit! UML has a
notation called activity diagrams. These diagrams, in many aspects are quite
similar to flow diagrams. They can be used at different stages in the development,
from requirements through to detailed programming.

Copyright © Open University Malaysia (OUM)


44  TOPIC 2 STATIC MODELLING WITH UML

The following diagram shows how the different actors invoke their own use cases
to achieve the overall task. The diagram has „swimlanes‰ for each of the different
actors.

Each system is different so you have to decide whether or not any activity
diagrams are useful.

Figure 2.4: An example of an activity diagram

EXERCISE 2.11
Do you think an activity diagram would help explain how a subset of the
use cases for VictoriaÊs Videos system fit together to form a whole? If so,
then draw it. Note: We are not trying to draw all the use cases of the
whole system, but only some of them that make up a process that makes
sense to the users as a whole.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  45

2.5 POTENTIAL PROBLEMS WITH USE CASES


Writing effective use cases is not a simple matter and there are a number of pitfalls
to be avoided. Here are 10, identified by Lilly (1999):

(a) The system boundary is undefined or inconstant;

(b) The use cases are written from the systemÊs point of view;

(c) The actor names are inconsistent;

(d) There are too many use cases;

(e) The actor-to-use case relationships resemble a spiderÊs web;

(f) The use-case specifications are too long;

(g) The use-case specifications are confusing;

(h) The use case does not correctly describe functional entitlement;

(i) The customer does not understand the use cases; and

(j) The use cases are never finished.

In writing this list, Lilly (1999) is not arguing against use cases, but trying to alert
newcomers to the potential problems, and suggesting ways to avoid them. She
advises:

(a) Explicitly define the systemÊs boundary. This makes clear what is inside and
outside the system.

(b) Make use of a standardised template for documenting your use-case


specifications. If the team uses a template, it will help communication
between team members as well as help newcomers get started.

(c) When writing use cases, focus on the goals of the actors. This will help you
find use cases from the usersÊ perspective and keep a focus on the primary
function of the system.

(d) Do not make use-case specification synonymous with user-interface design.


You can use low-fidelity representation of user interfaces, but since user
interface design is particularly subject to design-specific change, it is best not
to include it as part of the requirements if you want to get them signed off
earlier rather than later.

Copyright © Open University Malaysia (OUM)


46  TOPIC 2 STATIC MODELLING WITH UML

To help catch potential problems, Lilly suggests that you review your Use
Case Model, the diagrams and specifications, in incremental steps with the
development team, clients and users. Start by reviewing your use-case diagram
before you have defined use case details; check that the system boundary has been
clearly defined, that obvious actors have not been missed and that the use cases
focus on the usersÊ goals.

EXERCISE 2.12

Differentiate between use cases and requirement statements. Check your


answer at http://ootips.org/use-cases-vs-requirements.html.

2.5.1 How to Deal with Hundreds of Use Cases


The case study that you are working on is purposely chosen to be a small
application. So you may wondering how this process „scales up‰ to cater for larger
systems which may have 200+ use cases. The key is to organise the use cases so the
team can understand them. One specific technique is to organise the use cases into
groups or packages.

A UML package is a mechanism to group anything together. So a use case package


is a collection of use cases, actors and even other use case packages to structure
the use case model by dividing it into smaller parts. Thus, instead of trying to
understand 200+ use cases, the team needs to understand perhaps only 20 use case
packages. Individual team members then need to understand the details of a few
use case packages.

Deciding on the packages for a system requires a little experience, and there
are generally several valid approaches for one system. Some possibilities for
packaging the use case are listed as follows:

(a) By functional areas. For example, put everything to do with money in one
package, and inventory in another;

(b) By actor. For example, put all the cashierÊs use cases in one package;

(c) By „style‰ of use case. For example, put all the simple setup or maintenance
style use cases in one package;

(d) By importance or iteration. For example, all the use cases that are going to be
built first could be in one package; and

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  47

(e) By physical implementation. For example, all the use cases that are delivered
via the Web are in one package, and use cases accessed via the head office
computer are in another package.

Generally a combination of multiple approaches is best. Deciding on the use case


packages is usually a collaborative effort between the users, the requirements
analysts, the technical architect, perhaps the database designer and the project
manager.

The UML notation for a package is a folder. But, as emphasised earlier, the text of
the use case is more important than the diagrams. So often a use case package is
simply a short description of the use case, followed by a list of the use cases that
comprise the package. Optionally, include a use case diagram of the use cases.
Figure 2.5 summarises the use case package.

Figure 2.5: Use case package

2.6 RELATING USE CASES


As you remember, we first discussed use cases in Subtopic 2.1. Use cases describe
the interaction of an actor (either a person or an external system) with the system
under discussion. Use cases are written in plain language so that both the users
and technical staff can read them. The use cases can be written informally or using
more formal templates. The initial version of a use case describes the main flow of
events ă how things should occur in a normal situation, assuming there are no
problems. Later, as the work on the system progresses, the use cases get fleshed
out to contain alternate flows and exception handling.

There are many different approaches and styles to writing use cases. Reasons for
these differences include personal preferences, different styles of application (for
example, a website selling books is different from a stock market trading system),
and different scales or styles of development (for example, two people on a three-
month project work very differently than 50 people on a two-year project).

Copyright © Open University Malaysia (OUM)


48  TOPIC 2 STATIC MODELLING WITH UML

The next reading is a review of use cases, written by their inventor, Ivar Jacobsen.
He starts with a short history of their development.

ACTIVITY 2.2
Internet Reading
Jacobsen, I (2003) Use cases ă yesterday, today and tomorrow at
https://goo.gl/ld1bmw

Read up to the end of page 4, up to the start of the section titled „How
many use cases is enough?‰

As you can see from this reading, one aspect of use cases that has been evolving
since 1986 is how we can relate one use case with other use cases. Relating use
cases to each other allows us to see commonalities and differences between them.

There are three kinds of relationships between use cases, namely:

(a) Include ă Typically where a set of use cases each includes some common
functionality that is expressed in one shared subuse case;

(b) Extend ă Where the functionality of a use case is extended by referencing


other use cases; and

(c) Generalisation ă Where several use cases share something similar.

Before we discuss these relationships in more detail, remember that we primarily


write use cases for people to read. Use cases are not read by a compiler (a software
program that turns a computer program into executable computer code) or by any
other kind of tool. So before we add relationships to our use cases, we must be sure
that adding complexity will help the (human) reader to better understand them.

One more word of caution. As you saw in the reading, Jacobsen has changed his
views on how best to relate use cases. Use cases are not mathematically defined,
so the relationships between them are not rigorously defined, either. You will
probably find that when you read the details on the different types of relationships,
it will all seem quite simple, but that when you try to apply this knowledge, it can
be quite hard. Everyone, both novices and skilled practitioners, face the same
problem. The solution is to remember that use cases are for human use.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  49

ACTIVITY 2.3
Internet Reading
Jacobsen, I (2003) Use cases ă yesterday, today and tomorrow at
<http://www.therationaledge.com/content/mar_03/f_useCase
s_ij.jsp?from=inbrief>

Read pages 4ă5, that is, the sections „Use cases and the unified modelling
language‰ and „Use caution when formalising use cases‰.

Note: The rest of this reading, starting from the heading ÂTomorrow:
potential next stepsÊ, is more advanced and theoretical.

2.6.1 The Include Relationship


In the section of the reading that you have just worked through, Jacobsen describes
the „include relationship‰. When you are writing your use cases, you may find
that sections of some use cases occur in multiple use cases. In order to capture this
similarity, and to simplify the complexity of long use cases, you can put the
common section in a subuse case, and then reference this subuse case from the
other relevant use cases. If you have experience in traditional procedural
languages programming, you should be familiar with the concept of using a
subroutine to reduce programming complexity.

As an example, let us consider VictoriaÊs Videos. We have identified the use case
Maintain Members (from Exercise 2.6). The next table is a first draft for that use
case.

Table 2.2: Maintain Members Use Case


Maintain Members

Actor Intention System Responsibility


Identify the borrower Display personal details (name, address, date
of birth, date joined, etc.) of the borrower, plus
a summary of current borrowings
Optionally, the user can modify the Store the changes
personal details of the member
Optionally, the user can delete the Check that borrower has nothing borrowed
member Delete the member

Copyright © Open University Malaysia (OUM)


50  TOPIC 2 STATIC MODELLING WITH UML

Now compare this use case with Borrow Videos (from the answer for Exercise 2.9).
Is there anything in common? Yes. The first line for each is the same: „Identify the
borrower‰. As we are looking at use cases in essential format, this might not seem
like very much. But before we can build this system, we will have to decide how
the borrower will be identified. Will the user have a card to be scanned or will he
give us his name or an identification number? Will he need to quote a password?
So to cater for all these later concerns, we can create a subuse case that we will call
„Get Borrower‰. Now both the Borrow Videos and Identify Members use cases
will ÿincludeŸ the Get Borrower subuse case (note the UML notation of placing the
special characters ÿ Ÿ around the word „include‰).

So now, how do our use cases look? In long hand we could have:

Table 2.3: Inclusion a Subuse Case


Maintain Members

Actor Intention System Responsibility


Include use case Get Borrower ⁄

These days, the use of underlined text in a website means a hyperlink to something
else. This convention is used for use cases to indicate a subuse case. So a short way
of writing is simply to underline the use case name as shown in Table 2.4.

Table 2.4: Short Way of Writing the Inclusion of a Subuse Case


Maintain Members

Actor Intention System Responsibility


Get Borrower ⁄

The Get Borrower use case is shown in Table 2.5.

Table 2.5: A Subuse Case


Get Borrower

Level: Subfunction
Actor Intention System Responsibility
Identify the borrower Display personal details (name, address, date of
birth, date joined) of the borrower ⁄

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  51

You will notice the headings at the start of the use case that has level clause. It tells
us that this is a subuse case, as it only gives us a subfunction, that is, this use case
makes no sense by itself. It needs to be called by another use case.

Use Case Diagram Include Notation


To show an include relationship on the use case, UML specifies a dotted line, with
the arrow pointing to the included use case (see Figure 2.6).

Figure 2.6: Depicting the include relationship

EXERCISE 2.13
Let us again think back to the situation of VictoriaÊs Videos. You already
have a use case to borrow videos. But now Victoria tells you that she
would also like to sell old videos that she does not need.

Update your use cases to reflect this change. If possible, incorporate an


include relationship to simplify your use cases.

Update your use case diagram (from Exercise 2.10) with any new use
cases.

They include relationship is the most useful relationship between use cases and
you can build very sophisticated models using only this relationship. Indeed,
Cockburn (2002) writes:

As a first rule of thumb, always use the include relationship between use
cases. People who follow this rule report that they and their readers have less
confusion with their writing than people who mix includes and extends and
[generalises].

Copyright © Open University Malaysia (OUM)


52  TOPIC 2 STATIC MODELLING WITH UML

Cockburn holds this view because his emphasis is on the text of the use cases, and
their role in communicating between people. By contrast, people who put more
emphasis on the use case diagram, particularly when done with a CASE tool, like
the added complexity of having other relationships. The next sections discuss the
extend and generalise relationships.

2.6.2 The Extend Relationship


The extend relationship is another type of relationship between use cases. In the
previous section we looked at the include relationship, which you can think of as
„doing something common to several use cases‰. An informal definition of the
extend relationship is „doing something extra‰.

Let us look at an example of one way in which an extend relationship could be


used. In VictoriaÊs Videos we have this requirement (from the description for the
Victoria Videos Case Study in the Course Guide):

MemberÊs birthdays are marked with a special letter inviting them to borrow
any video of their choice for a week for free.

So we obviously we need a use case to generate the birthday letters  that is, a
straightforward use case. But how do we handle the situation when a person
comes to the shop with their birthday letter wanting to borrow a video for free?
Clearly this is an extension to the use case Borrow Videos.

So how would these use cases look? Let us look at Table 2.6.

Table 2.6: An Extend Relationship


Handle a Birthday Letter

Level: Subfunction
Trigger: Customer has a birthday letter
Extension point: Calculate total fee due in Borrow Videos
Actor Intention System Responsibility
Indicate that the borrower has a birthday Confirm birthday borrowing has not
letter already been used this year
Record use of birthday letter
Adjust total due

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  53

Once again you can see we are at the subfunction level. The trigger clause tells us
when it gets started, namely when a customer has a birthday letter. The extension
point tells us that the use case Handle a Birthday Letter gets started from the use
case Borrow Videos when it reaches the part „calculate total fee due‰. This is called
an extension point.

Lastly, to keep the use cases tidy, we can document the Borrow Videos use case to
show that there is an extension. In other words, we make it clear to someone
reading this use case that, as part of „calculate total fee due‰, there is something
more happening.

Table 2.7: Documenting a Use Case to Show an Extension


Borrow Videos

Extension Point: Calculate total fee due


Actor Intention System Responsibility
Get borrower
Identify the videos Calculate the total fees due for any past
fines and the new borrowings
Pass the total amount due to the Cash
Register Terminal

Note that apart from adding the extension point at the start of the Borrow Videos
use case, we have not changed the text of it at all. This is an important aspect of the
extend relationship. Borrow Videos was a complete and whole use case before we
added the birthday letters, so it does not need to change.

Use Case Diagram Extend Notation


To show an extend relationship on the use case, UML specifies a dotted line, with
the arrow pointing to the base use case (see Figure 2.7).

Figure 2.7: Depicting the extend relationship

Copyright © Open University Malaysia (OUM)


54  TOPIC 2 STATIC MODELLING WITH UML

A very common use of the extend relationship is for some action that can be taken
at any time. A common example is the ability to print the information on the screen
at any time.

So, for example, if we had the Maintain Members use case, then at any time the
front-desk clerk should be able to print out a summary of the member.

EXERCISE 2.14A
As discussed in the preceding section, a print function is an example of
the extend relationship. Write the Maintain Members use case, including
anything required to allow the user to print. Also draw the use case
diagram.

2.6.3 The Generalise Relationship


The generalisation relationship allows a specialised use case to change any aspect
of the base use case. The notation is a solid line ending in a hollow triangle drawn
from the specialised to the more general use case. This resembles the object-
oriented concept of subclassing or inheritance. In practice, it can be both useful and
effective to factor common behaviours. This is demonstrated in Figure 2.8.

Figure 2.8: The generalise relationship

Let us look at Figure 2.8 on how generalise is used.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  55

Figure 2.9: The generalisation relationship also can be used for actors in the use case
diagram

Figure 2.10 shows you an example of use case generalisation.

Figure 2.10: An example of use case generalisation

2.6.4 Business Rules and Use Cases


Business rules are probably the most basic part of requirements analysis and
should be done concurrently with the use case modelling. The following reading
explores the relationship between business rules and use cases more fully.

ACTIVITY 2.4
Internet Reading
Gottesdiener, E. (1999). Capturing business rules. Software Development
Magazine, 7(12), at
https://goo.gl/1pu6yh

Copyright © Open University Malaysia (OUM)


56  TOPIC 2 STATIC MODELLING WITH UML

In fact, besides their role in the use cases, business rules are also linked to other
artifacts in the software development process. The following reading discusses
such links, in particular to user interface designs, data cleansing and validation.

ACTIVITY 2.5
Internet Reading
Ambler, S. (2000). Object-oriented business rules. Software Development
Magazine at https://goo.gl/mBJA4d

In the last section of the reading, Ambler mentions the object constraint language
(OCL) as a means to express business rules. Other experts disagree. For example,
Gottesdiener says that business rules should be written in a language that the users
understand. We also like to adopt this approach in writing business rules. The
following are some options that we suggest can best express business rules:

(a) List all the rules in one list, and then refer to the list from everywhere else 
Use cases, screen mockups, class diagrams and others;

(b) Simply locate the rules in the use cases, as we have done in this course; and

(c) Keep the use cases simple, but add a section to your use case template to
explicitly refer to the business rules that each use case implements.

So, as you can see, there is a range of possibilities. Additional factors to consider
are the style of system (for example, does it involve lots of calculations), the size of
the application, the tools that are being used and so on.

So what are the business rules in VictoriaÊs Videos? Here are some examples:

(a) Only members can borrow videos;

(b) When a new person requests to become a member, they must show their
driverÊs license or other photo ID;

(c) The minimum age is 16 years old;

(d) A member can borrow any number of videos, as long as they have no
overdue videos;

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  57

(e) There are fines for overdue videos;

(f) The length of time that a video can be borrowed for depends on the video.
New releases are only lent out overnight, current releases are for three-day
hire, and the rest are for a week;

(g) Members can reserve a video;

(h) Every video has a classification, (general G, parental guidance PG, mature
audiences MA and restricted R). Members must be over 18 to borrow R
videos. Every video also has a category: Romance, General, Sci-Fi, Foreign
Language and Children;

(i) When a member has a birthday, they are sent a special letter inviting them to
borrow any video of their choice for a week for free;

(j) Every three months the shop does a stocktake; and

(k) Any missing videos are updated to be shown as missing.

You should recognise most of this text as it is pretty close to the initial description
that you saw from Victoria Videos Case Study. When describing a system, one
very common method is to list and describe the business rules. The skill of a
requirements analyst is to capture these rules and make them into something that
the rest of the design and programming team can work with. Use cases are a key
way of weaving the business rules together to create a system.

EXERCISE 2.14B
For each of the example business rules we have just given for VictoriaÊs
Videos, decide if the rule has been captured in any use case(s). If so, name
them. Or, you might note that a business rule has not yet been captured
in any use case.

The previous exercise should have helped you to appreciate the fact that quite a
strong link exists between use cases and business rules, but that each form is quite
different.

Copyright © Open University Malaysia (OUM)


58  TOPIC 2 STATIC MODELLING WITH UML

2.7 ANALYSIS CLASS DIAGRAM


In the previous sections, we have the requirements for our system defined to some
degree. Hopefully we are clear about the scope (that is, what is included) and have
some use cases and may be a use case diagram written for parts of the system.

Up to now there has been nothing object-oriented in the material. We could write
use cases and then continue in a non-object-oriented manner. Now, we will start
the object-oriented modelling using the analysis class diagram. While the material
is presented to you sequentially, in reality, the object-oriented modelling happens
in parallel with the use case writing.

This subtopic is all about „analysis class diagrams‰. The example of an analysis
class diagram is shown as follows (Larman, 2002):

Figure 2.11: Analysis class diagram

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  59

Why do we do this? Because we need to confirm our understanding of the domain


and the scope of the problem. In some cases the software developer or system
analyst already understands the domain, but in many cases there is some learning
to do. In certain specialist fields, such as finance, IT designers are expected to know
a great deal about the finance domain. While the theory may all look quite
straightforward, you do need to practise by working through the activities. In
analysis class diagram, we have three types of information:

(a) Conceptual classes  Conceptual classes represent business objects or a


business entity or concept. For example, shop, video CD and member.

(b) Associations between conceptual classes  Which define relevant


relationships, those that capture business information that needs to be
preserved and their multiplicity. For example, a shop has many video CDs,
a member borrows many video CDs.

(c) Attributes  Which are logical data values of an object. For example, each
member may have a „memberÊs number‰ which is an attribute of the object
„member‰.

It is important to note that analysis class diagram is a visualisation of things in the


real world domain of interest and not the software components such as Java class.

Remember ⁄
Analysis class diagram which is produced during the analysis phase is a
visualisation of things in the real world domain of interest and NOT the
software components such as Java classes. On the other hand, the relationship
between the software classes, which depicts the details of the classes are done
through the design class diagram which takes place during the design phase.
However, design class diagram is beyond the scope of this syllabus.

Copyright © Open University Malaysia (OUM)


60  TOPIC 2 STATIC MODELLING WITH UML

EXERCISE 2.15
Before we go into the details of the domain model, let us make sure we
are clear about its function. Refer to the following diagram:

Do not be concerned with the exact meanings of the notation ă the lines,
words, arrows, etc. ă as this is all explained later in this topic. For the
moment, just try to read the diagram with the following words, starting
in the top right-hand corner: Items are Stocked-in a Store. A Store. has
an address (for example, 15 Jalan XYZ, Ipoh) and a name (for example,
Kedai Perabot Ali). Each Store houses, or has, some Registers. Every
Sale is captured-on, or recorded on, a Register.

Continue with this description to cover all the domain objects and
relationships.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  61

2.7.1 Conceptual Classes


The first thing we have to do in building a domain model is to identify conceptual
classes (or domain classes, as it is termed in some of the object-oriented literature).
A conceptual class represents something  physical or conceptual  in a business.
There are different kinds of conceptual classes, as you will see in a moment. But
first, we need to revise what we mean by the words class and object. You will recall
from Topic 1 that a class is a template for a set of objects which all look the same.
So a manufacturing plant for a car is like a class, and all the cars that it makes are
the objects. Of course, every car has its own license plate and belongs to a different
owner.

Figure 2.12: Class and object

As the relationship between a class and its objects is so clear, we often get a bit lazy
with our language. If the head of engineering for a car factory says: „The painting
on the car needs to be done better‰, he is probably talking about the process that
goes on in the factory rather than a specific car. So, too, in software modelling; we
swap between using the words class and object.

The entity objects fall into a number of categories, based on the real-world objects
that they represent. Here are three kinds of conceptual classes that we will
encounter in business modelling:

(a) Concrete objects are tangible, that is, have a physical presence. Concrete
objects are the most easily understood by analysts and users. In the video
shop example, video CD is a concrete object.

(b) Conceptual objects are intangible and often far more difficult to understand.
For example, school is a conceptual object. You may argue that a school
tangibly exists  it has buildings. However, the concept of a school is not just
the buildings. Imagine that all the buildings in a school collapse in an
earthquake. We cannot say that the school does not exist anymore. It can be
rebuilt. Similarly, a video title is also a conceptual object.

Copyright © Open University Malaysia (OUM)


62  TOPIC 2 STATIC MODELLING WITH UML

(c) Event and state objects are highly abstract in nature. They are related in that
typically when an event of any significance occurs, some or more objects will
switch to a different state. An example of an event and state object in the
video shop is borrow video. We can see that borrow video events will
typically change the status (for example, borrow video list) of the object.

Conceptual class is an important concept in the object-oriented paradigm. In the


traditional software development process, complicated software programs were
broken down into processes or functions (in computer programming terms).

In the object-oriented software development approach, complicated software


programs are broken down into objects (which in most cases resemble real-world
objects). Hence, the division of the business or problem domain into conceptual
classes is the first step in object-oriented analysis and design. However, please note
that the conceptual classes or objects we are talking about in domain modelling are
different from the software object classes in the design class diagram. According
to Larman (2002), a conceptual class may be considered in the following terms:

(a) Symbol ă Words or images that represents a conceptual class;

(b) Intension ă The definition of a conceptual class; and

(c) Extension ă The set of examples to which the conceptual class applies.

For example, in a credit transaction, the conceptual class can have the symbol
Borrow. The intension of Borrow could be „represents the event of borrowing
transaction which has a date and transaction ID‰. The extension of Borrow is all
the examples of borrow.

2.7.2 Identification of Conceptual Classes


Conceptual classes in a domain model can serve as an inspiration for the design of
the software classes in the design model. In this respect, the identification of the
conceptual classes in the domain model is of vital importance to the success of the
system development. In a complicated business domain, there may be hundreds
of entities that can potentially be treated as conceptual classes. REMEMBER:
Whether or not they are included in the domain model very much depends on the
users and how they view their business environment. We have to choose the right
conceptual classes so that a meaningful domain model can be created.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  63

There are a number of ways that we can identify conceptual classes systematically.
One method is to come up with a conceptual class category list. We have already
categorised conceptual classes into three broad categories, namely concrete
objects, conceptual objects and event and state objects. These three categories are
further expanded into finer categories according to Table 2.8.

Table 2.8: Conceptual Class Category List

Conceptual Class Category Examples


Physical or tangible object Register
Specifications ProductSpecification
Places Store
Transactions Sale, Payment
Transaction line items SalesLineItem
Roles of people Cashier
Containers of other things Store, Bin
Things in the container Item
Other computer systems external to the CreditPaymentAuthorisationSystem
system
Abstract noun concepts Hunger
Organisation SalesDepartment
Events Sales, Payment, Meeting
Processes SellingAProduct
Rules or policy RefundPolicy
Catalogs ProductCatalog
Records of finance, work, contracts, legal Receipt, Ledger,
matters EmploymentContract
Financial instruments and services LineOfCredit
Manuals, documents, reference papers, DailyPriceChangeList
books

Source: Larman (2002)

Copyright © Open University Malaysia (OUM)


64  TOPIC 2 STATIC MODELLING WITH UML

Even though the category list as presented is drawn from some particular domains
(in the Table 2.8 case, the store domain), it more or less covers many common
categories in other business domains.

EXERCISE 2.16

Using Table 2.8 as a guide, produce a conceptual class categorisation for


VictoriaÊs Videos.

Another technique for identifying conceptual classes is the use of the noun phrase
identification. You will see that one of the arguments for developing use cases
before domain modelling is that they are an excellent source of noun phrases for
conceptual class identification. However, note the danger of ambiguities in the
natural language of use cases translating to the conceptual classes if the
transformation of one to the other is made too mechanically.

Now, let us look at one example in which we are going to use the noun phrase
identification to identify conceptual classes.

Example 2.1:
Below is a description of a Web-based ticket reservation system. All the noun
phrases that are candidates for conceptual classes are highlighted in bold.

An Internet-based ticket reservation company specialises in selling tickets for


entertainment events to customers who visit the companyÊs website. The
company acquires tickets for events from the usual ticket agencies on a regular
basis or on demand when stocks become low.

Before they can use the site, customers must register their contact details or
enter sufficient information to identify them if they have registered before. They
may then view publicity material and ticket availability information for a
number of different events and add tickets for chosen events to their order.

When they have finished, they enter their credit card details and, if all is well,
their tickets will be dispatched through the post. The company keeps a contact
address and a billing (credit card) address (which may be the same) for each
registered customer.

Concentrate just on the customer side ă do not model the supply of tickets from
„the usual ticket agencies‰.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  65

2.7.3 Issues in Identifying Conceptual Classes


There is no unique conceptual class list for a particular business domain. Different
users and object-oriented systems analysts may produce different lists. Whether or
not to include a certain entity object in the conceptual class list depends on the
context of the use cases and sometimes on the phases of the development cycle.

For example, should the object „borrow video list‰ be included in the video shop
domain model? This is a debatable question as the borrow video list of a member
is generated upon request (probably for some member who has forgotten how
many videos they have borrowed). It is not a part of the normal video borrowing
process; it is only required, say, in the „request for borrow video list‰ use case.

There is also the issue of the proper naming of the conceptual classes so that the
use of the domain model as an effective communication tool in the system
development project can be highlighted. There are two basic principles that we
need to follow in naming conceptual classes:

(a) They must be distinct; and

(b) There must be a way of telling them apart.

We will discuss „attributes‰ of conceptual classes in the coming subtopic.


Sometimes, there may be confusion between the conceptual class itself and its
attribute. For example, should „Popularity‰ be a separate conceptual class to
„Video‰ or just its attribute? Use the following hints to resolve this confusion:

A conceptual class is not considered something a number or text but


something that has legal entity, an organisation and occupies space

2.7.4 Specification Conceptual Classes


There is a conceptual class category called „specification‰ or „description‰ in the
extended conceptual class category list in Table 2.8. This category of conceptual
class requires a bit of elaboration. The following example will help you grasp this
idea.

In the video shop example, suppose we have the video Star Trek that has once been
in stock. The video has a video title, video classification and video category and
others that go with it. After the video has been borrowed by a member and he has
lost it, the video will be deleted from the system. If the management needs to
obtain some information about the video (for example, what classification it is)
there is no way they can obtain that information. To solve this problem, we need a

Copyright © Open University Malaysia (OUM)


66  TOPIC 2 STATIC MODELLING WITH UML

„VideoSpecification‰ conceptual class that records information about videos so


that whenever information about a specific video is needed (no matter whether it
is still in stock or not), it can be retrieved from the specification. The following
suggests when it is appropriate to use specification conceptual classes:

(a) There is a need to describe an item or service, independent of the current


existence of these items or services;

(b) Deleting instances of things that they describe (for example: Item) results in
a loss of information that need to be maintained; and

(c) It reduces duplicated information.

EXERCISE 2.17

Update domain model shown in Exercise 2.15 to include a description


conceptual class.

2.7.5 Associations
Now, we have successfully identified the conceptual classes in the business
domain. Say, in the video shop system, we have identified „Member‰, „Video‰,
„FrontDesk‰, „MemberRecord‰ as the conceptual classes (please note that this is a
highly simplified domain model and may not be the real domain model for the
video shop case). What are we going to do with all these objects (or conceptual
classes)? An obvious answer is to find out how they are related. An association is
an object-oriented term for relationship.

People in the real world have relationships with other people, with things and with
places. So we can say a person has a mother, is married to their spouse, likes to
drive their Porsche, lives in a house and so on. These are the associations of the
object „people‰ to other objects in the real world. We notice that most of the
relationships between the object „people‰ and the other objects are described by
verbs such as „has‰, „married to‰, „likes to‰, „lives in‰ and so on.

In UML, an association is a relationship expressing the interaction between


instances of two conceptual classes, represented by the verb that describes what
they do to each other, and/or by the nouns for the roles that each plays in the life
of the other.

The following Figure 2.13 shows the relationship between two conceptual classes
„Member‰ and „Video‰.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  67

Figure 2.13: UML notation for association

The line between the conceptual class „Member‰ and „Video‰ represents the
association between the two classes with the label „Borrow‰ that indicates the
association name (relationship). The „1‰ and „*‰ represent multiplicity, which we
will discuss in detail later.

2.7.6 Identifying Associations


Just as we identify conceptual classes, we need to identify all the essential
associations between conceptual classes that will result in a meaningful domain
model. There are a number of ways to do this. The following is a simple and
straightforward way in which we use the video shop system as an example.

Begin with a list of all the classes on the left and the UML diagram of all the classes
drawn (without association) on the right, as shown in Figure 2.14. Pick the first
and second classes in the list, that is, „Member‰ and „Video‰ and check whether
they have a relationship (either from the use case or discussion with users). If there
is a relationship (in this case „Member Borrow Video‰), add an association to the
UML diagram. At the same time, a line is drawn linking the „Member‰ and
„Video‰ items in the list, indicating that the relationship of these two classes has
been checked.

Figure 2.14: Association identification Step 1

Then we move down the list to check the relationship between „Member‰ and
„FrontDesk‰ and the association „Go To‰ is added. Again, the two items in the list
are also linked with a line.

Copyright © Open University Malaysia (OUM)


68  TOPIC 2 STATIC MODELLING WITH UML

The process is repeated with the other items down the list, that is, the „Member‰
ă „MemberRecord‰ pair. If a relationship exists, an association is added in the
UML diagram. For the items in the list, even though there is no relationship
between two items, such as „Member‰ and „MemberRecord‰, a link is also drawn
to connect the two items to indicate that the relationship between the two has been
considered. When „Member‰ and all the other items down the list have been
linked, it indicates that the relationship between „Member‰ and all the other
classes has been considered (regardless of whether or not they have an association
in the UML diagram). We can move on to the next step.

In the next step, the relationship between the class „Video‰ and the other classes
down the list is considered. Similarly, items are linked after their relationship has
been checked and an association is added between any two classes in the UML
diagram if a relationship exists.

Figure 2.15: Association identification step 2

This step is repeated with class pairs down the list until all class pairs have been
considered. The final model will look like Figure 2.16.

Figure 2.16: Association identification final step

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  69

The previous simple method for association identification is, in essence, an


exhaustive searching method that will check all the possible relationships between
class pairs. The advantage of this method is that the possibility of missing an
association in the model is very low. However, for large models with a large
number of conceptual classes, the number of class pairs that need to be checked
will be very large (n*[n ă 1] for n classes).

The effort involved may not be justified when some of the associations are not
significant or meaningful to the model. Hence, Larman (2002) has proposed the
„common association list‰. This method is based on the „need-to-know‰
association principle to avoid too many resulting associations, which would lead
to confusion in the model. The „common association list‰ by Larman (2002)
contains common categories that are usually worth considering in determining the
relationships between the classes. The common association list is given as follows
for the airline reservation system (see Table 2.9).

Table 2.9: Common Association List

Category Examples
A is a physical part of B Wing-Airplane
A is a logical part of B FlightLeg-FlightRoute
A is physically contained in or on B Passenger-Airplane
A is logically contained in or on B Flight-FlightSchedule
A is description for B FlightDescription-Flight
A is a line item of a transaction or report B MaintenanceJob-MaintenanceLog
A is known, logged, recorded, reported or Reservation-FlightManifest
captured in B
A is member of B Pilot-Airplane
A is an organisational subunit of B Maintenance-Airplane
A uses or manages B Pilot-Airplane
A communicates with B ReservationAgent-Passenger
A is related to a transaction B Passenger-Ticket
A is transaction related to another transaction B Reservation-Cancellation
A is next to B City-City
A is owned by B Plane-Airplane
A is an event related to B Departure-Flight

Source: Larman, 2002

Copyright © Open University Malaysia (OUM)


70  TOPIC 2 STATIC MODELLING WITH UML

2.7.7 Multiplicity
As you identify and draw each association, you will initially draw it as a simple
line joining two boxes in the UML diagram. Once you have established the
association, for example, „Member Borrow Video‰, there is another question to
ask: How many videos will the member borrow? This question relates to the
multiplicity of the association.

The multiplicity of an association is the number of instances of each class that can
participate in an occurrence of the association. The following table lists some
possible multiplicity values for associations. Multiplicity is an important piece of
information for the later system design stage. It communicates important domain
constraints that will affect the software design, especially in database design in the
implementation stage. Let us look at Table 2.10 for multiplicity values.

Table 2.10: Multiplicity Values

Multiplicities Meaning
11 one-to-one
1* one-to-many
1 1..* one-to-one or more
1 0,1 one-to-zero or one-to-one

Figure 2.17 depicts the domain model of the video shop system with multiplicity
added.

Figure 2.17: Associations with multiplicity

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  71

2.7.8 Aggregation and Composition Relationships


Aggregation and composition relationships are other types of relationships that
can be used to show the relation between two classes in an analysis class diagram.

(a) Composition („Uses a‰ Relationship)


A composition relationship, also known as a composite aggregation, is a
„stronger‰ form of aggregation where the part is created and destroyed with
the whole. It indicates that one class belongs to the other. Example of
composition relationship: A rectangle is made up of several points. If the
rectangle is destroyed, so are the points.

A composition relationship is indicated in the UML with a filled diamond


and a line as follows:

(b) Aggregation („Has a‰ Relationship)


In an aggregation relationship, the part may be independent of the whole but
the whole requires the part. In other words, aggregation is similar to
composition, but is a less rigorous way of grouping things. Example of
aggregation relationship: An order is made up of several products, but a
product continues to exist even if the order is destroyed. An aggregation
relationship is indicated in the UML with an unfilled diamond and a line as
follows:

Figure 2.18 shows a design class diagram which has association, composition and
aggregation relationships. Multiplicity of an association between classes is also
shown in the figure as follows:

Figure 2.18: A design class diagram


Source: Ambler (2014)

Copyright © Open University Malaysia (OUM)


72  TOPIC 2 STATIC MODELLING WITH UML

Notice that with both types of aggregation and composition relationships, the
diamond is located on the side of the line pointing to the class which represents
the „whole‰ in the relationship. Aggregation is a special form of association that is
tighter than a normal association. Aggregation means that there is a whole-part
relationship. Furthermore, the parts usually cannot exist without the whole.
Aggregation causes much confusion. As Martin Fowler writes in UML Distilled:

„One of my biggest bêtes noires [a thing someone particularly dislikes or


fears] in modelling is aggregation. ItÊs easy to explain glibly: Aggregation is
the part-of relationship. ItÊs like saying that a car has an engine and wheel as
its parts. This sounds good, but the difficult thing is considering what the
difference is between aggregation and association.‰

2.7.9 Other Issues of Association


There are other issues concerning association that are helpful in making the
domain model more comprehensible and serving the purpose of communicating
domain knowledge more effectively. These include:

(a) Naming Convention for Associations


The association should start with a capital letter such as Send-by or SendBy.
It is a common convention to read an association from left to right or from
top to bottom.

(b) Multiple Associations between Two Classes


There can be multiple relationships between objects in the domain model as
shown in Figure 2.19. Here Flies-to and Flies-From are distinctly separate
relationships.

Figure 2.19: Multiple relationships between objects in the domain model

(c) Associations and Implementation


Associations in the analysis class diagram is not about data flows, or object
connections in a software solution but it shows the relationship in a purely
conceptual sense of the real world. Also, some of the associations in the
analysis class diagram may not be implemented during the implementation
(that is, coding). You may also discover new associations need to be
implemented but were missed in the analysis class diagram.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  73

(d) „Need-to-know‰ versus Comprehensive Associations


When identifying associations in the analysis class diagram, pay attention to
the following (Larman, 2002):

(i) Focus on associations for which knowledge of the relationship need to


be preserved for some duration („need-to-know‰ associations); and

(ii) Avoid showing redundant or derivable associations.

A strict used of the „need-to-know‰ approach highlighted before to maintain the


associations in a analysis class diagram will provide minimal information on the
analysis class diagram. This means it may not convey a full understanding of the
problem to the user. According to Larman (2002), in terms of the association, a
good model of analysis class diagram can be constructed somewhere between a
minimal need-to-know model and one that illustrates every conceivable
relationship. In other words, emphasise need-to-know associations, but add choice
comprehension-only associations to enrich critical understanding of the model
(Larman, 2002).

In principal, use the following association guidelines when identifying


associations between classes (Larman (2002):

(a) Focus on the „need-to-know‰ associations;

(b) It is more important to identify the conceptual classes than to identify


associations;

(c) Too many associations will lead to confusion and marginal benefit; and

(d) Avoid showing redundant or derivable associations.

EXERCISE 2.18

Redraw Figure 2.16 to add in a „VideoSpecification‰ conceptual class to


the video shop domain model.

2.7.10 Attributes
Attributes are the pieces of data we use to identify or describe things. For example,
a person has a name, date of birth and eye colour. Attributes usually correspond
to nouns followed by possessive phrases, such as „the cour of that car‰. In this
case, colour is the attribute of car. Attributes are usually simple data types or
primitive data types such as integer, float, string, date, time and others.

Copyright © Open University Malaysia (OUM)


74  TOPIC 2 STATIC MODELLING WITH UML

For the video shop system, the following are possible attributes to the conceptual
classes identified:

(a) Member ă MemberÊs number

(b) Video ă Video ID, classification

(c) FrontDesk ă Front desk register number

(d) MemberRecord ă Number of video items borrowed, due dates of items


borrowed.

In UML, attributes are shown in the lower compartment of the rectangular box
representing the conceptual class. Hence the completed domain model, as
represented in UML for the video shop system is as shown in Figure 2.20.

Figure 2.20: Conceptual model of video shop system

Sometimes, it is difficult to judge whether an attribute is really an attribute or


whether we should treat it as another class. For example, a date is usually treated
as an attribute of a class such as a DueDate. But now consider a weather
forecasting system in the observatory that keeps daily records of atmospheric
conditions, and produces analyses for different weeks, months and years. p

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  75

Each date may be described by many other variables. For example, maximum,
minimum and average temperature, hours of sunshine, total rainfall, average wind
speed and so on. These analyses might also require separate attributes for the day
of the week, month and year. In this case, we might then choose to treat „Date‰ as
a separate conceptual class with the other variables as its attributes.

When there is a situation where it is difficult to judge whether to include an


attribute, use the following criteria to eliminate unnecessary and incorrect
attributes:

(a) If the independent existence of an entity is important, rather than just its
value, then it is a separate class;

(b) An entity that has features of its own within the given application is a
separate class;

(c) If the value of an attribute depends on a particular context then consider


restating the attribute as a qualifier;

(d) A name is a class attribute when it does not depend on context, especially
when it need not be unique;

(e) Do not list object identifiers that are used purely for unambiguously
referencing an object;

(f) If an attribute describes the internal state of a class that is invisible outside
the class then eliminate it from the analysis; and

(g) Omit minor attributes that are unlikely to affect most operations.

READING 2.4

Download Reading 2.4 from myINSPIRE to learn how attributes have


been discovered for the NextGen domain model besides the domain
model conclusion for this case study.

EXERCISE 2.19

Similar to Exercise 2.18, add in the conceptual class „VideoSpecification‰


and its corresponding attributes to Figure 2.19.

Copyright © Open University Malaysia (OUM)


76  TOPIC 2 STATIC MODELLING WITH UML

The following tips by Larman (2002) are very useful when creating analysis class
diagrams:

(a) Use Conceptual Class Category (from Table 2.8) or noun phrase
identification to identify the conceptual classes.

(b) Draw them in the analysis class diagram.

(c) Add the associations necessary to show the relationship between the classes.

(d) Add the attributes necessary to fulfill the information requirements.

 A system can be modelled from two angles: static and dynamic aspects.

 The static characteristic of a system is essentially the structural aspect of the


system.

 The static characteristics define what parts the system is made up of.

 In this topic we will briefly introduce to you some of the UML notations used
to visualise the static features of a system: use case, use case diagram, activity
diagram and analysis class diagram.

 Every system development project starts with a functional requirement


analysis.

 Functional requirements are described by use cases.

 Use cases are the core of object-oriented analysis and design.

 Getting the right requirements is critical to the success of system development


especially for large and complex systems and in a rapidly changing business
environment.

 The use case model includes the identification of actors, their goals and the
writing of use cases.

 Sometimes, use case diagrams can be used to help understand the overall
picture of the system, the flow of events and the relationship between actors
and use cases.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  77

 Basically, use cases are textual in nature where, probably to a minimal extent,
the help of some use case diagrams facilitate the understanding of the use
cases.

 You modelled a business domain with a highly abstract analysis class diagram.

 You learned how use cases are used to aid conceptual class identification.

 You also identified the associations between conceptual classes and found their
intrinsic properties by identifying their attributes.

Actor Use case


Analysis class diagram Use case activity diagram
Functional requirement Use case diagram
Non-functional requirements Use case package
Role

Copyright © Open University Malaysia (OUM)


T op i c  Dynamic
Modelling
3 with UML
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. State the meaning of dynamic modelling;
2. Draw a state diagram for a given problem;
3. Use a state diagram to identify any missing use cases;
4. Draw a sequence diagram for a given problem;
5. Draw a collaboration diagram for a given problem; and
6. Convert a collaboration diagram into a sequence diagram.

 INTRODUCTION
The previous topic has dealt with static modelling using UML. Now, this topic
will focus on dynamic modelling using UML.

Software design is about behaviour and behaviour is dynamic. The ways a


system behaves in response to certain events or actions are the dynamic
characteristics of a system. Therefore, an emphasis on dynamic models is very
important in designing a system.

There are three kinds of diagrams in UML that depict dynamic models. State
diagrams describe how a system responds to events in a manner that is
dependent upon its state. The other two kinds of dynamic diagrams fall into the
category called interaction diagrams. They both describe the flow of messages
between objects. However, sequence diagrams focus on the order in which the
messages are sent. They are very useful for describing the procedural flow

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  79

through many objects. They are also quite useful for finding race conditions in
concurrent systems. Collaboration diagrams, on the other hand, focus on the
relationships between the objects.

They are very useful for visualising the way several objects collaborate to get a
job done and for comparing a dynamic model with a static model. Collaboration
and sequence diagrams describe the same information and can be transformed
into one another without difficulty. The choice between the two depends upon
what the designer wants to make visually apparent.

3.1 STATE DIAGRAMS


A state diagram shows the life cycle of an object: what events it experiences, its
transitions and the states it is in between these events. Like many UML diagrams,
the state diagram provides a basic notation that can be used for a variety of
purposes. Our purpose at this stage is to draw a picture of the life cycle of the
conceptual classes that the system is all about. Usually in a system, there are only
a few conceptual classes that really require state diagrams. It is not wrong to
draw state diagrams for all the conceptual classes, but it is probably a waste of
time, because doing all of this drawing will not show us anything new. So the
key is to quickly work out which ones you need to do.

The following Table 3.1 gives some examples of systems and a list of their
conceptual classes. The third column suggests the conceptual classes that
probably require a state diagram. As you can see, the words in the third column
are really the core of each system.

Table 3.1: Examples of Systems and Conceptual Classes that Require State Diagrams

Conceptual Classes that


System Conceptual Classes
Require a State Diagram
Order entry Order, customer, product, receipt, Order, customer, product
shop and others.
Asset management Asset, purchase, sale, location and Asset
others.
Prisoner Prisoner, bed, sentence, medical Prisoner
management report, court orders and others.
Student enrolment Student, course, university, lecturer Student, course
and others.

Copyright © Open University Malaysia (OUM)


80  TOPIC 3 DYNAMIC MODELLING WITH UML

EXERCISE 3.1

For VictoriaÊs Videos, decide which conceptual class(es) require a state


diagram.

As an example, let us consider a prison system.

Suppose we have just started work and we have identified three use cases:

(a) Admission  Handles the prisoner being transferred from the police or
courts to the prison, and being admitted.

(b) Transfer  Handles transferring a prisoner to a half-way house.

(c) Release  Handles the way in which a prisoner is released back into the
community.

In parallel with identifying and writing use cases, we are also working on the
conceptual class model. Quickly we will realise that Prisoner is a key conceptual
class, so we start to draw its state diagram.

What does a state diagram look like? Here is an example (see Figure 3.1).

Figure 3.1: State diagram for prisoner ă Version 1

Note: A half-way house is a place to stop midway on a journey

We have boxes with rounded corners to denote each state. Each state must be
given a meaningful name. Notice that the name of the last state ends in „ed‰ 
this is a very common ending for English state names.

What this diagram shows is that there are three states that a prisoner can be in.

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  81

Next, we look at how our use case model supports these states. So what we do is
show the use cases on the state diagram. So our diagram is now as shown in
Figure 3.2.

Figure 3.2: State diagram for prisoner ă Version 2

Notice, too, the starting and end state symbols. These denote the first and last
states, respectively.

So now we could show this diagram to the users to confirm that we are correct in
our understanding. Very likely a person who understands prison systems would
say:

„Well, that is all fine, but what if a prisoner escapes?‰

After some discussion with the user, we could redraw the diagram like this (see
Figure 3.3).

Figure 3.3: State diagram for prisoner ă Version 3

This new version has a new state called Escaped (notice that it ends in „ed‰), and
we have identified two new use cases, namely Escape and Re-capture. This is the
crucial point of drawing state diagrams  they help us to quickly find missing
use cases.

Notice in this last diagram that we now recognise that some escaped prisoners
never get re-captured.

Copyright © Open University Malaysia (OUM)


82  TOPIC 3 DYNAMIC MODELLING WITH UML

EXERCISE 3.2
For VictoriaÊs Videos, draw two separate state diagrams, one for Video
Tape and one for Member.

Did you identify any missing use cases?

3.1.1 Showing Super States


Super states are a technique for simplifying state diagrams. After drawing „State
diagram for Prisoner ă Version 3‰, we could show it to another user who might
say:

That is fine, but prisoners can also escape from being in the half-way house.
Of course if we capture them, then they go back into custody.

So the diagram could look like this (see Figure 3.4).

Figure 3.4: State diagram for prisoner ă Version 4

You will notice that there are two transitions, or use cases, called Escape. Now
since these refer to the same use case, we can simplify the diagram by
introducing the concept of a super state.

In the next version you can see that there is a super state called Admitted. So
what we are now saying is that if a prisoner is In custody or In a half-way house,
and they Escape, then they will be in the state Escaped. Once they are in the state
Escaped, if they are re-captured, they go to the state In custody (see Figure 3.5).

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  83

Figure 3.5: State diagram for prisoner ă Version 5

3.2 COLLABORATION DIAGRAM


Collaboration diagrams depict an interaction among elements of a system and
their relationships organised in time and space. These diagrams contain the
following elements:

(a) Classes, denoted as class rectangles, to represent the objects involved in the
interaction;

(b) Association roles, which represent roles that links may play within the
interaction; and

(c) Messages, denoted as labelled arrows, to represent messages sent between


objects. The arrow points from the object that sends the message to the
receiving object. Optionally, parameters are passed as part of the message
and also optionally, some information, or another object is passed back.

Let us look at Figure 3.6 for an example of a collaboration diagram.

Figure 3.6: Example of a collaboration diagram

Collaboration is the specification of how a classifier, such as a use case or


operation, is realised by a set of classes and associations playing specific roles
and used in a specific way. The collaboration defines an interaction.

Copyright © Open University Malaysia (OUM)


84  TOPIC 3 DYNAMIC MODELLING WITH UML

A collaboration diagram shows the messages the objects send each other. A
message is represented as an arrow near the association line between two objects.
The arrow points to the receiving object. A label near the arrow shows what the
message is. The message tells the receiving object to execute one of its operations.
A pair of parentheses end the message. Inside the parentheses are the parameters
(if any) that the operation works on.

Table 3.2 summarises the details of collaboration diagrams.

Table 3.2: Details of Collaboration Diagrams

Link A connection path between two objects that allows


communication between them.

These are the association links on a class diagram. (Note: in


Visual Paradigm, you need to put a link between objects before
you can send a message along the link.)
Messages The actual message from one object to another. Note that there
may be several messages between the same pair of objects.
Messages to „self‰ Objects often send themselves messages.
Creation of Objects are continually being created. For example, new sale
instances results in a new transaction record.
Message Sequence numbers are needed to show the order in which the
numbering messages are sent.
sequence
Conditional Rarely used. Only sends a certain message if a condition is met.
messages
Mutually exclusive A method of numbering to allow two separate message
conditional paths sequences to be followed, depending on the result of a
conditional test.
Iteration or looping To specify that a particular message is sent multiple times.
Iteration over a Very commonly used. Send the same message to a collection of
collection objects, such as a list.
Messages to a class This is something we have not yet explicitly mentioned, and
object is a subtle point. In addition to methods on objects there is
sometimes a need to specify a method that operates at a class
level. The primary reason for this is the „create‰ message. If an
object does not yet exist then how does it get created? The
answer is that every class has the class method called create.
Class methods are also called static methods.

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  85

READING 3.1
Download Reading 3.1 from myINSPIRE to learn the details of
collaboration diagrams.

In addition to the notation in the reading, there is also the concept of a multi
object (see Figure 3.7). This is also known as a collection object (such as a list). So
a message which is shown as being sent to a multi object, is really a message sent
to the collector of that object. The collector then finds the correct object.

Figure 3.7: A multi object for a collaboration diagram

EXERCISE 3.3
Look at the following collaboration diagram. It shows the use case of a
thirsty person coming into a restaurant and requesting a drink from a
Bot. Think of a Bot as a robot that interacts with the other parts of the
restaurant.

Your task is to translate this diagram into a dialogue between the


various components.

Figure 3.8: A thirsty person walks into a restaurant

Copyright © Open University Malaysia (OUM)


86  TOPIC 3 DYNAMIC MODELLING WITH UML

3.3 SEQUENCE DIAGRAM


Sequence diagrams depict an interaction among elements of a system organised
in time sequence (Refer to Figure 3.9). These diagrams contain the following
elements:

(a) Class roles, denoted as class rectangles, represent roles that objects may
play within the interaction.

(b) Lifelines, denoted as dashed lines, represent the existence of an object over
a period of time.

(c) Activations, denoted as thin rectangles, represent the time during which an
object is performing an operation.

(d) Messages, denoted as labelled horizontal arrows between lifelines,


represent communication between objects.

Figure 3.9: Sequence diagram notation

Typically a sequence diagram shows one use case. However, to adequately show
how errors are handled, often extra diagrams are required. Figure 3.10 shows the
example of an ATM machine system.

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  87

Figure 3.10: Sequence diagram for ATM machine

The following Table 3.3 summarises the details of sequence diagrams.

Table 3.3: Details of Sequence Diagrams

Links Not shown.


Messages A message is a simple line from one object to
another.
Focus of control and activation This is extremely useful when you are new to
boxes sequence diagrams. It allows you to very easily
see which objects are active or waiting to get an
answer for a message that they have sent.
Illustrating returns Again, very useful for beginners. Explicitly
shows when the message is answered.
Messages to „self‰ or „this‰ A simple line from an object to itself. Nested
activation boxes, as shown in the text, are not
really necessary.
Creation of instances Very important.
Object lifelines and object Sometimes useful.
destruction
Conditional messages As for collaboration diagrams.
Mutually exclusive conditional
messages
Iteration for a single message As for collaboration diagrams.
Iteration for a series of messages
Iteration over a collection (multi
object)
Messages to class objects As for collaboration diagrams.

Copyright © Open University Malaysia (OUM)


88  TOPIC 3 DYNAMIC MODELLING WITH UML

READING 3.2
Download Reading 3.2 from myINSPIRE to learn the details of a
sequence diagram as shown in Table 3.3.

EXERCISE 3.4
Take the collaboration diagram in Exercise 3.3 and translate it into a
sequence diagram.

3.4 DESIGNING FOR RESPONSIBILITIES


You have seen what interaction diagrams (either collaborative or sequence
diagrams) look like; now the question is, how do we come up with them?
Obviously, the design model has to be based on the artifacts that we have in the
requirements analysis. We have a set of use cases. We will start to produce the
interaction diagrams based on these artifacts.

As we work through the use cases, and we are trying to decide which object
should fulfill a particular function, the word responsibility is used.

Booch, Rumbaugh and Jacobsen (1999) defined a responsibility as „a contract or


obligation of a type or class‰. A class is responsible for knowing things and doing
things.

In terms of its actions, an instance of a class may do something itself, may cause
another class to do something by initiating an action or controlling or
coordinating its actions. These are a few types of „doing‰ responsibilities that
must be defined appropriately for classes in a system.

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  89

A classÊs responsibilities might be: knowing about its own data, knowing about a
related object or knowing about things it can figure out.

Design is about assigning responsibilities to appropriate classes.

Doing responsibilities of an object include:

(a) Doing something itself, such as creating an object or doing a calculation;

(b) Initiating action in other objects; and

(c) Controlling and coordinating activities in other objects.

Knowing responsibilities of an object include:

(a) Knowing about private encapsulated data (for example, the knowledge of
size of the glass in Exercise 3.3);

(b) Knowing about related objects; and

(c) Knowing about things it can derive or calculate.

Example 3.1: Process a Sale


Now we are ready to start work on creating a collaboration diagram for the use
case Process a Sale.

Where do we begin? We start with the GUI telling the Register it is ready to
create a new sale. This is a simple create operation on the class Sale. Next, the
GUI sends the Register the id or barcode of the item and the quantity. Next we
need to find out what the item is, as per our robustness diagram. Let us just
check that this is correct. For this, look at the conceptual class model as shown in
Figure 3.11.

Copyright © Open University Malaysia (OUM)


90  TOPIC 3 DYNAMIC MODELLING WITH UML

Figure 3.11: Process a sale


Source: Larman (2002)

What do you notice about the itemId? Is this attribute on the Item class?
No, it is not  it is on ProductSpecification. But how do we get to
ProductSpecification? From the domain model, we know that it is from the
ProductCatalog. We are trying to get a whole ProductSpecification
object back, so note the syntax of message 5 from Figure 3.11. Next the
ProductCatalog object sends a message to the ProductSpecification
collection object, denoted with the special notation. This collection object finds
the correct ProductSpecification and sends it back.

(Note: At this point we have assumed that all these objects are sitting around just
waiting for us to talk to them. In reality, of course, they would be in a database
and we would have to do some work to get them out. However, getting data in
and out of databases is not covered in this module.)

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  91

So now we have a ProductSpecification object. Should the Register


object create the SalesLineItem? No, as that is a detail that is best delegated to
another object. So, as we correctly identified in the robustness diagram, albeit in a
different order, the ProductSpecification is passed to the Sale object,
which it then uses to create the SalesLineItem in message 7. Message 8 then
adds the SalesLineItem to the SalesLineItem collection object. Message 9
is the GUI telling us that there are no more items, so we need to calculate the
total. Once again the Register delegates this task to the Sale object which
then, in turn, asks each SalesLineItem for its total. Each SalesLineItem
asks its ProductSpecification for its price.

Lastly, the payment is made (assume it is cash only, and that correct money is
given) and the Payment object is created (see Figure 3.12).

Figure 3.12: Collaboration diagram for process a sale

So now we have one collaboration diagram for the use case Process a Sale. Of
course, we could also show this as a sequence diagram.

Copyright © Open University Malaysia (OUM)


92  TOPIC 3 DYNAMIC MODELLING WITH UML

EXERCISE 3.5
1. Draw a sequence diagram for Process a Sale, based on the
understanding of the collaboration diagram that has been given in
Figure 3.12.
2. Draw a collaboration diagram and a sequence diagram for the use
case Borrow Videos in the VictoriaÊs Video case.

 Software design is about behaviour and behaviour is dynamic.

 The ways in which a system behaves in response to certain events or actions


are the dynamic characteristics of a system.

 Therefore an emphasis on dynamic models is very important in designing a


system.

 Dynamic modelling for object-oriented systems will involve state and


interaction diagrams.

 The interaction diagrams such as collaboration and sequence diagrams will


give us the dynamic look of the system that indicates the sequence of
exchange of messages between the classes.

 There exists an interplay between the static and dynamic models.

 A static model cannot be proven accurate without associated dynamic


models.

 Dynamic models, on the other hand, do not adequately represent


considerations of structure and dependency management.

 Thus, the designer must iterate between the two kinds of models, driving
them to converge on an acceptable solution.

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  93

Collaboration diagram Sequence diagram


Interaction diagram State diagram

Copyright © Open University Malaysia (OUM)


T op i c  Introduction to
Java
4
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Describe the Java environment;
2. Explain the strengths of Java;
3. Identify the types of Java programs; and
4. Execute a Java program.

 INTRODUCTION
The previous topics have dealt on how to create models of object-oriented
systems. In particular, you have learned how to perform systems modelling
using UML. You have learned that UML can be used to perform static and
dynamic modelling for object-oriented systems. A model is just a model in the
sense that it cannot be executed. A model gives us a solid understanding about
the nature and behaviour of the system. A model acts as a blueprint in order to
implement the system. The object-oriented programming language such as Java
is the popular language used to implement UML models. This topic and onwards
will focus on the Java programming language.

Starting from a failed project, Java has emerged as a popular programming


language within a short period of time. JavaSoft Sun MicroSystems successfully
signed up 38 licenses in only one year after the Java technology was announced.
Besides, it also successfully attracted 6000 programmers to attend the first
seminar ă the JavaOne Developer ConferenceTM in 1996.

Copyright © Open University Malaysia (OUM)


TOPIC 4 INTRODUCTION TO JAVA  95

What is so special in Java that computer industries and businesses can accept it
within a very short period of time compared to other new technologies in the
computer history? The answer to this question is provided in Subtopic 4.2 
Characteristics of Java. The next subtopic will give an overview of Java.

4.1 JAVA ENVIRONMENT


In the traditional language environment such as C, C++ and Pascal, the source
code compilation will generate the object code in binary file format as shown in
Figure 4.1. This binary file is specific for the machine that generates it; in other
words, it cannot be executed directly on other machines. For example, the binary
file generated by the SPARC machine cannot be executed on a Pentium machine.
To execute the program on another machine, the program source code must be
recompiled on that machine. The traditional programming environment depends
heavily on this computer architecture.

Figure 4.1: Traditional language environment

Figure 4.2 illustrates the Java programming environment. The output of a Java
program compilation is in the form of a bytecode. The Java bytecode is a set of
instructions that is quite similar to the machine code instructions or native code
for a machine. The difference is that the bytecode is not specific to any processor.
The result of compilation can be implemented by a Java Virtual Machine (JVM),
or any machine that will interpret the bytecode.

Figure 4.2: Java language environment

Copyright © Open University Malaysia (OUM)


96  TOPIC 4 INTRODUCTION TO JAVA

If we want to implement a Java program on a Pentium machine, then we need an


interpreter or JVM for the Pentium machine. The same applies for the SPARC
machine. However, unlike traditional languages such as C and Pascal, a Java
program does not have to be recompiled to enable it to run on another machine.

What are the Advantages of Using Bytecode?


Using bytecode as an intermediary and not allowing each person to compile it
into the machine language of whatever computer they want to run give us
advantages. A compiler is a complex program. A Java bytecode interpreter, on
the other, is a simple program. This means it is easy to write a bytecode
interpreter for a new type of computer; once that is done, that computer can
run any compiled Java program. It would be much difficult to write a Java
compiler for the same computer.

4.2 CHARACTERISTICS OF JAVA


Java technology provides a neat development platform based on objects. Java
environment provides class library which contains various classes that have
already been tested. This class library can be accessed by the programmer who
wants to use it in his program development; furthermore, this library can be
extended by the programmer according to his or her requirements. Other main
characteristics of Java are highlighted as follows:

(a) Simple
Java has functionality needed to implement its rich feature set. It does not
add lots of syntactic structure or unnecessary features.

(b) Object-oriented
Almost everything in Java is either a class, an interface, a method or an
object.

(c) Platform Independent


Java programs are compiled to a byte code format that can be read and run
by interpreters on many platforms including Windows 95, Windows NT as
well as Solaris 2.3 and later.

(d) Safe
Java code can be executed in an environment that prohibits it from
introducing viruses, deleting or modifying files, or otherwise performing
data destroying and computer crashing operations.

Copyright © Open University Malaysia (OUM)


TOPIC 4 INTRODUCTION TO JAVA  97

(e) High Performance


Java can be compiled on the fly with a Just-In-Time compiler (JIT) to code
that rivals C++ in speed.

(f) Multi-threaded
Java is inherently multi-threaded. A single Java program can have many
different things processing independently and continuously.

4.3 TOOLS TO DEVELOP JAVA PROGRAMS


When Java was introduced in 1995, JDK was the only development tool available.
Although what is provided in JDK is sufficient to develop any Java program, the
facilities provided for the programmer are outdated compared to the latest
integrated development environment for languages such as Visual Basic and
C++.

Integrated Development Environment (IDE) refers to the software package that


combines various development tools. This includes program editor, compiler,
debugger and other utilities. Most IDEs have features such as windows, drag-
and-drop and other graphic elements. The aim is to make the software
development process fast, efficient and easy to debug. The JDK must be installed
before IDE installation.

Part of IDE uses the Rapid Application Development (RAD) approach. RAD
accelerates the software development process by using tools such as the interface
designer. Many of the Java IDEs available in the market use the graphic interface
builder to support RAD.

The following are some Java IDE softwares with their URLs:
 WinEdit (http://www.winedit.com/)
 Jcreator (http://www.jcreator.com)

ACTIVITY 4.1

JDK can be downloaded free from the website


http://www.oracle.com/technetwork/java/javase/downloads/index-
jsp-138363.html

Copyright © Open University Malaysia (OUM)


98  TOPIC 4 INTRODUCTION TO JAVA

4.4 WRITING JAVA PROGRAMS


There are two types of programs in Java ă application and applet. Application
itself can be divided into two types, namely text-based application and frame.
Text-based application does not support GUI while frame actually is a GUI-based
stand alone program.

Text-based application could be written using structured approach or using


„object-oriented approach‰. But frame could only be written using object-
oriented approach.

Apart from application, another type of Java program is applet. Applet is a web-
enabled program. The examples of test-based applications will be illustrated in
the next subtopic. Applet and frame are not covered in the syllabus. Applets are
covered in another course, CDOP3203 ă Java Programming. We will skip any
elaboration about frame and applet in this module.

Figure 4.3: Java programs

Copyright © Open University Malaysia (OUM)


TOPIC 4 INTRODUCTION TO JAVA  99

4.5 WRITING TEXT-BASED APPLICATION


USING STRUCTURED APPROACH
Text-based applications can be written using structured approach or object-
oriented approach. In this subtopic, we will discuss how you can write a text-
based application using the structured approach.

Program 4.1 shows an example of a non-GUI stand alone application written


using the structured approach.

Program 4.1: Hello.java

Line Number

1 // this program displays “Hello world”


2 class Hello{
3 public static void main (String args[]) {
4 System.out.println(“Hello world!”);
5 }
6 }

In the structured approach, all the statements and instructions are dumped into
the main method. Sometimes, extra methods could be added to perform specific
tasks. No objects are required to be created when writing Java programs using
structured approach. The previous Program 4.1 is described as follows:

Line 1
Line 1 in the program is comments written by the programmer. It helps others to
understand the nature of the program. Thus, the program becomes more
readable.

Line 2
Line 2 declares the name of the class as Hello.

Copyright © Open University Malaysia (OUM)


100  TOPIC 4 INTRODUCTION TO JAVA

Line 3
Line 3 is where the program starts to execute. In this class, a method called
main() contains the statements to display the „Hello world!‰ string. The
main() method must be present in all Java applications because it is the first
method that will be executed when an application runs (that is, it is where the
program starts to execute). The Java technology interpreter must find this
defined exactly as given or it will refuse to run the program. The following
describes each element of line 3:

public: The method main() can be accessed by anything, including the


Java interpreter.

static: This keyword tells the compiler that the main() method is usable
in the context of the class Hello. No object is needed to execute static
methods.

void: This keyword indicates that the method main() does not return any
values (that is, there is no return keyword in the main() method).

String[ ] args: This method declares the single parameter to the main()
method. The name of the parameter is args with the type of string array.

Line 4
The statement System.out.println(“Hello world!”) in Line 4 in the body
of the method will instruct the computer to display the message „Hello world‰
upon execution.

Line 5, 6
Line 5 and 6 contain two braces to close the method main() and class Hello
respectively.

How do We Compile and Execute Java Applications?


The following activity will guide you to compile and execute Program 4.1:

Note: Before doing this activity, please download Java Development Kit (JDK)
which is downloadable from myINSPIRE (click eServices  Resources for IT).
The JDK version available in myINSPIRE is version 6.0 (1.6; jdk1.6.0 update
24).

The purpose of this exercise is for you to compile and execute Program 4.1. It
is compulsory for you to follow all the steps to ensure that you learn how to
compile and execute a Java program using JDK.

Copyright © Open University Malaysia (OUM)


TOPIC 4 INTRODUCTION TO JAVA  101

Step 1
By using Notepad in Windows, type Program 1.1. Then, save it in a file with
the name Hello.java in the jdk1.6.0_24/bin directory. (In this example, the Java
file is saved in the C:\jdk1.6.0_24/bin directory. You may have a different
directory for jdk1.6.0. Check your correct jdk directory from Windows
Explorer).

Step 2a
Now lauch the Command Prompt from the Start button of your Windows
by typing „cmd‰ without the quotes and then press <enter> as shown in the
following:

Step 2b
In your command prompt, type cd:\ to enter the directory C:\ as shown in
the following:

Then, you need to enter the directory that stores the Java program that you
have typed in Step 1. Use the command cd to enter the correct directory as
shown in the following:

C:\jdk1.6.0_24\bin>cd jdk1.6.0_24/bin <enter>

Copyright © Open University Malaysia (OUM)


102  TOPIC 4 INTRODUCTION TO JAVA

(In this example, the Java file is saved in the C:\jdk1.6.0_24/bin directory. You
may have a different directory name. Check your correct jdk directory from
Windows Explorer).

Step 3
Compile the Java program using the instruction javac Hello.java in the DOS
environment. The example is shown as follows:

C:\jdk1.6.0_24\bin>javac Hello.java <enter>

If the error message is displayed, go to Step 4. If the error message is not


displayed, go to Step 5.

Copyright © Open University Malaysia (OUM)


TOPIC 4 INTRODUCTION TO JAVA  103

Step 4
Go back to Notepad and open the file that you have typed in Step 1; however,
do not close the DOS window. Do the necessary correction in your program.
Make sure you save your file after the corrections. Now go back to the DOS
window and repeat Step 3.

Step 5
If there is no error, the compiler will generate the bytecode file ă that is
Hello.class. Now you are ready to execute your program. In order to do this,
type the command java Hello in the eDOS Window as shown in the
following:

C:\jdk1.6.0_24\bin>java Hello <enter>

Take note that this instruction consists of two parts. The first part (java)
refers to the Java runtime interpreter. The second part (Hello) refers to the
class name which has the main() method that is to be executed by the
interpreter.

The program generates the output given as follows. It displays the string sent
as a parameter to the System.out.println() method ă the first statement
in the main() method.

Copyright © Open University Malaysia (OUM)


104  TOPIC 4 INTRODUCTION TO JAVA

 Starting from a failed project, Java has emerged as a popular programming


language within a short period of time.

 The strength of Java, which lies in its object-oriented paradigm, has


contributed to this success.

 The object-oriented paradigm in Java makes it easy to reuse the applications.

 In addition, the types of Java programs have also been discussed in this topic.

 It is important for the learners to understand the types of Java programs and
be able to compile and execute those programs.

 Below is the summary of Java applications and applet discussed previously:

Type of Java How It could be Where the Output will


Program Written? be Produced?
Text-based Structured OR Command prompt
application Object-oriented
(OO)
Frame Object-oriented Windows of the userÊs
PCÊs operating system
Applet Object-oriented Web browsers (Internet
Explorer, Chrome and
so on)

Applet Object-oriented programming


Bytecode Text-based application
Frame

Copyright © Open University Malaysia (OUM)


Topic  Basic
Constructs of
5 Java
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Describe the importance of data types and variables in Java;
2. List the primitive data types in Java;
3. State the rules of naming a variable in Java;
4. Describe assignment;
5. Identify Boolean operators and relational operators; and
6. Explain operator precedence.

 INTRODUCTION
What is a computer program? A program is a sequence of instructions that a
computer can execute to perform some tasks. There are two basic blocks of
programming: data and instructions. To work with data, you need to understand
variables and data types; to work with instructions, you need to understand
control structures and subroutines (methods). This topic will focus on how
variables and data types and its related concepts can be implemented in Java.

Copyright © Open University Malaysia (OUM)


106  TOPIC 5 BASIC CONSTRUCTS OF JAVA

5.1 DATA TYPES


Java is a kind of language that places importance on types. This means each
variable should consist of the approved types. There are eight types of primitive
data in Java. Six of these are the numerical types while one is the char data that
is used for characters in the Unicode coding and the other type of data is
Boolean for the true values (true or false). All types of data in Java have the
same cell sizes in any environment. All the variables in Java must have a type.
(variables will be elaborated in Subtopic 5.2.)

5.1.1 Integer
The integer type of data is used for numbers that do not have decimals. The
negative values are also allowed. Java prepares four types of integer data,
namely int, short, long and byte. The storage size and the value range for
each of these data types are shown in Table 5.1.

Table 5.1: Value Range for the Integer Data Type

Storage
Type Minimum Value Maximum Value
Capacity

int 32-bit ă2,147,483,648 2,143,483,647


short 16-bit ă32,768 32,767
long 64-bit ă9,223,372,036,854,775,808L 9,223,372,036,854,775,807L
byte 8-bit ă128 127

In many cases, the int type data is the most practical. If the integer value used is
too large, for example, in representing the income of PETRONAS, then the most
appropriate data is long. The byte and short data type are for the use of
specific application such as keeping files at a lower level or a larger array if the
storage space is insufficient.

In the Java language, the range for the integer data type does not depend on the
machine where the Java code is executed. Unlike Java, in C or C++ language, the
int data type is different according to the machine. For the 16 bytes processor
such as the 8086, the int cell size is 2 bytes while for the 32 bytes processor such
as the Sun SPARC, the cell size is 4 bytes. For the Intel Pentium processor, the
integer data type depends on the operation system: for DOS and Windows 3.1,
the integer cell size is 2 bytes and when using the 32 bytes processor on Windows
95 or Windows NT, the cell size is 4 bytes.

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA  107

As the range for all types of Java data is fixed, the Java program will produce the
same results if run on any machine. This makes it easier for the programmers
who wish to transfer their codes from one machine to another or between the
operational systems on the same platform.

The long type of numerical integer has the L suffix (for example, 2412345600L).
The hexadecimal numbers have the initial 0x (for example, 0xA9B9). Take note
that Java does not have the type of data with unsigned descriptor as in C.

5.1.2 Real
The real data type or floating point represents numbers that have the decimal
parts. There are two types of real data types, which are float and double. The
storage size and value range for each of these data are shown in Table 5.2.

Table 5.2: Value Range for the Real Type Data

Storage
Type Minimum Value Maximum Value
Capacity
float 32 bit 3.40282347E+38F 1.40239846E-45F
double 64 bit 1.797693134862+31570E+308 4.9406545645841246544E-324

The name double is used because the number from this type has two times the
precision of the float type numbers. Sometimes it is called the variable with
double precision. In many applications, the double type is picked to represent
real numbers. This is because the float data type can only represent seven
meaningful digits (decimals). The precision of limited float data is insufficient
in most cases. One of the reasons for using it is when there is a need for quick
processing or when the real number count that needs to be stored is large.

The real number from the float type has the F suffix, for example 75.43F. The
floating point number without the suffix F such as 75.43 would be considered
double. This is because the double data type is the default data that represents
real numbers in Java. This is different from C language that uses the float as its
default data type.

We could also add the D suffix to represent the double type numbers. All the
floating point data types follow the IEEE 754 specifications. An overflow occurs
when the range error takes place and an underflow when the zero division
operation takes place.

Copyright © Open University Malaysia (OUM)


108  TOPIC 5 BASIC CONSTRUCTS OF JAVA

5.1.3 Characters
The character data type is represented by char. The single open inverted sign (Â)
is used to show character constant.

ÂYÊ character constant


„Y‰ string that contains only the Y character

The char data type follows the Unicode coding scheme. Unicode was created to
facilitate the programmer to deal with non-Roman characters. As the Unicode
was invented to handle all characters existent in all the written languages in the
world, the cell size is 2 bytes. This size allows character representation of up to 65
536 compared to the ASCII/ANSI code, which is the 1 byte code and only allows
a 255 character representation. Until recently, only 35 000 character codes were
used.

The Unicode character is usually expressed in the hexadecimal coding scheme


that starts with Â\ u0000Ê until Â\uFFFFÊ. The initial \u shows the Unicode value
and the next four hexadecimal digits show the represented Unicode characters.
For example, \u2122 is the trademark symbol (™).

Java has also allowed us to use the escape sequence for special characters as
shown in Table 5.3.

Table 5.3: Unicode Value for Special Characters

Escape Sequence Meaning Unicode Value


\b Backspace \u0008
\t Tab \u0009
\n New line \u000a
\r Carriage return \u000d
\‰ „ \u0022
\Ê Â \u0027
\\ \ \u005e

Although Java allows any Unicode character in the applet or Java applications,
the question of whether that character can be displayed on the applet or console
depends on the support provided. For example, we cannot display the Kanji
character (a type of Japanese writing) on the machine that operates using the
Windows 95 of the US version.

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA  109

/*
Java char Example
This Java Example shows how to declare and use Java
primitive char variable inside a java class.
*/

public class JavaCharExample {

public static void main(String[] args) {

/*
* char is 16 bit type and used to represent Unicode
characters.
* Range of char is 0 to 65,536.
*
* Declare char variable as below
*
* char <variable name> = <default value>;
*
* here assigning default value is optional.
* /

char ch1 = ‘a’;


char ch2 = 65; /* ASCII code of ‘A’*/

System.out.println(“Value of char variable ch1


is :” + ch1);
System.out.println(“Value of char variable ch2
is :” + ch2);
}
}

/*
Output would be
Value of char variable ch1 is :a

ACTIVITY 5.1

Please refer to the website http://www.unicode.org for further


explanations on the Unicode.

Copyright © Open University Malaysia (OUM)


110  TOPIC 5 BASIC CONSTRUCTS OF JAVA

5.1.4 Boolean
Boolean types have two values: true and false. These literals are typed without
quotes, but they represent values, not variables. Boolean-valued expressions are
used extensively in control structures and to test the mantic expressions. Boolean
values can also be assigned to variables of type Boolean.

Boolean data type does not exist in C language. However, the non-zero value is
used to represent true and zero for false. In C++, a data type called bool is used.
It, too, can take either the true or false value. As C++ has a history that relates
closely to C, therefore the exchange between the Boolean value and integer is
allowed. This means that the integer value can still be used to test a signal. But in
Java, the exchange of the Boolean value and integer is not allowed, even though
the casting operation is used. The following is an example of the use of the
Boolean data type to represent the status of a room.

class test1 {
public static void main (String args[]){
Boolean dark;
dark = true;

while (dark) {
System.out.println(“Switch on lights”);
dark = false;
}//while
}//main
}//class

In the previous example, we declare a dark variable as a Boolean type.


Therefore, this variable can only take the true or false value. Then, we give an
initial value as true. When this variable is made a requisite for the while loop
and its value tested, then this requisite is fulfilled because dark is valued as
true.

Therefore, the statement for the while loop body would be executed, that is,
output „switch on lights‰ would be printed on the display. Then, the dark
variable is assigned the false value. Logically, after the lights are switched on,
the room would no longer be dark. Thus, it is appropriate if the dark variable
value be given false value. The accomplishment of the program would exit
from the loop because the loop requisite is no longer valid.

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA  111

At the end of this section, you should be able to list the types of data that could
be used in developing a Java program and differentiate the four data types that
have been discussed. In the subsequent subtopic, we will learn how to name and
declare a variable with the appropriate data type.

ACTIVITY 5.2
You wish to develop a program to evaluate students based on the
marks obtained. What is the type of data involved in the development
of the said program?

EXERCISE 5.1

State the appropriate data type for the following values:

(e) 51;

(f) ă31444843;

(g) 3.14; and

(h) 5.301E ă 10.

5.2 VARIABLES, DECLARATION AND


CONSTANT
Programs manipulate data that are stored in memory. In machine language, data
can only be referred to by giving the numerical address of the location in
memory where it is stored. In a high-level language such as Java, names are used
instead of numbers to refer to data. It is the job of the computer to keep track of
where in memory the data is actually stored; the programmer only has to
remember the name. A name used in this way  to refer to data stored in memory
 is called a variable. Figure 5.1 and Figure 5.2 show the concept of memory
location in a CPU of a computer.

Figure 5.1: Memory location showing the name and value of variable age

Copyright © Open University Malaysia (OUM)


112  TOPIC 5 BASIC CONSTRUCTS OF JAVA

Figure 5.2: Memory location showing the name and value of variables age and name

A variable in Java is designed to hold only one particular type of data; it can
legally hold that type of data and no other. The compiler will consider it to be a
syntax error if you try to violate this rule. In the previous subtopic, you have
learned data types that could be used in a Java program. This subtopic will
describe how to name variables to be used according to the Java specification.

Remember: Declaring a variable will involve data type and the variable name.

You must focus on the content of this subtopic because when you fail to declare
the right variable, it will cause the Java program that has been developed to be
uncompilable and not able to be excuted if a variable is not properly declared.

5.2.1 Name of Variable


Names are the basics to programming. In programs, names are used to refer to
many different sorts of things. In order to use those things, a programmer must
understand the rules for giving names to things and the rules for using the names
to work with those things (Eck, 2006). The rule to name a variable in Java is as
follows:

(a) The name of a variable must start with a letter;

(b) The name of the variable must consist of letters and digits; and

(c) The name of the variable cannot use JavaÊs reserved word.

The definition of letter and digit in Java encompasses a wider meaning than other
programming languages. The letter is defined as characters „A‰ ă „Z‰, „a‰ ă „z‰,
„_‰, „$‰ or any Unicode characters that symbolises a letter in a particular
language. For example, French users can use the character “Ç” in a name
variable; while Greeks can use the “µ” character. The same goes for digits. Digits
are from „0‰ ă „9‰ and any Unicode characters that symbolises a digit in a
particular language. Symbols such as „+‰ or „©‰ and also empty spaces cannot
be used in the name of a variable.

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA  113

Java is sensitive towards cases. This means the capital letters and the small letters
are considered different characters. There is no limit to the length of the name of
a variable. The reserved words for Java cannot be used as the name of the
variable.

Table 5.4 lists the Java reserved words.

Table 5.4: Java Reserved Words

abstract extends interface super


Boolean false long sure
break final native switch
byte finally new synchronised
Case float null this
Cast for operator throw
continue implements public var
default import rest void
Do inner return volatile
double instance of short while
Else int static
catch future outer
throws char generic
package transient class
goto private
true
const if protected try

There is also a style in naming the variable, especially if that name consists of
several words. The rule discussed before does not allow empty space characters
to be used to separate words. The most popular among the programming
community is by starting the first word with a small letter and the capital letter to
start each of the next words. The character „_‰ is not selected even though it does
not break the above rules. The following is an example of the name of a variable.

studentName, totalMarks, pricePerunit

is the style suggested compared to

student_name,total_marks,price_perunit

Copyright © Open University Malaysia (OUM)


114  TOPIC 5 BASIC CONSTRUCTS OF JAVA

ACTIVITY 5.3
You intend to develop a program on workersÊ salary systems. Try to list
down the variables that represent the information that is going to be
used.

5.2.2 Variable Declaration


Like other programming language, Java claims each variable be declared first
before it is used. The variable declaration is done by placing the data type first
followed by the name of the variable. The syntax for variable declaration is given
as follows:

data_type name_variable;

Some examples of declaration are shown as follows:

class test2 {
public static void main (String args[]){

byte presentStatus;
int n;
long distanceInInches;
Boolean stillStudying;
char grade;

}//main
}//class

Each declaration ought to end with „;‰ because the declaration is a complete Java
statement. We can also declare several variables in a line such as:

class test3 {
public static void main (String args[]){

int x, y, z;
Boolean haveEaten, sleepy;
}/main
} //class

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA  115

However, normally only one variable is declared in a line to enable us to write


comments about it. The following is an example of how variables are declared
with comments written:

class test4 {
public static void main (String args[]){

long distanceInInches; //distance between earth and sun


Boolean stillStudying; //informs present status
char grade; //grade for programming course

}//main
}//class

5.2.3 Constant
The variable whose value is always constant, which means it does not change,
is known as constant. The reserved word final is used in this constant
declaration as in the following format:

public static final data_type name_constant=value_constant;

The reserved word public shows that the constant declared can be accessed and
used by any method in class where it is declared even in other classes. static
means that this constant has not accomplished any operation on other objects.
The word final means the value for the constant is permanent and cannot be
changed by any other Java statement.

data_type is a type of data for name_constant that is declared.


name_constant is the name intended for the constant and it has to abide by the
rules of naming the variable. However, to differentiate with other variables,
normally each character in the name_constant is written using capital letters.
value_constant is the value intended to relate to that constant. The following
is an example of the constant declaration.

class test5 {
public static void main (String args[]){
public static final double Pl = 3.14159;
public static final int COUNT = 10;
}//main
}//class

Copyright © Open University Malaysia (OUM)


116  TOPIC 5 BASIC CONSTRUCTS OF JAVA

Pl is declared as the double type constant with a value of 3.14159. Meanwhile,


the COUNT is declared as int type constant with a value of 10. The value of a
particular constant cannot be changed in the program other than the initial value
that is assigned to it. For example, see the following declaration:

class test6 {
public static void main (String args[]){

final double PI = 3.14159


PI = 3.2549; //error – cannot change value for constant
} //main
}//class

5.2.4 Comment
As in other programming languages, comments in Java do not appear in the
output of the programs. Java has three ways to write comments.

(a) Comments to the Last Line


This type of comment is the most popular. It is used to write comments on
line. This type of comment starts with //.

class test7 {
public static void main (String args[]){
System.out.println(“Welcome”); //one line comment
}//main
}//class

(b) Comment Block


Comment block is usually used to write comments that exceed one line. It
starts with /* and ends with */.
class test8 {
public static void main (String args[]){

/* This is a comment example that exceeds one line.


Therefore, it needs to be written in block form. */
}//main
}//class

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA  117

After reading through this subtopic, you should be able to declare a variable with
the appropriate data type. You should also enable to differentiate the three types
of comments and how to use them.

ACTIVITY 5.4

You know the type of comments that can be used logically. Do you
know the importance of comments in a program?

EXERCISE 5.2

State whether the following variables are valid or otherwise. For the
variables that are invalid, please state the reasons:

(a) nameLength;

(b) Name_length;

(c) Import;

(d) 43650BBB;

(e) BBB43650;

(f) touch&go;

(g) touch-and-go;

(h) 2nd;

(i) break; and

(j) OUM.

Answer the following questions to test your knowledge on what you have
learned in this topic.

Copyright © Open University Malaysia (OUM)


118  TOPIC 5 BASIC CONSTRUCTS OF JAVA

5.3 ASSIGNMENT STATEMENT, INITIAL


VALUE AND CHANGING NUMERIC VALUE
After the variable is declared, it has to be given initial value using an assignment
statement. Normally, the compiler would give a warning message if there is a
variable with no initial value.

5.3.1 Assignment Statement


In Java, the only way to get data into a variable is with an assignment statement.
An assignment statement in Java has the following form:

variable = expression;

where expression refers to data or its computation whereas variable is any


name of variable that has been declared. The expression can consist of any
variable, constant, expression or a combination of the three that is linked by the
operator such as +, ă, /, * and others that can produce a value.

When the computer comes to an assignment statement when executing a


program, it evaluates the expression and puts the resulting data value into the
variable. For example, consider the simple assignment statement (Eck, 2006):
discount = 100;

The variable in this assignment statement is discount, and the expression is the
number 100. The computer executes this assignment statement by putting the
number 100 in the variable discount, replacing whatever was there before. Now,
consider the following assignment statement, which might come later in the same
program:

newPrice=oldPrice–discount;

Here, the value of the expression oldPrice–discount is being assigned to the


variable newPrice. In the expression, the ă is a substraction operator that
tells the computer to subtract the value of discount from the oldPrice. The
names oldPrice and discount are themselves variables, and it is the values
stored in those variables that are to be computed (Eck, 2006).

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA  119

5.3.2 Initial Value


The following program shows how a variable is given an initial value:

class test9 {
public static void main (String args[]){

int age; // declaration of int variable


char sex; // declaration of the char variable
Boolean status; // declaration of the Boolean
age = 10; // assigned value 10 for age
gender = ‘M’; // assigned character ‘M’ for sex
status = false; // status has value false
}//main
}//class

Java allows both declaration and giving initial value to be executed on the same
line. For example:

class test10 {
public static void main (String args[]){

int age = 10; // initial value of age is 10


Boolean status = false; // initial value of status is
// false
long lengthBridge = 8864L;
double weight = 37.266;
float average = 67.35F;
double pressure = 26.77e3;
}//main
}//class

The declaration of the variable can be placed anywhere in the code so long as it is
declared before the variable is used. However, a variable can only be declared
once in a method. The contents of the variable may change based on the last
assigned expression and it has only one value.

Copyright © Open University Malaysia (OUM)


120  TOPIC 5 BASIC CONSTRUCTS OF JAVA

5.3.3 Changing Numeric Value


In general, the type of the expression on the right-hand side of an assignment
statement must be the same as the type of the variable on the left-hand side.
However, in some cases, the computer will automatically convert the value
computed by the expression to match the type of the variable.

Java does not face problems in executing the multiplication operation of an


integer of the int type with a double type real number. The result of this
multiplication is double. Generally, any binary operation on a numeric value
from a different type is acceptable and the result would be evaluated as follows:

(a) If one is of the double type operant, the other operant would be changed
to double.

(b) On the other hand, if one of it is a float type operant, the other operant
would be changed to float.

(c) Also, if one of it is a long type operant, the other operant would be
changed to long.

The same principle applies to integer types: int, short and byte.

There is a possibility that we may assume a double number as an integer. The


numeric change is allowed in Java, unfortunately there may be information lost.
This happens if the casting operator is used. The syntax for the casting operator is
by providing parenthesis for the target type that is desired followed by the name
of the variable. For example:

double grandTotal = 100.89;


int ringgit = (int) grandTotal;

The value assigned to the ringgit is 100. Changing the floating point value to int
would cut off the decimal portion of the float point value. If we wish to round up
a floating point number to the nearest integer, use the Math.round method:

double grandTotal = 100.89;


int ringgit = (int) Math.round(grandTotal);

The sum assigned to the ringgit is 101. Note that the use of the casting
operation (int) is still needed. This is because the value returned by the round
method is a long type, and a long value can only be changed to int value with
the casting operator.

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA  121

The Java compiler will not give any warning if we try to change a certain number
from one type to another, which is outside the target type range. Therefore, a
good programming practice is testing whether the intended value to be changed
is within the target type range before change can be made.

Java allows the change in value of a particular variable from one type to another
without the casting operation following this sequence:

byte short int long float double

and

char int

A value of a type that occurs earlier in this list can be converted automatically to
a value that occurs later. For example, according to Eck (2006):

int A;
double X;
short B;
A = 17;
X = A; // Acceptable; A is converted to a double
B = A; // illegal; no automatic conversion
// from int to short

In some cases, you might want to force a conversion that would not be done
automatically. For this, you can use casting. For example, according to Eck (2006):

int A;
short B;
A = 17;
B = (short)A; // Acceptable; A is explicitly type cast
// to a value of type short

You can do casting from any numeric type to any other numeric type. However,
you should note that you might change the numeric value of a number by type-
casting it. You can also type-cast between the type char and the numeric types.
The numeric value of a char is its Unicode code number. For example, (char)97
is „a‰, and (int)‘+’ is 43 (Eck, 2006).

Copyright © Open University Malaysia (OUM)


122  TOPIC 5 BASIC CONSTRUCTS OF JAVA

SELF-CHECK 5.1

What is meant by assignment statement and initial value?

EXERCISE 5.3

The following Java program has a few mistakes. Rewrite the program
by correcting the mistakes.

class Error {
public static void main (String[ ] args){
width = 15
area = length * width;
System.out.println(“Area is “ + area);
}
}

After knowing how to give initial value to variables and performing binary
operations to numerics with different data types without data lost, you will learn
in detail about operators and the operatorÊs operation that involves numeric
values in the next subtopic.

5.4 OPERATOR
In developing a program, we will use mathematical operations to do the
calculation. In this topic, students will be exposed to the arithmetic operations,
assignment, increment and decrement that could be used in a Java program.

Arithmetic operation, assignment as well as addition and reduction in Java is the


same as in C language.

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA  123

5.4.1 Arithmetic
Table 5.5 below shows the operator and operation that is used in Java. The
operation for this operator is the same as in C language.

Table 5.5: Arithmetic Operator

Operator Operation
+ Addition
ă Subtraction
* Multiplication
/ Division
% Residue(modulo)

The / operator refers to the integer division if both operands are integers. This
means that the results obtained are integers. If otherwise, the division is division
of real numbers. The % operator meanwhile refers to the integer residue. Look at
several examples that are shown in Table 5.6.

Table 5.6: Example of the Division Operation and Modulo

Operation Result
5/2 2
5.0 / 2 2.5
5.0 / 2.0 2.5
5 / 2.0 2.5
5%2 1

Copyright © Open University Malaysia (OUM)


124  TOPIC 5 BASIC CONSTRUCTS OF JAVA

5.4.2 Multiple Assignments


Multiple assignment operators provide a short cut to using an arithmetic
operation in the assignment statement. The following Table 5.7 shows a multiple
assignment operator, an example of its usage and the meaning of that assignment
statement.

Table 5.7: Multiple Assignment Operator

Operator Example Meaning


+= no += 7 no = no + 7
ă= no ă= 7 no = no ă 7
*= no *= 7 no = no * 7
/+ no / = 7 no = no / 7
%= no % = 7 no= no % 7

5.4.3 Addition and Reduction


As in C and C++, the addition and reduction operator are used in the same way.
Only one operant is involved in this operation. The operant must be a variable
from the integer type. There are two forms of usage of the addition and reduction
operator, which are known as a prefix or postfix of a variable. The following
Table 5.8 shows an addition and reduction operator, an example of its usage and
the meaning of each particular operator.

Table 5.8: Addition and Reduction Operator

Operator Usage Meaning


i++ Add value i by 1 after being used in a statement
++
++i Add value i by 1 before being used in a statement
iăă Reduce value i by 1 after being used in a statement
ăă
ăă i Reduce value i by 1 before being used in a statement

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA  125

This operation will change the value of the variable. Therefore, it cannot be done
on a constant, for example 7++. See several examples as follows:

class test11 {
public static void main (String args[]){

int i = 1;
int j = 1;
int x = 7–++i;//the value of x is 5, and i becomes 2
int y = 7–j++;//the value of y is 6, and j becomes 2

}//main
}//class

Note that the values of x and y are different even though the original value of i
and j are the same. This is because in the third statement, the value of i is added
by 1 first before subtracting from 7 while in the last statement, the original value
of j is subtracted from 7 and then only added by 1. The use of the addition and
reduction operator in the statement can cause confusion which is difficult to
trace. Therefore, the use of this operator is not encouraged in statements such as
the examples shown previously. However, it can be used in the following cases:

int n = 0;
n++; // alternative to n = n + 1;

5.4.4 Relational Operators


Java has Boolean variables and Boolean-valued expressions that can be used to
express conditions that can be either true or false using a relational operator.
Relational operators are used to test whether two values are equal, whether one
value is greater than another and so forth. The relation operators in Java are: ==,
!=, <, >, <=, and >=. The meanings of these operators are shown in Table 5.9.

Table 5.9: Relations Operator

Operator Operation Example Value


== Same as 2==3 False
!= Not same as 2!=0 True
< Less than 3 <4 True
> More than 4>3 True
<= Less than or same as 4<=4 True
>= More than or same as 3>=4 False

Copyright © Open University Malaysia (OUM)


126  TOPIC 5 BASIC CONSTRUCTS OF JAVA

These operators can be used to compare values of any of the numeric types. They
can also be used to compare values of type char.

Boolean expressions are used intensively in loop and branch statements. But you
can also assign Boolean-valued expressions to Boolean variables, just as you can
assign numeric values to numeric variables.

By the way, the operators == and != can be used to compare Boolean values.
This is occasionally useful. For example, can you figure out what the following
program does?

class test12 {
public static void main (String args[]){
int age=30, height=40;
Boolean status;
status = ((age > 20) == (height > 55));
}//main
}//class

Relational operators <, >, <=, and <= are not used to compare values of type
string.

Please remember that Java uses different symbols for assignments and
equivalence tests. Assignments use symbol „=‰ while equivalence tests use the
symbol „==‰. For example, the value

(9 = = 6)

is false. Java avoids the possibility of the occurrence of errors arising from the use
of the symbol „=‰ at places where the symbol „==‰ is used.

If you use several operators in one expression, and if you do not use parentheses
to explicitly indicate the order of evaluation, then you have to worry about the
precedence rules that determine the order of evaluation.

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA  127

Table 5.10 shows the priority level of the numeric operator including relations.

Table 5.10: Level of Operator Priority

Priority Order Operator


1 ()
2 ++ ăă
3 */%
4 +ă
5 <> <= >=
6 == !=

Operators on the same line have the same precedence. When they occur together,
unary operators and assignment operators are evaluated right-to-left, and the
remaining operators are evaluated left-to-right.

For example, A*B/C means (A*B)/C, while A = B = C means A = (B = C). Let us look
at the following examples:

Example 5.1: Evaluating 2 + 4/2

2+4/2

2 + 2 = 4

(Note: 4/2 will be evaluated first as the operator/has higher priority than
operator +)

Example 5.2: Evaluating (2 + 4)/2

(2 + 4) / 2

6 /2 = 3

(Note: Those operands and operators in the parentheses will be evaluated first as
parentheses have the highest priority. Thus 2 + 4 in the parentheses will be
evaluated first and the result will be divided with 2).

Can you evaluate the expression 2 + (4/2) ă 4/2 ă (6 ă 2/2)? The answer is ă3.

Copyright © Open University Malaysia (OUM)


128  TOPIC 5 BASIC CONSTRUCTS OF JAVA

5.4.5 Boolean Operators


„And‰, „or‰, and „not‰ are the Boolean operators in Java that allow us to do
complicated conditions (see Table 5.11).

Table 5.11: Boolean Operators

Operator Meaning Value


&& AND Boolean
| | OR Boolean
! NOT Boolean

In Java, the Boolean operator „and‰ is represented by &&. The && operator is
used to combine two Boolean values. The result is also a Boolean value. The
result is true if both of the combined values are true, and the result is false if either
of the combined values is false. For example, „(x == 0) && (y == 0)‰ is true if and
only if both x is equal to 0 and y is equal to 0.

The Boolean operator „or‰ is represented by ||. The expression „A || B‰ is true if


either A is true or B is true, or if both are true. „A || B‰ is false only if both A and B
are false.

The && and II operators are evaluated using a short cut method. This means in
evaluating the following statement,

(valueA && valueB)

if the statement or the A value variable has been evaluated as false, therefore the
statement or B value variable need no longer be evaluated to obtain the overall
value of that statement.

The Boolean operator „not‰ is a unary operator. In Java, it is indicated by ! and is


written in front of its single operand. For example, if test is a Boolean variable,
then,

test = !test;

will reverse the value of test, changing it from true to false, or from false to true.

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA  129

In conclusion, you should have recognised the operators that could be suitably
used with arithmetic operations that will be used in a particular Java program.

EXERCISE 5.4

1. Give the value for each of the following arithmetic statements:

Statement Value

(a) 4 + 5.0 * 6;

(b) (4 + 5) * 6;

(c) 4 + 5 / 6;

(d) (4 + 5) / 6;

(e) 4 + 5 % 3;

(f) (4 + 5) % 3;

(g) 9 % 2 * 7 / 3; and

(h) 5.0 / 2 * 3 % 2.

2. What are the values of j and k after the following statement has
been executed? Assume that value j is 5 and value k is 7 before
the statement is accomplished.

(a) k + = j;

(b) k ă = j ++;

(c) k * = ++ j *2;

(d) k / = 25 * j ăă; and

(e) k % = j ă 3.

Copyright © Open University Malaysia (OUM)


130  TOPIC 5 BASIC CONSTRUCTS OF JAVA

 There are two basic blocks of programming: data and instructions.

 To work with data, you need to understand variables and data types which is
the focus of this topic.

 As other programming languages, Java is rich with various constructs that


should be understood by learners.

 This topic has discussed the basic Java constructs that should be known by
learners to enable them to write a complete Java program which is free from
errors.

Boolean Expression
Boolean operator Relational operator
Data types Variable

Copyright © Open University Malaysia (OUM)


Topic  Control
Structure and
6 Method
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Describe the three structures in a control structure;
2. Develop programs using selection structures;
3. Develop programs using repetitive structures;
4. Describe the syantax of declaring a method in Java; and
5. Develop Java programs that have method overloading.

 INTRODUCTION
As highlighted in Topic 5, there are two basic aspects of programming: data and
instructions. To work with data, you need to understand variables and data types;
to work with instructions, you need to understand control structures and methods.
This topic will focus on control structures and methods. Variables and types have
been elaborated in Topic 5.

Copyright © Open University Malaysia (OUM)


132  TOPIC 6 CONTROL STRUCTURE AND METHOD

6.1 CONTROL STRUCTURE


A program is a sequence of instructions. In the ordinary „flow of control‰, the
computer executes the instructions in the sequence in which they appear, one after
the other. This condition is called sequence accomplishment. In programming, the
statement that will be accomplished next is not necessarily located in the next line.
This scenario is known as transfer of program control. Bohm and Jacopini
conducted research in the 1960s and concluded that all programs can be written in
a structured way by using only three control structures, as shown in Table 6.1.

Table 6.1: Three Control Structures

Type of Control Structure Meaning


Sequence structure Sequence of instructions is executed sequentially line by
line.
Selection structure Selection structure allows the computer to decide between
two or more different courses of action by testing
conditions that occur as the program is running.
Repetitive structure Repetitive structure allows a sequence of instructions to be
repeated over and over.

Source: Bohm & Jacopini

These three structures are capable of changing the flow of control in a program,
can be implemented in the Java language. The following subtopics will touch on
this.

6.2 SELECTION STRUCTURE: IF, ELSE,


SWITCH, BREAK
Selection structure allows the computer to decide between two or more different
courses of action by testing conditions that occur as the program is running.

There are three forms of selection structures in Java:

(a) Single selection;

(b) Bi-selection; and

(c) Multi-selection.

Single selection as in C, is implemented using the if statement.

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  133

6.2.1 The If, Else Statements


Let us now learn about the if, else statements.

(a) Single Selection


The following is an example of the if algorithm for selection structure:

If your age is more or the same as 55,


Print “Compulsory Retirement”

What is Algorithm?
Algorithm is a step-by-step problem-solving procedure written in natural
language such as English.

The above algorithm can be translated to the Java code as

if (age > = 55)


System.out.println(“Compulsory retirement”);

The if syntax structure can be written generally as follows:

if (expression)
statement;

In Java, the expression value is from the Boolean type, that is, the
expression has true/false values. Therefore, the expression value besides
the true or false is invalid to be used in the expression.

(b) Bi-selection
Bi-selection provides other alternatives if the requisite is not fulfilled. The
following is an example of an algorithm condition, where one of the choices
is accomplished.

If your age is less than 55


Print “Still Eligible for Employment”

If not
Print “Compulsory retirement”

Copyright © Open University Malaysia (OUM)


134  TOPIC 6 CONTROL STRUCTURE AND METHOD

Let us look at Figure 6.1 which shows the selection structures in bi-selection.

Figure 6.1: Selection structures in bi-selection

The above algorithm can be translated to the if-else structure as

if (age < 55)


System.out.println(“Still eligible for employment”);

else
System.out.println(“Compulsory retirement”);

The if syntax structure can be written generally as follows:

if(expression)
statement 1;

else
statement 2;

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  135

Generally, the syntax in the following Figure 6.2 represents the if-else
statement.

Figure 6.2: If-else statement

In the case of single selection, if the expression has false value, no action
will be taken. This is different with the case of bi-selection, where we are
given another alternative, that is, if the expression has false value,
statement 2 will be accomplished. With reference to the example before, if
the age is or more than 55, the words “compulsory retirement” will be
printed.

Copyright © Open University Malaysia (OUM)


136  TOPIC 6 CONTROL STRUCTURE AND METHOD

(c) Multi Selection


Multi selection enables the programmer to determine the actions that have
to be accomplished in certain conditions by imposing a requisite. Observe
the following algorithm:

If the race code is the same as ‘M’


Print “Malay”

If_not, race code is the same as ‘C’


Print “Chinese”

If_not, race code is the same as‘I’


Print “Indian”

If_not
Print “Others”

At any one time, only one situation can take place. We use the if-else if
structure. The Java code that is at par with it is:

if (raceCode == ‘M’)
System.out.println (“Malay”);

else if (raceCode == ‘C’)


System.out.println (“Chinese”);

else if (raceCode ==’I’)


System.out.println (“Indian”);

else
System.out.println (“Others”)

For example, say raceCode is valued ‘I’. With this value, the expression
raceCode ==’M’ will have false value, therefore the program control will
abandon the statement System.out.println (“Malay”); and tests the
next expression, that is raceCode == ‘C’. This statement also has a false
value and the action that matches it, that is, System.out.println
(“Chinese”); is abandoned. The next expression is tested and found that
the value to be true, then the expression System.out.println(“Indian”);
will be accomplished and the “Indian” string will be printed as shown in
Figure 6.3.

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  137

Figure 6.3: Selection structure in multi selection

Java also supports the use of the ? operator, which is sometimes very useful. The
expression

requisite ? statement1 : statement2

will accomplish statement 1 value if the requisite value is true.

Copyright © Open University Malaysia (OUM)


138  TOPIC 6 CONTROL STRUCTURE AND METHOD

On the other hand, if the requisite value is false, the expression will accomplish
statement2 value.

Boolean operators such as &&, || and ! also could be used in if expressions.

Example 6.1:

if (age >=10) && (age <=20)


System.out.println(“You are qualified”);

else if (age >20) && (age <=30)


System.out.println(“You are not qualified”);

else
System.out.println(“Input error”);

if expressions with combination of more than one Boolean operations is valid to


use such as shown in the code mentioned before. The Boolean operator && is also
used for range of numbers. Like the example before, for the age between 10 and 20
the system will print „You are qualified‰.

EXERCISE 6.1

What is the output that will be displayed by the following program


segment?
r = 2;
if (r > 1)
System.out.println (“AAA”);
else System.out.println (“BBB”);
if (r < 1)
System.out.println (“AAA”);
else System.out.println (“BBB”);
if (r ! = 1)
System.out.println (“AAA”);
else System.out.println(“BBB”);

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  139

6.2.2 Switch Statement


The multi selection structure is sometimes difficult or too long to write. Therefore,
Java also provides switch statements as its alternative. The following is the syntax
for the switch statement that can replace the if-else if statement (Eck, 2006).
Note that there is a break statement at each case block.
switch (expression) {
case constant-1:
statements-1
break;
case constant-2:
statements-2
break;
.
. // (more cases)
.
case constant-N:
statements-N
break;
default: // optional default case
statements-(N+1)
} // end of switch statement

Copyright © Open University Malaysia (OUM)


140  TOPIC 6 CONTROL STRUCTURE AND METHOD

A switch statement allows you to test the value of an expression and, depending
on that value, to jump to some location within the switch statement. The
expression must be either integer-valued or character-valued. It cannot be a
String or a real number. The positions that you can jump to are marked with
„case labels‰ that take the form: „case constant:‰ This marks the position the
computer jumps to when the expression evaluates to the given constant. The
default statement is optional to the programmers. It provides a default jump point
that is used when the value of the expression is not listed in any case label.
Following is the program segment for testing the choice made by the menu system:

int choice = 1;
switch (choice) {
case 1: … // choose menu 1
break;
case 2: … // choose menu 2
break;
case 3: … // choose menu 3
break;
case 4: … // choose menu 4
break;
default: … // wrong input
break;
}

The break statement can also be used to force program control exit any loop
blocks.

The decision on whether to use if or switch statement depends on the userÊs


requirements. if statement is normally used to make decisions based on the range
of the value or specific conditions while switch statement is used to make
decisions based on a integer or character value. Also, the value for every case
must be different. Let us look at Figure 6.4.

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  141

Figure 6.4: Selection structure in multi selection using switch and break

Copyright © Open University Malaysia (OUM)


142  TOPIC 6 CONTROL STRUCTURE AND METHOD

The following example shows the use of switch statement from the previous
example of if-else if structure:

switch (raceCode){
case ‘M’: System.out.println (“Malay”); break;
case ‘C’: System.out.println (“Chinese”); break;
case‘I’ : System.out.printn (“Indian”); break;
default : System.out.println (“Others”);
}

6.3 REPETITIVE STRUCTURE: WHILE, DO-


WHILE FOR
We use repeated actions to solve problems in everyday life. We also use repeated
actions to solve problems in programming. For example, assume that you want to
write a program that will add 100 numbers given by a user. To solve this problem
in programming, we could have two options: to solve it sequentially or to do it
using repetition in a loop. Both cases are shown in Table 6.2.

Table 6.2: Sequential versus Repetition

Task Perform Sequentially Task Perform Using Repetition


Read first number from user repeat (100 times)
Add it to the total Read number from the user
Read second number from user Add it to the total
Add it to the total
Read third number from user
Add it to the total
Read fourth number from user
Add it to the total
⁄.
⁄.
⁄.
⁄.
Read 99th number from user
Add it to the total
Read 100th number from user
Add it to the total

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  143

Observe that repetition takes few lines compared to sequential solution to


accomplish a same task. From here, you can see the advantages of using repetition
in loops. Loops allow a sequence of instructions to be repeated over and over.

The repetitive structure in Java is the same as in C, except that the expression that
is tested should take the Boolean value. Repetition can be implemented by using
one of the following structures: while, do-while or for.

6.3.1 The While and Do-while Statement


The while and do-while loop is frequently used when we are unable to estimate
how many times a statement block should be repeated. The while loop will only
accomplish a block_statement body as long as the expression value is
true. The general form is as follows:

while (expression) {
block_statement
}

The while loop will not be accomplished at all if the expression value is false
the first time it is tested. Notice the following example to find the addition integer
from 1 to 100.

/*Find the addition of the integers 1+2+3+99+…+100*/


sum = 0;
i = 1;
while (i <= 100) {
sum += i;
i++;
}

The while loop in the example before will stop when the value i exceeds 100.
When the i value exceeds 100, the requisite (expression) will become false.

For the repetitive structure while, there are four basic components that need to be
fulfilled.

(a) Initial Value


This value will assign initial value for the variable that will be used in the
loop. In our example, the i = 1 statement is the initial value;

Copyright © Open University Malaysia (OUM)


144  TOPIC 6 CONTROL STRUCTURE AND METHOD

(b) Stop Condition


This condition will be tested to determine whether the next iteration needs
to be accomplished. In the above example, i < = 100 is the stop requisite;

(c) The Process that Needs to be Accomplished


In our example, sum + = i statement will be accomplished if the requisite is
true; and

(d) Updated Statement


Normally, this statement is placed at the end of the loop. In our example, the
control variable, which is i will be updated i++.

In contrast, the do-while loop is a variation of the while loop. Its syntax is as
follows:

do {
Statement1
Statement2
……
……
StatementN
} while (condition);

For the do-while loop, the loop body will be executed first, then the condition
is evaluated. If the condition is true, the loop body will be executed. Otherwise
the loop will be terminated. The difference between while loop and do-while
loop is the order in which the condition is evaluated and the loop body
executed.

6.3.2 The for Statement


The for loop in Java takes the following general syntax:

for(initial_value;stop_condition;updated_statement){
block_statement
}

Unlike while and do-while statements, for loop is used for the number of loop
repetitions that are already known in advance.

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  145

We can give initial value to several variables that usually act as the calculator in
the first slot. Unlike C, Java allows int type variable to be declared and given its
initial value at this slot. However, it is only valid in the body or for loop block
where it is declared.

The second slot requisite is used to test the requisite that determines whether the
body of a for loop will be accomplished or not. The third slot explains updates
that describe how to update to change the initial_value (counter).
block_statement can consist of only one simple statement or a block. Therefore,
nested loop is also allowed.

The following is an example of the for loop:

for (int line = 1; line <= 5; line++){


System.out.println(‘HI ’);
}

The result that will be displayed is:

HI
HI
HI
HI
HI

The following examples show the comparison of three loop statements (while, do
while, for). The programs are to print number from 0 to 100.

While Do-While For


int x=0; int x=0; for(int x=0; x<=100;
while(x<=100){ do{ x++)
System.out.println System.out.printl {
(x); n(x); System.out.prinln(x)
x++; x++; ;
} }while(x<=100); }

Copyright © Open University Malaysia (OUM)


146  TOPIC 6 CONTROL STRUCTURE AND METHOD

6.3.3 The Break and Continue Statements


Sometimes we need to exit from a loop before the completion of the loop. In such
cases, use break statement to exit from the loop prematurely. The break
statement is used in while loop, do-while loop, for loop and also used in the
switch statement in the following form:

break;

When the computer executes a break statement in a loop, it will immediately


jump out of the loop. It then continues on to whatever follows the loop in the
program. Consider this example:

for (int line = 1; line < = 5; line++){


System.out.println(‘HI ’);
if (line==3)
break;
}

In this program, the program will exit the loop when the value of line becomes
3 even though the requisite for the loop line <=5. The result that will be
displayed is:

HI
HI
HI

The continue statement is related to break. A continue statement tells the


computer to skip the rest of the current iteration of the loop. However, instead of
jumping out of the loop altogether, it jumps back to the beginning of the loop and
continues with the next iteration (after evaluating the loop's continuation
condition to see whether any further iterations are required).

break and continue can be used in while loops and do-while loops. They can
also be used in for loops and switch statements. Note that when a break occurs
inside an if statement, it breaks out of the loop or switch statement that contains
the if statement. If the if statement is not contained inside a loop or switch,
then the if statement cannot legally contain a break statement. A similar
consideration applies to continue statements.

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  147

6.3.4 Nested Loops


A nested loop is a loop within a loop  an inner loop within the body of an outer
one. How this works is that the first pass of the outer loop triggers the inner loop,
which executes to completion. Then the second pass of the outer loop triggers the
inner loop again. This repeats until the outer loop finishes. Of course, a break
within either the inner or outer loop would interrupt this process.

The following is an example of a nested loop:

Outer loop Inner loop

For (int line = 1; line < = 5; line ++) {


For (int column = 1; column < = line; column++)
System.out.println (‘*’);
System.out.println ( );
}

The result that will be displayed is:

*
**
***
****
*****

Remember⁄⁄
If you use a break statement inside a nested loop (that is the inner loop), it will
only break out of that loop, not out of the loop that contains the nested loop
(outer loop).

ACTIVITY 6.1

Do you know how to compare the values of two numbers? What is the
suitable loop instruction?

Copyright © Open University Malaysia (OUM)


148  TOPIC 6 CONTROL STRUCTURE AND METHOD

6.3.5 Compound Statements


When using if/else, for while loops, there is one important concept that you should
know, that is, the compound statement. What is the compound statement? We will
start with two examples in order to explain the concept of compound statements.
Consider the following two examples:

Example 6.2:

1 int x=2;
2 if (x==2)
3 System.out.println(“Hi”);
4 System.out.println(“Hello”);
5 System.out.println(“Bye”);

Example 6.3:

1 int x=2;
2 if (x==3)
3 {
4 System.out.println(“Hi”);
5 System.out.println(“Hello”);
6 }
7 System.out.println(“Bye”);

The output for Example 6.2 is:

Hi
Hello
Bye

while the output for Example 6.3 is

Bye

Do you know why there is a difference between the output for the Example 6.2
and Example 6.3?

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  149

In Example 6.2, there are no braces { } for the if statement in Line 2. Thus, only
one statement that follows the if statement (that is Line 3) is subjected to the
condition of Line 2 (that is if Line 2 returns a true Boolean value then Line 3 will
be executed whereas Line 3 will not be executed if Line 2 returns a false value).
Line 4 and 5 will be executed irrespective of whether Line 2 returns a true or false
value.

In Example 6.3, there are braces { } for the if statement in Line 3 and Line 6. All
the statements inside the braces (Line 4ăLine 5) are subjected to the condition of
Line 2 (that is, Line 4ăLine 5 will be executed if Line 2 returns a true value whereas
Line 4ăLine 5 will not be executed if Line 2 returns a false value). Line 7 will be
executed irrespective of whether Line 2 returns a true or false value because it is
not inside the braces.

Line 4ăLine 5 in Example 6.3 is known as a compound statement. Any number of


statements can be enclosed within a set of braces, including other if and
compound statements as shown in the following example.

Example 6.4:

int x=2;
int y=3;
if (x==2)
{
if (y==1)
System.out.println(“Hi”);
System.out.println(“Hello”);
}
System.out.println(“Bye”);

The previous program will produce the following output:


Hello
Bye

Can you explain how we get this output?

Besides if-else statements, compound statements also could be included in for


and while loops such as in the following Example 6.5.

Copyright © Open University Malaysia (OUM)


150  TOPIC 6 CONTROL STRUCTURE AND METHOD

Example 6.5:

for (int a=1; a<=3; a++){


System.out.println(“Hi”);
System.out.println(“Hello”); Compound Statement
}
System.out.println(“**************”);
for (int b=1; b<=3; b++) Notice that there are no braces in
System.out.println(“Hi”); this line
System.out.println(“Hello”);

This program will produce the following output:

Hi
Hello
Hi
Hello
Hi
Hello
*********************
Hi
Hi
Hi
Hello

Can you explain how we get the this output?

EXERCISE 6.2

What is the output that is displayed from the following program segment?

(a) for (f = 0; f < 3; ++f)


for ( g = 0; g < 2; ++g)
System.out.println (f + “ “+ g + “ “);

(b) for (num = 1; num < 100; ++ num)


if (100 % num == 0)
System.out.println (num + “);

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  151

6.4 METHOD
Methods allow the programmer to modularise a program ă each method will
perform a single specialised task.

A method is a subprogram. When codes become long or repetitive, it is often


helpful to be able to decompose the task into separate methods. Such
decomposition has the effect of making each piece (method) smaller and
therefore easier to write and read.

In object-oriented programming such as Java, method plays an important role.

6.4.1 Types of Method in Java


In general, there are four types of methods that could be written in a class diagram
namely constructor operation, query operation, update operation and task
operation. Constructor method is used to create new objects for a class by giving
initial values for the attributes. The name of the constructor operation is the same
with the name of the class (we will learn more about constructor method in the
CDOP3203 course).

Query method is used to access only the objectÊs state and this operation does not
change the state of an object. Examples of this method are:

(a) getName();

(b) getPay();

(c) RetrieveID(); and

(d) checkPassword().

Update method is used to update or change the value of attribute(s) of an object.


This update operation will change the state of the object. Examples of this method
are:

(a) setName(); and

(b) updateAge().

Copyright © Open University Malaysia (OUM)


152  TOPIC 6 CONTROL STRUCTURE AND METHOD

Finally, task methods are used to perform some specific task. This method may
change the state of the object. Examples of this method are:

(a) calculateAge(); and

(b) convertToCelcius()

6.4.2 Creating a Method


Consider the following Java application that was discussed in Topic 1.

Program 1.2: Hello2.java (Class Definition)

1 // this program displays “Hello world”


2 class Hello2{
3 public void display()
4 System.out.println(“Hello world!”);
5 }
6 }

Line 3ă5 is the declaration of a method. A Java method is a set of Java statements
which can be included inside a Java program. Java methods are similar to functions
or procedures in other programming languages. Methods in Java could be divided
into two, namely:

(a) Library methods such as main(), max (x,y), sqrt(x); and

(b) User defined methods written by the programmer such as method


display() shown above in Program 1.2.

Irrespective of whether it is library method or user defined methods, the methods


in Java will take the following form:

<modifier access> <return_type> <method_name>


([<parameter_list>]) {
__ [<statements>]
}

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  153

Example 6.6:

Modifier return type Method name Parameters

public int getMax(int no1, int no2){

int max;
if (no1>no2)
max= no1;
else Method body
max= no2;
return max;

}
Return value

The <method_name> can be any legal identifier such as getAverage, setName,


calculateAge.

<modifier access> could be private, public or protected. The public access modifier
indicates that the method can be called from other program. The private indicates
that a method can be called only by the other methods from the same class. If we
do not declare any access modifier for a method, then the system will assume that
the method is public.

The <return_type> indicates the type of value returned by the method. If the
method does not return any value, then it should be declared as void as shown in
the following:

public void calculateAverage(){


…..
…..
}

If the method returns a value such an int value, then the method should be
declared as int as shown in the following example:

public int getAverage(){


Must int x=1;
matched int y=2
each other int average=(x+y)/2;
return average;
}

Copyright © Open University Malaysia (OUM)


154  TOPIC 6 CONTROL STRUCTURE AND METHOD

If the method returns a string value, then the method should be declared as
String as shown in the following example:

public String getAverage(){


…..
…..
return ..;
}

The same goes for other methods that return other data types such as float, double,
char and Boolean. Use return statement within the method to pass back value if
the method returns a value as shown in the next example:

public int getAverage(){


…..
return …..;
}

Note that the return statement should not be included within the method if it is
a void method.

public void getAverage(){


…..
return …..; /*ERROR! Cannot return value if the
method is void */
}

The <parameter_list> allows argument values to be passed into a method.


Parameters are optional, that is, a method may contain no parameters. Elements of
the list are separated by commas in which each element consists of its data types
and an identifier as shown in the next example.

Data type Identifier

Example 6.6:

Public int getPowerOfTwo(int no1){


int answer; /* any variable declared in a method are local
variable */
answer = no1*no1;
return answer;
}

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  155

Example 6.7:

/* Note that this program does not have return statement within the
method as it is a void method. */
public void calculateAverage(int no1, int no2) {
int average = no1/no2;
}

Example 6.8:

Public int getId(){


int id = 4567
return id;
}

Example 6.9:

public void displayName (String name){


System.out.println(“Your name is” + name);
}

The <method_name> and <parameter_list> together are called method


signature.

6.4.3 Calling a Method


When creating a method, you give a definition of what the method is supposed to
do. In order to execute the method, you need to call or invoke it. When a program
calls a method, the program control is transferred to the method. A method returns
control to the caller (that is the program) when its return statement is executed or
when its method ending closing brace is reached (if it is a void method). If the
method returns a value, a variable should be declared to receive the value returned
by the method. For example:

int max= getMax(34,67);

Arguments

If a method does not return any value (that is, it is a void method), then the method
must be a statement. For example:

calculateAge();

Copyright © Open University Malaysia (OUM)


156  TOPIC 6 CONTROL STRUCTURE AND METHOD

If a method has a parameter, then you need to include the arguments during the
method invocation. The arguments must match the parameters in order, number
and be compatible as defined in the method signature.

The following Example 6.10 shows a complete program which has method
declaration and method invocation:

Example 6.10:

class obj {
public static void main (String[ ] args ){
int a=67;
pass the
int b=80; value
int max=getMax(a,b);
System.out.println(“Maximum is “ + max);
}

public static int getMax(int no1, int no2){

int max; //local variable


if (no1>no2)
max= no1;
else
max= no2;
return max;
} return the result
}

When you invoke a method that has parameter(s), the value of the argument is
passed to the parameter in the method as pass-by-value. It means the value of
the variable represented as argument in the method invocation will be passed
to the parameter. The argument will not be affected regardless of the changes
made to the parameter inside the method.

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  157

Any variable declared inside a method is known as a local variable. Local


variables are only recognised inside its method.

Tips of Using Methods:


 Each method should be used to perform single tasks such as calculating
average, determining maximum number and so on.
 Avoid having a multiple tasks in a method such as calculating average and
determining maximum that are combined in one method.

6.4.4 Method Overloading


Consider the program shown in the previous Example 6.10. The method
getMax() will determine the maximum value between two integer numbers. But
what if you need to find which of the two floating-point numbers has the
maximum value? The solution is to create another method with the same name but
with different parameters as shown in the following program:

class obj {
public static void main (String[ ] args ){
int a=67, b=80;
float c=4.5f, d=89.7f;
int max1=getMax(a,b); //Line 5
float max2=getMax(c,d); //Line 6
System.out.println(“Maximum integer number is “ + max1);
System.out.println(“Maximum float number is “ + max2);
}

public static int getMax(int no1, int no2){ //first method


int max;
if (no1>no2)
max= no1;
else
max= no2;
return max;
}

Copyright © Open University Malaysia (OUM)


158  TOPIC 6 CONTROL STRUCTURE AND METHOD

public static float getMax(float no1, float no2){ //second


method
float max;
if (no1>no2)
max= no1;
else
max= no2;
return max;
}
}

Line 5 of the program will invoke the first method that will determine the
maximum value between two integer numbers. Line 6 will invoke the second
method that will determine the maximum value between two float numbers.

As you can see in the previous program, two methods with the same name have
been declared. This approach of declaring more than one method with the same
name but with different parameter list is known as method overloading. You
cannot overload methods based on different modifiers or return types.

 A program is a sequence of instructions.

 In the ordinary „flow of control,‰ the computer executes the instructions in the
sequence in which they appear, one after the other. This condition is called
sequence accomplishment.

 In programming, the statement that will be accomplished next is not


necessarily located in the next line. This scenario is known as transfer of
program control.

 Bohm and Jacopini conducted research in the 1960s and concluded that all
programs can be written in a structured way by only using three control
structures, namely: sequential structure, selection structure and repetitive
structure.

 Sequential structure in Java could be implemented using if, if-else, if-else if and
switch statements.

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE AND METHOD  159

 Repetitive structure in Java could be implemented using while, do-while


and for loops.

 Methods inside the program allow us to modularise the program. Thus, it


makes the program more readable and organised.

break method
case nested loops
continue Repetitive structure
do-while Selection structure
for Sequential structure
if switch
if-else while

Copyright © Open University Malaysia (OUM)


T op i c  Array, String
and Input
7 Reading
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Define array;
2. Write a Java program using array;
3. Write a Java program that is capable of performing string
manipulation; and
4. Write an interactive Java program using scanner class.

 INTRODUCTION
To recap, a program is a sequence of instructions that a computer can execute
to perform some tasks. There are two basic blocks of programming: data and
instructions. To work with data, you need to understand variables and data
types; to work with instructions, you need to understand control structures and
methods. All these have been elaborated in Topic 5 and Topic 6.

Like other programming languages, there are also three other important
constructs in Java listed as follows:

(a) Array;

(a) String; and

(b) Input reading.

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING AND INPUT READING  161

These constructs enable us to write a complete and comprehensive Java program


such as programs (just to name a few) that will:
(a) Process the marks of 100 students and determine the highest and lowest
marks;
(b) Determine number of characters in a string; and
(c) Enable an user to key in data during program run-time.

The next subtopics will elaborate on these constructs.

7.1 ARRAY

Array is a group of memory locations that are connected and have the same
name and data type.

Ever thought of a situation where we can use an array in a program? Consider


the following scenario:

„You have been required to write a program that will accept and store the
marks for five students‰.

For the above problem, you are just required to declare five variable types of
integers as shown below to store the studentsÊ marks:

int student1, student2, student3, student4, student5;

Now consider the following situation:

„You have been required to write a program that will accept and store the
marks for 500 students‰.

For the above problem, are you going to declare 500 variables shown as follows:

int student1, student2, student3, student4, …., student499,


student500;

It is very obvious that the above approach to write 500 variables is „tiring‰
and is not a good approach. The solution is to use array:

int[] student = new int [500];

Do not worry if you do not understand the previous declaration because we


will discuss it later.

Copyright © Open University Malaysia (OUM)


162  TOPIC 7 ARRAY, STRING AND INPUT READING

We need to state the name of the array and the location in order to refer to a
particular memory location in the array. Figure 7.1 shows a visual representation
of an array.

Figure 7.1: Visualisation of an array

Array allows the programmer to collect a number of data from the same type by
referring to only the name of a variable. Unlike C, the Java array is implemented
as an object. Thus, we only need to know how to use it without having to know
how it is implemented.

7.1.1 Array Declaration


An array object needs to be created in order to use it in a program. After it is
created, the size of the array cannot be changed easily. We will not discuss how
this size can change in this section. The following is the syntax of array declaration:

data_type[] name_variable = new data_type[size];

data_type is a type of data for elements that are intended for storing the array.
name_variable is the array name and size is the number of elements than can
be stored in the array.

Array is an example of an object where its creation has to be handled by the


programmer. This is accomplished by using a new operator. Without it, the array
object cannot be created. For example, the following statement would create the x
array object, which consists of 10 int data type elements.

Number of elements in the array


int[] x = new int[10]
Array name

Integer data type

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING AND INPUT READING  163

The definition and creation of the array object can also be done separately as
follows:

int[] x; This example is the same as above but


x = new int[10]; it consists of two steps

Another way to write the array definition as in C language is:

int x[] = new int[10];

Observe how the initial value can be provided during array declaration:

int[] number = { 3, 5, 4, 0};


char[] letter = {‘A’, ‘B’, ‘Z’, ‘E’};

The effect of the above declarations is shown as follows:

Number[0] 3
Number[1] 5
Number[2] 4
Number[3] 0

letter[0] A
letter[1] B
Letter[2] Z
letter[3] E

Notice that in the two examples before, the new operator is not used. We can also
give an initial value to an array that has no name definition shown as follows:

new int[] {3, 7, 4, 9, 11}

This statement will allocate a new array and add the value in parenthesis { }. The
sum of initial value will be calculated and the array size is determined according
to that sum. This type of syntax is used if we wish to send an array as a
parameter to a particular method without creating a localised variable for it. For
example:

printFiveEven(new int [ ] {2, 4, 6, 8, 10});

Copyright © Open University Malaysia (OUM)


164  TOPIC 7 ARRAY, STRING AND INPUT READING

actually is the abbreviation for

int[] evenNum = {2, 4, 6, 8, 10};


printFiveEven(evenNum); //send as a parameter in method

To refer to an array element, the usual method used in C can be used, that is by
stating the array name and its index. For example:

x[0] = 10;
x[1] = x[0] * 10;

7.1.2 Array as Object


When the array is assumed as an object, then it has attributes and methods that
can be executed.

(a) Length Attribute


To determine the size of the array, use the statement

array_name.length

length is an attribute for the array that stores information on the size of
the array. For example:

int[] evenNum = {2, 4, 6, 8, 10};


for (i = 0; i < evenNum.length;i++)
System.out.println(evenNum[i]);

Here evenNum.length is the size for the array evenNum. By referring to


the previous evenNum array, this means that the value for
evenNum.length is 5. Therefore, the for loop above will be executed
five times and will print the contents of the evenNum array beginning from
the index 0 to evenNum.length-1, that is 4.

(b) arraycopy( ) Method


We can copy the contents of an array to another array by using the
arraycopy() method available in the class System. The syntax for
executing this task is as follows:

System.arraycopy(source, sourceIndex, target,


targetIndex, no);

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING AND INPUT READING  165

This method is further elaborated as follows:


(i) source ăIs the source array name whose contents are intended for
copying.
(ii) target ă Is a new array which will store values that are copied.
(iii) sourceIndex ă Indicates the start of the content position of the array
that is to be copied from the source array.
(iv) targetIndex ă Shows the start of the position at the target array
that will be used to store the values that are to be copied.
(v) no ă Is the number of the values copied.

The following is an example of the program segment that shows how three out of
five values are copied from the evenNum array to the newNum array.
int[]evenNum = 2, 4, 6, 8, 10};
int[]evenNum = {1000, 2000, 3000, 4000, 5000, 6000};
System.arraycopy(evenNum, 1, newNum, 2, 3);
for (i = 0; i < newNum.length; i++){
System.out.println(“newNum[“+i+”]after
copying: “+newNum[i]);
}

arraycopy()method was used to copy the evenNum array element starting


from index 1 position. The number of elements copied is three, therefore the
elements that are copied are 4, 6, 8. These elements that are copied are then
stored in the evenNum array starting from the index 2 position. Therefore, the
newNum[2]element, newNum[3]and newNum[4]each would be replaced by the
values 4, 6 and 8. The figure below shows the memory space for both arrays after
the given program segment is executed:

Figure 7.2: Array memory space

Copyright © Open University Malaysia (OUM)


166  TOPIC 7 ARRAY, STRING AND INPUT READING

The output obtained from the accomplishment is:

newNum[0] after copying is 1000


newNum[1] after copying is 2000
newNum[2] after copying is 4
newNum[3] after copying is 6
newNum[4] after copying is 8
newNum[5] after copying is 6000

Did You Know that ⁄


We are allowed to assign an integer array to another integer array such as
follows:

int[ ] array1= {12,33,45};


int[ ] array2;
array2=array1;

The effect obtained is both arrays refer to a set of the same data. Changes in
one of the arrays will affect both arrays. The following visual will help you to
understand this explanation:

array1 Index Value


0 12
1 33
2 45
array2
Observe that array1 and array2 are pointing to the same memory location.

SELF-CHECK 7.1

You have already learned about arrays. Can you state the difference
between an array and a string?

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING AND INPUT READING  167

EXERCISE 7.1

1. Each declaration in the table as follows contains errors. Give


reason for the errors.

(a) int intA[ ] = new double[10];

(b) int intA[ ] = new int[1.5];

(c) double doubleA = newdouble [-10];

(d) int intMatrik[ ][ ] = new int[10];

2. Assume that the declaration below was made and state whether it
is valid or otherwise. Give the reasons.
int j[ ] = new int [10];
char k [] = new char[6];
int x = 7, y = 2;

double m = 0.0;

(a) j[0]

(b) k[0]

(c) c[1.0]

(d) k[‘j’]

(e) k[j]

(f) j[x + y]

(g) j[x % y]

(h) j[10]

(i) c[-1]

(j) j[j[4]]

Copyright © Open University Malaysia (OUM)


168  TOPIC 7 ARRAY, STRING AND INPUT READING

EXERCISE 7.1
3. The following program will create an array and then values will
be assigned to this array. These values will be displayed. Observe
the usage of the for command in the program. In your opinion,
what will be the output? Compare your answer with the
computerÊs output.
arraycopy class {
public static void main (String[ ] args){

int[ ] anArray; //declare array of integer type


anArray = new int[10]; /* create array of integer
type with the size of 10 */

//assign values for each element and display the


content for (int i=0; i< 10; i++){
anArray[i]=i*2;
System.out.println( anArray[i] + “ “);
} //for
}//main
} //class

7.2 STRING
The character string, which is a combination of individual characters, is
implemented as a string class. We no longer need to declare a variable that
stores character string values as char type array. String constant consists of
character strings that are in between two inverted signs „ ‰. This includes the
empty space character that separates the words. Words, digits and special
characters such as +, ă, *, /, $, etc. could be assigned to string variables in Java.

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING AND INPUT READING  169

7.2.1 String Declaration


Let us look at the following example for string declaration:
String zero = “ ”;//an empty string
String university = Open University Malaysia”;
String courseCode = “CDOP3103”;
String courseName= “Object Oriented Programming”;

Each declaration of the character string as shown in the given example is an


object from the String class.

7.2.2 String Operation


Like array, string is implemented as an object. Thus, we only need to know how
to use it without having to know how it is implemented.

Java supports various manipulations of the character string. Next is the


discussion on the operations that can be carried out on the String class.

(a) Combining Strings


Java uses the „+‰ operator to combine two strings.

String son = ‘Firdaus’;


String Father = ‘Mohd’;
String myName = son + father;

In the previous example, the use of the „+‰ operator will produce myName
character string with the value “FirdausMohd”. Note that there is no
empty space in this string. The „+‰ operator only acts to combine two
strings according to the sequence that is stated.

When we try to combine a character string with a constant or variable


that is not a character string, the constant value or the variable would
be changed to character string. All Java object class can be changed to
character string with the „+‰ operator. Note the following example:

String software = “OFFICE” + 2010;

Copyright © Open University Malaysia (OUM)


170  TOPIC 7 ARRAY, STRING AND INPUT READING

Here the software is assigned to “OFFICE2010”. This approach is


normally used in output statements and it mostly helps when we intend to
print constant string and variable values. The following is one of its
examples:

System.out.println(“Software that is used” +software);

The output obtained from the accomplishment of the previous statement is


as follows:

Software that is used OFFICE2010

(b) Substring
To obtain only part of the complete string, we use the substring()
method. This method is a library method available in String class. For
example, let us look at the following program segment:

String IPTS = “Open University Malaysia”;


String S = IPTS.substring(0,4);

This program segment will create a substring “University”. Java


calculates the character in a string starting from 0 (the same as C and C++).
For example, the “O” character in the IPTS string is the character that is at
the 0 position, character „p‰ is at position 1, „e‰ in position 2, „n‰ at
position 3 and so on.

The call for substring() method in the previous example pass two
parameters, that is 0 and 10. The second parameter is the first position in
the IPTS string that we do not intend to copy. In this case, what we intend
to accomplish is to copy the character from position 0 to 9. Therefore, the
substring() method will calculate from position 0 (included) to position
10 (excluded).

The advantage of the calculation method used by the substring()


method is that we can obtain the length of a substring. The length of
s.substring (a,b) is b – a. Therefore, the length of substring “Open”
is 4 ă 0 = 4.

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING AND INPUT READING  171

(c) Length of String


To find the length of a string, use the length() method.

String IPTS = “Open University Malaysia”;


int length = IPTS.length( ); //length value is 27

Note here that length()is a method. This is different from the length
attribute that represents array size.

(d) String Comparison


To test whether two strings have the same value, we can use the equals()
method. The expression,

s.equals(r)

returns the true value if s and r strings are the same and false if
otherwise. s and r can be either constant or a string variable.

If IPTS has “Open University Malaysia” value, then the statement

“Greetings”.equals(IPTS)

has false value.

To compare two strings without concerning whether they are capital or


small letters, use the equalIgnoreCase()method.

“OPEN UNIVERSITY MALAYSIA”.equallgnoreCase(IPTS)


// this statement will return true value

Never use the „==‰ operator to compare two strings. This operation will
only check whether both strings are stored in the same location. Definitely
the string stored at the same location will have the same value. But we can
also store many strings that have the same value at different locations.

ACTIVITY 7.1

String class has made available more than 50 methods to manipulate


the string. Explore the list of methods in the java.lang.String class
which can be found at https://goo.gl/TyK3yy

Copyright © Open University Malaysia (OUM)


172  TOPIC 7 ARRAY, STRING AND INPUT READING

EXERCISE 7.2
1. Consider the following declaration:
String hannah = “Did Hannah see bees? Hannah did.”;
(a) What is the value displayed by hannah.length()?
(b) What is the value returned by invoking
hannah.charAt(12)?

2. The following program demonstrates the usage of length,


charAt and getChars which are the methods of the string
library. The method getChars is not discussed in the module.
Please refer to other reference books to understand the function of
this method. What is the output produced by the following
program upon execution? Compare your output with the
computerÊs output.

public class string {


public static void main( String args[ ])
{
String s1, output;
char charArray[ ];
s1 = new String(“hello there”);
charArray = new char[5];
output = “s1:” + s1;
output += “\nLength of s1:” + s1.length( );
output += “\nThe string reversed is:”;
for (int count = s1.length( ) – 1; count >= 0;
count––)
output += s1.charAt(count) + “ ”;
s1.getChars(0, 5, charArray, 0);
output += “\nThe character array is:”;
for (int count = 0; count < charArray.length;
count++)
output += charArray[count];
System.out.println(output);
}//main
}//class

Please use a different sheet to write the output.

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING AND INPUT READING  173

7.3 USING SCANNER TO CAPTURE INPUT


The Scanner class, introduced with J2SE 5.0, is a very useful new class capture
inputs for the primitive data types.

For example, the following code shows how to read an integer from the
keyboard:

Scanner scanner = new Scanner (System.in); int i =


scanner.nextInt ();

For each of the primitive types there is a corresponding nextXxx() method that
returns a value of that type. Example of nextXxx() methods that you can use to
capture inputs are shown in Table 7.1.

Table 7.1: Example of nextXxx() Methods

Methods Purpose
nextInt() To capture integer data type
nextFloat() To capture float data type
nextDouble() To capture double data type
next() Reads a string that ends before a white space
nextLine() Reads a line of character

The following program demonstrates how to read int and float values from
the keyboard.

The statement „import java.util.*;” without the codes must be written in


the beginning whenever you want to use Scanner class in your program.

import java.util.*;

/** Demonstrate the Scanner class for input of numbers.**/


public class UsingScanner
{
public static void main (String arg[]) {

// Create a scanner to read from keyboard


Scanner scanner = new Scanner (System.in);

System.out.printf ("Input integer: ”);


int val1 = scanner.nextInt ();
System.out.println ("You entered " +val1 +"\n");

Copyright © Open University Malaysia (OUM)


174  TOPIC 7 ARRAY, STRING AND INPUT READING

System.out.printf ("Input float: “);


float val2 = scanner.nextFloat ();
System.out.println ("You entered " +val2 +"\n");

} // main

} // class UsingScanner

The output for the previous program is given as follows:

Input integer: 23431


You entered 23431

Input float: 1.2343


You entered 1.2343

EXERCISE 7.3

Write a Java program that will accept three integer numbers from a user
and display the maximum number among these three inputs.

7.4 OUTPUT FORMATTING


How can you format a numeric value or numeric number in Java? For example,
how you can obtain 12.53 from 12.5323468787 or 1,267 from 1267.

We can use the command from the library class DecimalFormat to format the
numbers.

As an example, the statement as follows will display the first three digits after the
decimal point:

DecimalFormat num = new DecimalFormat(“.000”);

The following statement will display three digits of a number as an output. If the
number is less than three digits, then 0 will be appended at the front. If the digits
of a number are greater than three, then all the digits in the number will be
displayed.

DecimalFormat num = new DecimalFormat(“000”);

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING AND INPUT READING  175

Try to execute the following program and see the effect.

import java.text.*; //compulsory if you are using


DecimalFormat

class uji{

public static void main (String[ ] args){


int papar=6;

DecimalFormat num = new DecimalFormat(“000”);


System.out.println(num.format(papar));
System.out.println(num.format(18));
System.out.println(num.format(124));
System.out.println(num.format(23455));
}
}

Now, replace the following statements to the statements that have been bolded in
the previous program.

DecimalFormat num = new DecimalFormat(“0,000.000”);

Can you see any difference in the output upon executing the program?

 This topic focuses on array, string and how to capture input from the user
during program runtime.

 An array is a group of memory locations that are connected and have the
same name and data type.

 The string class in Java enables us to perform various manipulations on the


string.

 An interesting thing in writing the Java program is that the reading input
process from the keyboard is not as simple as expected.

 In this module, you have learned to write Java programs in a structured


manner. If you are interested in writing Java programs in an object-oriented
manner, you are encouraged to take CDOP3203 ă Java Programming course.

Copyright © Open University Malaysia (OUM)


176  TOPIC 7 ARRAY, STRING AND INPUT READING

Array String

Scanner class

Copyright © Open University Malaysia (OUM)


 ANSWERS 177

Answers
Suggested Answers to Exercises for Topic 2

Exercise 2.1
(a) functional

(b) non-functional

(c) functional

(d) non-functional

(e) could be regarded as either

Exercise 2.2
Functional requirements:

 register members

 track overdue videos

 produce a daily upload file for the general ledger

 print letters for members on their birthdays.

Non-functional requirements:

 speed of the system should allow a video borrowing transaction to be


completed within one minute

 the barcode reader should be at least 99.5 per cent accurate

 a front desk clerk should be able to become familiar with all the functions of
the system within one week.

Copyright © Open University Malaysia (OUM)


178  ANSWERS

Exercise 2.3
Customer (or member)  primary or secondary  depending on whether the
customer directly interacts with the system. Suggest to the client, Victoria, that
for the first version of the system, members are secondary and the front desk
clerk interacts with the system. Later versions could allow customers to borrow
their own videos.

Front desk clerk  primary  This actor deals with the members and includes
joining, borrowing videos and asking questions.

Back office clerk  primary  This actor deals with all the back office functions
such as sending data to the general ledger system. (You might find out later that
this „actor‰ is actually several actors.)

Stocktaker  primary or secondary  depending on implementation. More


information is required on what a stocktake entails.

Management  secondary, as their reporting needs are met from the data
warehouse. Sufficient information is needed to run the business.

Security manager  primary  maintains the user names to control access to the
system.

Data warehouse  external  needs a daily update of data.

Cash register terminal  external  handles all financial transactions.

In addition, every primary user needs to be able to logon, logoff and change their
password.

Exercise 2.4
Borrow a video ă brief format for an initial version of the use case

This use case starts when the member finishes selecting their videos and brings
them to the front desk. The front desk clerk asks to see their membership card.
The clerk then enters the memberÊs number into the system. The front desk clerk
then scans the barcodes of the memberÊs videos. The system calculates the price
according to whether the videos are new releases, current releases or other and
the price is displayed on the cash register terminal. The customer pays by credit
card or cash and then leaves the shop with their videos.

Copyright © Open University Malaysia (OUM)


ANSWERS  179

The most important actor is the front desk clerk because this actor serves the
members. After all, if there were no members, then the video shop would go out
of business. Similarly, if nobody borrowed any videos, then it would be time to
pack up and go home.

Exercise 2.5
The following list has the main use cases that you might have identified. Note
that there are other use cases, which we will find during later analysis. You
might have already thought of some of these yourself. Obviously the more use
cases you find earlier, the easier the whole process is.

Actor Use Cases Notes or Issues


Front desk clerk Borrow videos This use case interacts with
the cash register
Return videos
Create members Need to decide if still using
membership cards
Enter a reservation
Members This includes both changing
and deleting
Search for titles
Back office clerk Generate birthday letters
Stocktaker Do stocktake Not very well understood at
this stage
Internal Generate data for the
data warehouse
Security manager Maintain valid users
Everyone Logon
Logoff
Change password
Get online help

Copyright © Open University Malaysia (OUM)


180  ANSWERS

Exercise 2.6
Return videos

This use case is used when a member returns videos. The front desk clerk scans
the videos and the system is updated to show the videos as returned.

(As you can see, some use cases are very simple.)

Generate birthday letters

The back office clerk performs this use case approximately once a week. The
system displays the range of birthday dates that was last produced. The clerk
then selects another date range, usually another week. The system produces the
letters. The clerk puts the letters in envelopes and posts them.

Exercise 2.8
Alternate flows in borrow videos

 The memberÊs number might be invalid. Ask clerk to re-enter the number.

 Member might have overdue videos. They are not allowed to borrow any
more videos, so end the use case.

 Member might have fines to pay for videos that were returned late. They
must pay the fines as well as the fees for the new videos.

Copyright © Open University Malaysia (OUM)


ANSWERS  181

Exercise 2.9
Borrow videos

Actor Intention System Responsibility


Identify the borrower Confirm borrower exists
Identify the videos Calculate the total fees due for any past fines and the
new borrowings
Pass the total amount due to the cash register terminal
Identify the videos Record videos as returned

Exercise 2.10
Here are just a few examples. They are many, many more:

 Is it true that members will not use the computer system, that is, will
everything be done through the clerk?

 How are the members going to identify themselves?

 Tell me about stocktakes. What are the issues? What are you trying to
achieve?

 Who will support and maintain the system?

 Have you thought about transferring the data from the old system to the new
system?

 Is any auditing required?

Copyright © Open University Malaysia (OUM)


182  ANSWERS

Exercise 2.11

Points to note about this diagram:

 See how the member is shown on the left-hand side. While they have no
direct interaction with the system, it is useful to see where they fit in.

 While the cash register terminal is an external system from the point of view
of video tracking, sometimes it is useful to look inside it and see its use cases.
So, in this example we can see that there is a use case called „take money‰.
Please remember that this is not a dataflow diagram so we are not saying
anything about the data flowing between the two systems.

Copyright © Open University Malaysia (OUM)


ANSWERS  183

 Note how this diagram quickly gets very busy with lots of lines. This is why
the use cases that everyone uses, namely logon, logoff, etc., are not shown.
Later in the unit we will show you a way to deal with large systems with
hundreds of use cases.

Exercise 2.12

Exercise 2.14
Perhaps you can already envisage the answer, but let us work through it slowly.
We need a use case to sell old videos. So here is our first version:

Actor Intention System Responsibility


Identify the old videos Get the prices
Pass the total amount due to the cash register
terminal

What do you notice about the last line? It is the same as the last line of the
Borrow Videos use case.

So we could create a new subuse case called Process Payment.

Level: Subfunction
Actor Intention System Responsibility
Get payment Pass the total amount due to the cash register
terminal

Copyright © Open University Malaysia (OUM)


184  ANSWERS

Then, updating the other two use cases gives us the following:

Borrow Videos

Actor Intention System Responsibility


Get Borrower (note Display details of current borrowings
underline)
Identify the videos Calculate the total fees due for any past fines and the
new borrowings
Process Payment (note underline)

Sell Old Videos

Actor Intention System Responsibility


Identify the old videos Get the prices
Process Payment (note underline)

The use case diagram from Exercise 2.11 is now as follows:

Copyright © Open University Malaysia (OUM)


ANSWERS  185

Exercise 2.15a
Maintain Members

Extension point: At any point once the memberÊs details are displayed
Actor Intention System Responsibility
Get Borrower Display personal details (name, address, date
of birth, date joined, etc.), plus a summary of
current borrowings (for example, total number
borrowed, total number of overdues, current
number borrowed and current number
overdues)
Optionally, the user can Store the changes
modify the personal details
of the member
Optionally, the user can Check that the borrower has nothing borrowed
delete the member Delete the member

Print Borrower Details

Level: Subfunction
Trigger: User wishes to print the details of a member
Extension point: Anytime in Maintain Members
Actor Intention System Responsibility
Indicate that a printout is required Print the details

Copyright © Open University Malaysia (OUM)


186  ANSWERS

Exercise 2.15b
Business Rule Use Cases
Only members can borrow videos. Borrow Videos
When a new person requests to become a Handled by the clerk, not the
member, they must show ID. system
The minimum age is 16 years old. Handled by the clerk, not the
system
A member can borrow any number of Should be in Borrow Videos
videos, as long as they have no overdue
videos.
There are fines for overdue videos. Borrow Videos
Also look at Return Videos
The length of time that a video can be The Borrow Videos use case needs
borrowed for depends on the video. New to handle this
releases are only lent out overnight,
current releases are for three-day hire,
and the rest are for a week.
Members can reserve a video. Reserve Videos
Every video has a classification, (general The Classification and Category
G, parental guidance PG, mature are attributes of the Video
audiences MA and restricted R). Specification, so these are
Members must be over 18 to borrow R maintained by the use case
videos. Every video also has a category: Maintain Video Title, identified in
Romance, General, Sci-Fi, Foreign Exercise 4.5.
Language and Children.
When a member has a birthday, he is sent Generate Birthday Letters
a special letter inviting him to borrow any
video of his choice for a week for free.
Every three months the shop does a Do stocktake. Users have to
stocktake. remember to do it.
Any missing videos are updated to be Record Video Tape Missing. This
shown as missing. is the use case that we identified
in Exercise 4.4

Copyright © Open University Malaysia (OUM)


ANSWERS  187

Exercise 2.17
Conceptual Class Category Example
Physical or tangible objects Video CD
Specifications, designs or descriptions Video title
of things
Places Video shop
Front desk
Transactions Borrow a video
Return a video
Transaction line items Video CD
Roles of people Member
Front desk clerk,
Back room clerk,
Accountant
ă all the roles you identified would
go here
Abstract noun concepts Boring
Exciting
Organizations Companies that make videotapes
Banks
Events A new video is released
Processes Borrow a video
Return a video
Do a stocktake
ă many use cases fit here
Rules and policies Borrowing policy
Joining policy
Overdue policy
Catalog Video catalog
Manuals, documents, reference, paper, Member records
books New releases
New employee training

Copyright © Open University Malaysia (OUM)


188  ANSWERS

Exercise 2.18

Copyright © Open University Malaysia (OUM)


ANSWERS  189

Exercise 2.19

Copyright © Open University Malaysia (OUM)


190  ANSWERS

Exercise 2.20

Copyright © Open University Malaysia (OUM)


ANSWERS  191

Suggested Answers to Exercises for Topic 3


Exercise 3.1
The most obvious entity that we wish to track is each Video Tape.

The other entity for which a state diagram could be useful is the class Member.
The problem discussed did not mention that if a member has too many overdues,
then he is not allowed to borrow, but this is the sort of fact that should be verified
with individual users if a state diagram is used.

As we stated, it is not wrong to draw state diagrams for other classes, it is simply
that they will be very simple and you will not learn from them. But, of course,
the best way to find this out is to draw them.

Exercise 3.2
The first version for the state diagram for Video Tape might look like this:

Then you could think about how a video tape comes into existence. Clearly we
are missing a use case here ă let us call it Get New Video Tapes.

What about the final state? An initial answer could be to create another new use
case, this time called Retire Video Tapes. Clearly we have uncovered new
functionality and would need to go back to the users to discuss this. For example,
perhaps they try to sell some old video tapes.

Copyright © Open University Malaysia (OUM)


192  ANSWERS

So now the diagram looks like this:

Lastly, let us think about lost or missing video tapes. Once again, we would need
to discuss this with Victoria, and the answer could be the following:

Now to the state diagram for the member:

Copyright © Open University Malaysia (OUM)


ANSWERS  193

Exercise 3.3
Thirsty drinker: (to the BarBot) Can I have a glass of beer?

BarBot: (to the GlassTray) Get me a (clean) Glass?

GlassTray: (gets glass from GlassTray and passes it back to the BarBot)

BartBot: (passing empty Glass to BeerTap) Fill it up.

BeerTap: (to the Glass) How big are you?

Glass: (to the BarBot) 285ml.

BeerTap: (dispenses 285ml of beer into glass, and returns the filled
Glass to the BarBot)

BarBot: (passes full Glass to the drinker)

Exercise 3.4

Copyright © Open University Malaysia (OUM)


194  ANSWERS

Exercise 3.5

Copyright © Open University Malaysia (OUM)


ANSWERS  195

Exercise 3.6

Copyright © Open University Malaysia (OUM)


196  ANSWERS

Suggested Answers to Exercipses fopr Topic 5


Exercise 5.1
(a) short

(b) long

(c) float

(d) float

Exercise 5.2
(a) valid

(b) valid

(c) not valid


reserve word

(d) not valid


it starts with digit

(e) valid

(f) not valid


it has Â&Ê character

(g) not valid


it has ÂăÊ character

(h) not valid


it starts with digit

(i) not valid


reserve word

(j) valid

Copyright © Open University Malaysia (OUM)


ANSWERS  197

Exercise 5.3
class hasErrors {
public static void main (String[ ] args){
int width=15; //any values is acceptable
int length=20; //any values is acceptable
int area=length +width;
System.out.println(„Area is‰ + area);
}
}

Exercise 5.4
1. (a) 34.0

(b) 54

(c) 4

(d) 1

(e) 6

(f) 0

(g) 2

(h) 1.5

2. (a) j == 5 k == 12

(b) j == 6 k == 2

(c) j == 6 k == 84

(d) j == 4 k == 0

(e) j == 5 k == 1

Copyright © Open University Malaysia (OUM)


198  ANSWERS

Suggested Answers to Exercises for Topic 6


Exercise 6.1
Output:
AAA
BBB
AAA

Exercise 6.2
(a) 0
6
12
18
24
30
36

(b) 1
8
15
22
29
36
43

Suggested Answers to Exercises for Topic 7

Exercise 7.1
1. (a) intA is declared as integer array but was assigned with double array.

(b) The array size must be an integer value.

(c) doubleA is declared as double but was assigned with double array.
Also, the size of the array cannot be negative.

(d) intMatriks is declared as two dimensional array but was assigned


with one dimensional array.

Copyright © Open University Malaysia (OUM)


ANSWERS  199

2. (a) valid

(b) valid

(c) not valid

(d) valid

(e) not valid

(f) valid

(g) valid

(h) not valid

(i) not valid

(j) valid based on the syntax

3. Output:
0
2
4
6
8
10
12
14
16
18

Exercise 7.2
1. (a) 32

(b) e

2. Output:
s1: hello there
Length of s1: 11
The string reversed is: e r e h t o l l e h
The character array is: hello

Copyright © Open University Malaysia (OUM)


200  ANSWERS

Exercise 7.3
import java.util.*;

class GetMaxValue
{
public static void main( String args[ ] )
{
int temp, max;
Scanner scanner = new Scanner(System.in);

System.out.println("Enter first number:");


int no1=scanner.nextInt();

System.out.println("Enter second number:");


int no2=scanner.nextInt();

System.out.println("Enter third number:");


int no3=scanner.nextInt();

if (no1>no2)
temp=no1;
else
temp=no2;

if (temp>no3)
max=temp;
else
max=no3;

System.out.println("The maximum number is: "+max);


}//main
}//class

Copyright © Open University Malaysia (OUM)


MODULE FEEDBACK
MAKLUM BALAS MODUL

If you have any comment or feedback, you are welcome to:

1. E-mail your comment or feedback to modulefeedback@oum.edu.my

OR

2. Fill in the Print Module online evaluation form available on myINSPIRE.

Thank you.

Centre for Instructional Design and Technology


(Pusat Reka Bentuk Pengajaran dan Teknologi )
Tel No.: 03-27732578
Fax No.: 03-26978702

Copyright © Open University Malaysia (OUM)


Copyright © Open University Malaysia (OUM)

S-ar putea să vă placă și