Sei sulla pagina 1di 211

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 Directors: Prof Dato’ Dr Mansor Fadzil
Assoc Prof Dr Norlia T. Goolamally
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
Universiti Kebangsaan Malaysia

Developed by: Centre for Instructional Design and Technology


Open University Malaysia

Printed by: Meteor Doc. Sdn. Bhd.


Lot 47-48, Jalan SR 1/9, Seksyen 9,
Jalan Serdang Raya, Taman Serdang Raya,
43300 Seri Kembangan, Selangor Darul Ehsan

First Edition, August 2008


Copyright © The Open University of Hong Kong and Open University Malaysia,
October 2010, 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 W iii

Table of Contents
Course Guide ix ă xviii

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 10
1.2.4 Sending Message 13
1.2.5 Class 15
1.2.6 Inheritance 18
1.3 Object-Oriented Systems Modeling and UML 21
Summary 23
Key Terms 25

Topic 2: Static Modeling with UML 26


2.1 Use Case 27
2.1.1 Levels and Types of Requirements 28
2.1.2 Challenges of Writing Requirements 29
2.1.3 Types of Roles 31
2.2 Writing Use Cases 32
2.2.1 Goals and Levels of Use Cases 36
2.3 Use Case Diagrams 39
2.4 Activity Diagrams 40
2.5 Potential Problems With Use Cases 42
2.5.1 How to Deal With Hundreds of Use Cases 43
2.6 Relating Use Cases 44
2.6.1 The Include Relationship 46
2.6.2 The Extend Relationship 49
2.6.3 The Generalize Relationship 51
2.6.4 Business Rules and Use Cases 52
2.7 Analysis Class Diagram 54
2.7.1 Conceptual Classes 57
2.7.2 Identification of Conceptual Classes 58
2.7.3 Issues in Identifying Conceptual Classes 61
2.7.4 Specification Conceptual Classes 61
2.7.5 Associations 62
2.7.6 Other Issues of Association 68

Copyright © Open University Malaysia (OUM)


iv X TABLE OF CONTENTS

2.7.7 Attributes 70
Summary 73
Key Terms 74

Topic 3: Dynamic Modeling with UML 75


3.1 State Diagrams 76
3.1.1 Showing Super States 79
3.2 Collaboration Diagram 80
3.3 Sequence Diagram 83
3.4 Designing for Responsibilities 85
Summary 88
Key Terms 89

Topic 4: Introduction to Java 90


4.1 Java Environment 91
4.2 Characteristics of Java 92
4.3 Tools to Develop Java Programs 93
4.4 Writing Java Programs 94
4.5 Writing Text-Based Application Using Structured Approach 95
Summary 100
Key Terms 100

Topic 5: Basic Constructs of Java 101


5.1 Data Types 102
5.1.1 Integer 102
5.1.2 Real 103
5.1.3 Characters 104
5.1.4 Boolean 105
5.2 Variables, Declaration and Constant 106
5.2.1 Name of Variable 107
5.2.2 Variable Declaration 109
5.2.3 Constant 110
5.2.4 Comment 111
5.3 Assignment Statement, Initial Value & Changing
Numeric Value 112
5.3.1 Assignment Statement 112
5.3.2 Initial Value 113
5.3.3 Changing Numeric Value 114
5.4 Operator 116
5.4.1 Arithmetic 117
5.4.2 Multiple Assignments 117
5.4.3 Addition and Reduction 118

Copyright © Open University Malaysia (OUM)


TABLE OF CONTENTS W v

5.4.4 Relational Operators 119


5.4.5 Boolean Operators 121
Summary 123
Key Terms 123

Topic 6: Control Structure and Method 124


6.1 Control Structure 124
6.2 Selection Structure: If, Else, Switch, Break 125
6.2.1 The if, else Statements 126
6.2.2 Switch Statement 131
6.3 Repetitive Structure: While, Do-While For 134
6.3.1 The while and do-while Statement 135
6.3.2 The for Statement 136
6.3.3 The break and continue Statements 137
6.3.4 Nested Loops 138
6.3.5 Compound Statements 139
6.4 Method 142
6.4.1 Types of Method in Java 142
6.4.2 Creating a Method 143
6.4.3 Calling a Method 146
6.4.4 Method Overloading 148
Summary 149
Key Terms 150

Topic 7: Array, String and Input Reading 151


7.1 Array 152
7.1.1 Array Declaration 153
7.1.2 Array as Object 155
7.2 String 158
7.2.1 String Declaration 159
7.2.2 String Operation 159
7.3 Capturing Input from User during Runtime 163
7.3.1 Using Pembaca Class 163
7.4 Output Formatting 166
Summary 167
Key Terms 168
Answers 169
References 191

Copyright © Open University Malaysia (OUM)


TOPIK 2 KAEDAH DAN TEKNIK W 17

Copyright © Open University Malaysia (OUM)


COURSE GUIDE

Copyright © Open University Malaysia (OUM)


Copyright © Open University Malaysia (OUM)
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 by Faculty of Science and Technology, Open University Malaysia (OUM).

COURSE AUDIENCE
This course is offered to all students taking 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 able to learn independently and
optimise the learning modes and environment available to you. Before you begin
this course, please confirm the course material, the course requirements and 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: Approximate Study Time Allocation

STUDY ACTIVITIES STUDY HOURS

Understanding the course content and initial discussions 5

Reading 8 topics 60

Attending tutorial sessions 10

Online discussions 12

Completing assignment 15

Revision 18

TOTAL STUDY HOURS ACCUMULATED 120

LEARNING OUTCOMES
By the end of this course, learners 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 diagram, activity diagram, analysis,
sequence diagram, collaboration diagram and state diagram for a given
problem; and
4. Write Java programs in a structured manner.

Copyright © Open University Malaysia (OUM)


COURSE GUIDE  xi

COURSE SYNOPSIS
This course is divided into 7 topics. The synopsis for each topic is presented
below:

Topic 1: Introduction to Object Orientation


This topic will introduce the concepts of object orientation. In
particular, you will learn about object and its characteristics, class,
message passing mechanism between objects, object interface,
encapsulation and inheritance. Besides that, you also will be
introduced how UML is fit to develop object-oriented systems. In
specific, you will be shown some of the main UML diagrams that can
be used to perform static and dynamic modeling. This topic has been
included with many examples to reinforce your understanding about
object orientation.

Topic 2: Static Modeling with UML


System can be modeled 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 visualize the static features of system using
use case, use case diagram and analysis class diagram.

Topic 3: Dynamic Modeling with UML


This topic will focus on dynamic modeling using UML. Software
design is about behavior and behavior is dynamic. The ways a system
behaves in response to certain events or actions are the dynamic
characteristics of a system. Therefore an emphasis upon dynamic
models is very important in designing a system.

Topic 4: Introduction to Java


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

Topic 5: Basic Constructs of Java


There are two basic blocks of programming: data and instructions and
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 and data
types and its related concepts that could be implemented in Java

Copyright © Open University Malaysia (OUM)


xii  COURSE GUIDE

Topic 6: Control Structure and Method


As highlighted in Topic 2, 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 (such as if-else statement, switch-case
statement, loops, etc) and methods.

Topic 7: Array, String and Input String


Like other programming languages, there are THREE important
constructs in Java that enable us to write complete and comprehensive
Java programs such as programs that will (just to name a few):

 Process the marks of 100 students and determine the highest and
lowest marks.
 Determine number of characters in a String.
 Enable an user to key in data during program run-time.

These constructs are listed below and will be discussed in this Topic:
 Array
 String
 Input Reading

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

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 -

Copyright © Open University Malaysia (OUM)


COURSE GUIDE  xiii

It is compulsory for the students to read these readings as it will give them a
solid understanding of the particular concepts related to the course. These
readings is part of the syllabus. Hence, it can be tested for the tests and 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.

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

Copyright © Open University Malaysia (OUM)


xiv  COURSE GUIDE

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 pre-requisile knowledge is required to take this course

ASSESSMENT METHOD
Refer to myVLE for information on assessment method for this subject.

COURSE ASSESSMENT
Refer to the latest announcement in myVLE.

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 a Computer-base Virtual
Learning Environment, known as MyVLE. The system have a number of
functionalities which enable the students to access OUMÊs digital library,
communicate with the tutors and their fellow students. We strongly advised 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 objective

Copyright © Open University Malaysia (OUM)


COURSE GUIDE  xv

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


course materials.
3. To provide an opportunity for you to apply what you have learned by
completing some task and case studies.

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 assignment schedule below). 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 penalized 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, e.g. (Stott 2002, 38). 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 edn, London: ABC Publishing.

Assignment Schedule
Assignment will be posted to MyLMS before Tutorial 1.

Student are required to submit the assignment together with during Tutorial 4
Student will get their assignment marks from their tutors during Tutorial 5.
Please make sure to ask for the marks during this Tutorial 5. The tutor will post
his/her feedback of your assignment answer online via myLMS.

Tutorials
The course includes 5 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 discussed 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

Copyright © Open University Malaysia (OUM)


xvi  COURSE GUIDE

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.

Tutorial Guideline (for tutors)


The following chart gives a general guideline on the Topics to be discussed on
each tutorials:

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 the following two case studies.
You are required to read and understand the following case studies prior of
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.

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

Copyright © Open University Malaysia (OUM)


COURSE GUIDE  xvii

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 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Ês 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, etc.

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.

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

Copyright © Open University Malaysia (OUM)


xviii  COURSE GUIDE

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, C(2002), page 29 - 31)

The case study is the NextGen point-of-sale (POS) system. In this case study we
shall see that there many interesting requirement and design problems to solve.
This is a realistic problem as organizations really do write POS system using
object technologies. A POS system is a computerized 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 computer and bar code scanner and
software to run the system. It is interfaced to various service applications such as
third party tax calculator and inventory control. These system must be relatively
fault-tolerant. A POS system increasingly must support multiple and varied
client-side terminals and interfaces. These include Web browser, a regular PC
which supports graphical user interface (GUI), touch screen input, wireless
PDAÊs, 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 customization. Using an iterative development strategy, we are
going to proceed through requirements, object-oriented analysis, design, and
implementation.

Copyright © Open University Malaysia (OUM)


T o p ic 1 X Introduction 
to Object 
  Orientation 
LEARNING OUTCOMES
 
When you have completed this topic, you will be able to:
1. Diffentiate between algorithmic and object-orientation approaches;
2. Give example to decribe object-orientation approach;
3. Describe the important object-oriented concepts;
4. Desribe how Unified Modelling Language (UML) can be used for
modeling object-oriented systems; and
5. Name few UML diagrams used for systems modeling.

X INTRODUCTION
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 or sub-
problems, each of which is then solved independently.

Copyright © Open University Malaysia (OUM)


2 X TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

Prepare Lunch

Make French Make Make Hot


Fries Sandwich Chocolate Drink

Figure 1.1: Lunch Preparation using Algorithmic Approach

One 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 preparing lunch. The solution designed is based
on the algorithmic approach. One important thing in the algorithmic approach is
that it concentrates on the processes aspect of the program.

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 objectoriented 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. 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 W 3

To illustrate, letÊs 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 is
determined as follows:

• Waiter object is responsible for integrating all the relevant activities;


• French fries cook object is responsible for frying the French fries;
• Sandwich maker object is responsible for preparing the sandwich; and
• Hot drink machine object is responsible for preparing hot drinks.

Figure 1.2 shows the solution based on the object-oriented approach. Notice how
the above 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:

1. A packet of French fries message is sent to the French fries cook


object;
2. Chicken sandwich message is sent to the Sandwich maker object;
and
3. A cup of hot chocolate drink message is sent to the Hot drink
machine object.

Figure 1.2: Lunch Preparation based on an Object Orientation Approach

Copyright © Open University Malaysia (OUM)


4 X 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
insights about object-oriented programming.

1.2.1 Objects
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 behavior 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 shortly.
A few object examples are given as follows:
• A car with plate number JEU 875;
• The carÊs steering; and
• The carÊs front left wheel.

(a) Object Has State


Every object has properties that collectively represent its state. For example,
consider the vending machine object. The following are few properties of
the object:
• Number of can drinks that are not yet sold;
• Total money in the machine; and
• Total money that was inserted by the customer when buying.

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

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION W 5

reference. For example, the car object has a property, where its value is a
reference to its four wheels objects.

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 behavior is influenced by its state. This will be explained later.

Exercise 1.3

Identify four attributes of a car object. Give an example of object 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 occurs which change the state
of the object that receives the message or the state of the object that sends
the message.

Again, letÊs 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 less one now.

Copyright © Open University Malaysia (OUM)


6 X 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 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 sequence 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 W 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

Copyright © Open University Malaysia (OUM)


8 X TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

other records store data about three computer users. 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).

This situation can compromise the reliability of the database system.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION W 9

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 do 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.

Exercise 1.5

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

Copyright © Open University Malaysia (OUM)


10 X TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

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 fifteen 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 donÊt need to know about how the fried rice is prepared in the restaurant.
You donÊt 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.

EXERCISE 1.6

Give a few 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

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION W 11

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

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 changes 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

Copyright © Open University Malaysia (OUM)


12 X TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

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 doesnÊt 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.

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
doesnÊt know how the Square object is going to implement its respond to the
message send by the client. For example, the client doesnÊt know the formula
used by the object to calculate the circumference. Moreover, the client doesnÊt
know whether the Square object has changed the formula as long as the value
returned is correct.

Figure 1.10: Interface and Object Encapsulation

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION W 13

EXERCISE 1.7

1. Give an example of interface for the ATM machine.


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

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 doesnÊt 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 model the collaboration of objects. For
example, Figure 1.12 shows the communications that occur between the objects to
change a studentÊs course grade in a student information system. 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.

Copyright © Open University Malaysia (OUM)


14 X TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

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.

Figure 1.12: Objects Collaborating in Message Sending

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION W 15

1.2.5 Class
A big and complex object oriented software system usually involves too many
objects, attributes and behaviours. An example of the system is the student
record system in a university. In this system, the student is modeled 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

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 donÊt 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
Copyright © Open University Malaysia (OUM)
16 X TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

object in the Student class has the same attributes and behaviours defined in the
class (see Figure 1.14).

Figure 1.14 shows a Student class that has two parts:


(i) Attribute list for every object in the class has;
(ii) Behaviour list for every object in the class. Every behaviour that is listed
contains text that describes the objectÊs response.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION W 17

Figure 1.14: Class Specification for all the Student Objects

The object created from a class is sometimes called as 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 behaviour when received a
message.

Copyright © Open University Malaysia (OUM)


18 X TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

EXERCISE 1.8

Given as follows are several objects in Figure 1.15. 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 colour and location. Besides, the Shape class objects can also
understand the message setColour(newColour), which is to set the colour of
the object attribute to newColour.

Figure 1.16: Shape Class Specification

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION W 19

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
colour (from Shape class definition)
location (from Shape class definition)
width (from Square class definition)
height (from Square class definition)

Behaviours
changeColour(newColour) (from Shape class definition)
setWidth(newWidth) (from Square class definition)
setHeight(newHeight) (from Square class definition)

Figure 1.17: Class and its subclasses

Copyright © Open University Malaysia (OUM)


20 X TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

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 behaviour inherited from the
superclass, but have added some more characteristics and behaviours for
themselves. For example, after we have created Student class, we could also
define another class for diploma students, master 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 employee records system. You could create a generic
employee 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 code 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.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION W 21

1.3 OBJECT-ORIENTED SYSTEMS MODELING


AND UML
In the previous sections, you have learned all the important concepts that you
should know when dealing with object-oriented approach to develop software. A
system including object-oriented systems need to be examined from various
angles and its features need to be modeled 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 given as follows:
• 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.
• Dynamic: 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.
Source: http://www.developer.com/design/article.php/1553851

The static modeling which models the structural part of the system and dynamic
modeling 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 modeling and dynamic modeling
are the subsets that make up the systems modeling which is the key aspect of
most systems development methodology.

Systems modeling 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 visualize the system,
specify the structure and behavior of that system, construct the system, and
document the decisions made along the way. While this standard is not perfect

Copyright © Open University Malaysia (OUM)


22 X TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

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

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

• Use case
• Use case diagram
• Analysis class diagram

The above three UML diagrams will be elaborated in Topic 2.

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION W 23

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

• State diagram
• Sequence diagram
• Collaboration diagram

The 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 or sub-
problems, 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.

• 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.

• Object hides its implementation from the client. This is known as


encapsulation.

Copyright © Open University Malaysia (OUM)


24 X TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION

• 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.

• Class that inherits other class is known as subclass. Subclass has all the
characteristics and behaviour inherited from the superclass, but has added
some more characteristics and behaviours for themselves.

• A system including object-oriented systems need to be examined from


various angles and its features need to be modeled 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 modeling and dynamic modeling are the subsets that make up the
systems modeling, which is the key aspect of most systems development
methodology.

• Systems modeling for object-oriented systems makes extensive use of the


Unified Modeling Language (UML).

Copyright © Open University Malaysia (OUM)


TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION W 25

Algorithmic approach Object Orientation


Attribute Static modeling
Class Subclass
Dynamic modeling Superclass
Message Unified Modelling Language (UML)
Object

Copyright © Open University Malaysia (OUM)


T op i c 2 Static 
 
Modelling 
with UML  

LEARNING OUTCOMES
When you have completed this topic, you will be able to:
1. Describe the meaning of static modeling;
2. Write use case for a given problem;
3. Draw 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. Describe the issues in drawing an analysis class diagram;
7. Draw 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, interaction between the

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  27

modules, etc so that the implementation can be done without any bugs or defects.
Object-oriented system which is developed using object-oriented programming
normally will be modeled using object modeling techniques. UML is the common
„tool‰ used to perform object modeling in developing object-oriented systems.
UML was the result of the collaboration between three methodologists: Jim
Rumbaugh, Grady Booch and Ivar Jacobson.

System can be modeled 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 diagram and analysis class
diagram. The next topic will touch on using UML to perform dynamic modeling
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 to 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:
 Defining the purpose of the system, prioritising its functionality, and specifying
its context (i.e. who are its users and what systems does it interact with?).
 Identifying external interfaces, both human and system-to-system. The
technology of an existing system with which the system must interface can
constrain the requirements and design.

Copyright © Open University Malaysia (OUM)


28  TOPIC 2 STATIC MODELLING WITH UML

 Identifying major functionality that must be provided by the system and


describing it.
 Documenting assumptions upon which the requirements are based. If the
assumptions change, then so might the requirements.
 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 merger, etc. 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:
 Business requirements · these define the high-level processes that occur in
an organisation. For example, for a banking system, what is the purpose of
developing the new banking system? Is it going to replace an old system or is
it going to be used in a new line of business, etc.?
 System requirements · what the computer system must do for its users.
These are the functional requirements of the system.
 Internal requirements relating to technology, personnel, hardware platform
requirements, etc. 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. And 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)


TOPIC 2 STATIC MODELLING WITH UML  29

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 VideosS

In this topic, we will use VictoriaÊs Videos system, which you were
introduced to in Appendix 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 systems 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:

(a) Problem domain complexity


The biggest challenge is finding out about the problem domain (the
environment in which the system will operate, e.g. our video shop). This is

Copyright © Open University Malaysia (OUM)


30  TOPIC 2 STATIC MODELLING WITH UML

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Êve said already, 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. Recognizing
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.

The requirements analysis is progressively presented in the Use Case Model


for the functional requirements. 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.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  31

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Êll
look at actors further in the next section.
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. Step 4 is
not covered in the syllabus.

Figure 2.1: The main steps

2.1.3 Types of Roles


There are three kinds of roles or actors:
1. 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.

Copyright © Open University Malaysia (OUM)


32  TOPIC 2 STATIC MODELLING WITH UML

2. 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.
3. External · Any system that receives or generates data for the system ·
these are external systems, e.g. tax office system, bank, accounts system, etc.

Note that this taxonomy differs slightly from UML and in Larman (2002). In
particular, 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. Further, 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.

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

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  33

There are three types of format for writing use cases. The format to be considered
is depends on the need. The explanation for these three types of use cases format
are given as follows:
 Brief use case - it has one-paragraph summary and normally used for main
success scenario. Here is an example of 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).

 Casual use case ă it is an informal paragraph which has multiple paragraphs


that cover various scenarios. The Handle Returns shown in Reading 2.2 was
the example
 Fully dressed ă the most comprehensive that shows all the steps and variations.
It has supporting sections, such as preconditions and success guarantees.
Example of fully dressed use case for NextGen case study could be found at
http://www3.itu.edu.tr/~buzluca/ymt/ornek_uc.pdf. However, detail
discussion about fully dressed use case is beyond the syllabus.

Writing a use case is, to a certain extent, is like writing a report, and as you will
know if youÊve ever written a report, itÊs much easier if you can follow some kind
of format. Most companies and organizations 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. The full version and a detailed description of the template are
available at http://members.aol.com/acockburn/papers/uctempla.doc. Use case
templates are not covered in this course.

Copyright © Open University Malaysia (OUM)


34  TOPIC 2 STATIC MODELLING WITH UML

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.

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.

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


requirements must aim for goals that will bring value to the organization. This
means that a use case:
 must deliver something of value to an actor
 typically represents a major piece of functionality that is complete from
beginning to end
 represents the goal of an interaction between an actor and the system; the goal
represents a meaningful and measurable objective for the actor
 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 Section 2.2 is an example of success scenario.
Copyright © Open University Malaysia (OUM)
TOPIC 2 STATIC MODELLING WITH UML  35

 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 below:
condition:

handling

Example of alternate scenarios for Process Sale are given below (Larman, 2002)
based on the above format:

3a: Invalid item identifier found: condition


1. System signals error and rejects entry handling
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 above examples only have one handling for the conditions. There can be
more than one handling for certain conditions.

EXERCISE 2.7

Identify success scenarios and alternate scenarios for NextGen POS example.

Remember that a use case may has 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Ês 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.8

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 course mates.

Copyright © Open University Malaysia (OUM)


36  TOPIC 2 STATIC MODELLING WITH UML

Model such as Use Case Model help 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. Black-box use cases approach is usually
adopted to help system developers avoid making the same mistake twice. Let us
know discuss the term. Something is a black box if we cannot see the inner
workings of it. 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
donÊt 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. Example of black box use case 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 her goal as Âlogging inÊ, but in fact this is just the mechanism that
achieves the higher-level goal of identifying and authenticating herself. When writing
use cases, keep the user interface out and focus only on actor intent.

EXERCISE 2.9

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Ês 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

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  37

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. 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.4 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 myLMS to learn about goals and scopes of
use case.

Information systems are rather abstract entities that consist of software, hardware
and applications. However, even though we cannot visualize the whole
information system, for the purpose of use cases we need to define a boundary
for it. ItÊs 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:
1. Define the right system boundary
2. Identify the primary actors
3. Identify the actorsÊ goals
4. Define and name the use cases.

READING 2.2

Now download Reading 2.2 from myLMS to learn about four-step


procedures to define use cases as listed above.

Copyright © Open University Malaysia (OUM)


38  TOPIC 2 STATIC MODELLING WITH UML

EXERCISE 2.10

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:
 Read any documentation that has been collected.
 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.
 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Ês important that you understand the use case model as itÊs 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Ês sometimes helpful to approach a topic from a different
angle, weÊd like you to reinforce your understanding of the Use Case Model by
working through the next reading by Cockburn.

ACTIVITY 2.1

Internet Reading
Cockburn, A, ÂStructuring use case with goalsÊ at
<http://members.aol.com/acockburn/papers/usecases.htm>

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  39

2.3 USE CASE DIAGRAMS


Â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.

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

Figure 2.2: Use Case Diagram Notation

A collection of use case diagrams will form a context for use case diagrams that
shows the scope of the system, and the relationship between the actors and 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.
5.

READING 2.3

Now download Reading 2.3 from myLMS to learn about use case diagram in
detail.

Copyright © Open University Malaysia (OUM)


40  TOPIC 2 STATIC MODELLING WITH UML

EXERCISE 2.11

By using the example of use case diagram shown below 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.

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 or not.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  41

Figure 2.3: An Example of an Activity Diagram

EXERCISE 2.12

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)


42  TOPIC 2 STATIC MODELLING WITH UML

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 ten, identified by Susan Lilly (1999):
1. The system boundary is undefined or inconstant.
2. The use cases are written from the systemÊs point of view.
3. The actor names are inconsistent.
4. There are too many use cases.
5. The actor-to-use case relationships resemble a spiderÊs web.
6. The use-case specifications are too long.
7. The use-case specifications are confusing.
8. The use case doesnÊt correctly describe functional entitlement.
9. The customer doesnÊt understand the use cases.
10. The use cases are never finished.

In writing this list, Susan Lilly (1999) is not arguing against use cases, but trying
to alert newcomers to the potential problems, and suggest ways to avoid them.
She advises:
 Explicitly define the systemÊs boundary. This makes clear what is inside the
system and what is outside the system.
 Make use of a standardised template for documenting your use-case
specifications. If the team uses a template, it will help communications
between team members as well as help newcomers get started.
 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.
 DonÊt 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.

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Êve defined use case details; check that the system boundary has been

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  43

clearly defined, that obvious actors have not been missed and that the use cases
focus on the usersÊ goals.

EXERCISE 2.13

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 organize the use cases so
the team can understand them. One specific technique is to organize 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:
 By functional areas. For example, put everything to do with money in one
package, and inventory in another.
 By actor. For example, put all the cashierÊs use cases in one package.
 By ÂstyleÊ of use case. For example, put all the simple setup/maintenance
style use cases in one package.
 By importance or iteration. For example, all the use cases that are going to be
built first could be in one package.
 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.

Copyright © Open University Malaysia (OUM)


44  TOPIC 2 STATIC MODELLING WITH UML

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 emphasized 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.4: Use Case Package

2.6 RELATING USE CASES


As you remember, we first discussed use cases in Section 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/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)


TOPIC 2 STATIC MODELLING WITH UML  45

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
<http://www.therationaledge.com/content/mar_03/f_useCases_ij.jsp?fro
m= inbrief>

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:


 include · typically where a set of use cases each includes some common
functionality that is expressed in one shared sub-use case;
 extend · where the functionality of a use case is extended by referencing
other use cases; and
 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,
faces the same problem. The solution is to remember that use cases are for human
use.

Copyright © Open University Malaysia (OUM)


46  TOPIC 2 STATIC MODELLING WITH UML

ACTIVITY 2.3

Internet Reading
Jacobsen, I (2003) ÂUse cases · yesterday, today and tomorrowÊ at
<http://www.therationaledge.com/content/mar_03/f_useCases_ij.jsp?fr
om=inbrief>

Read pages 4ă5, i.e. the sections ÂUse cases and the unified modelling
languageÊ and ÂUse caution when formalising use casesÊ.

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 sub-use case, and then reference this sub-use 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Ês 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.1: 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
Now compare this use case with Borrow Videos (from the answer for the Exercise
2.9). Is there anything in common? Yes. The first line for each is the same:

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  47

Â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 she give us her name or an identification number? Will she need
to quote a password? So to cater for all these later concerns, we can create a sub-
use case that we will call ÂGet BorrowerÊ. And now both the Borrow Videos and
Identify Members use cases will ÿincludeŸ the Get Borrower sub-use 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.2: Inclusion a Sub-use 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 sub-use case.
So a short way of writing is simply to underline the use case name, as follows.

Table 2.3: Short way of writing the inclusion of a sub-use case

Maintain Members

Actor intention System responsibility


Get Borrower ⁄

The Get Borrower use case is then as follows.

Table 2.4: A sub-use Case

Get Borrower

Level: Subfunction
Actor intention System responsibility
Identify the borrower Display personal details (name, address,
date of birth, date joined, etc.) of the
borrower ⁄
You will notice the headings at the start of the use case that has level clause. It
tells us that this is a sub-use 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.
Copyright © Open University Malaysia (OUM)
48  TOPIC 2 STATIC MODELLING WITH UML

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.

Figure 2.5: Depicting the Include Relationship

EXERCISE 2.14

LetÊs 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 doesnÊt 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.11) with any new use cases.

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

As a first rule of thumb, always use the includes 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 [generalizes].

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.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  49

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Ês 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?

Copyright © Open University Malaysia (OUM)


50  TOPIC 2 STATIC MODELLING WITH UML

Table 2.5: 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 Confirm birthday borrowing has not
birthday letter already been used this year
Record use of birthday letter
Adjust total due

Once again you can see weÊre 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.6: 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.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  51

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.

Figure 2.6: Depicting the Extend Relationship

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.15A

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 specialized 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 specialized to the more general use case. This resembles the object-
oriented concept of sub-classing or inheritance, in practice it can be both useful
and effective to factor common behaviours. This is demonstrated as follows:

Copyright © Open University Malaysia (OUM)


52  TOPIC 2 STATIC MODELLING WITH UML

general use case

specialised use case

The generalization relationship also can be used for actors in the use case
diagram as shown below:

general actor

specialised actors

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 modeling. 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
<http://www.ebgconsulting.com/Capturing%20Business%20Rules.pdf>

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  53

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Ê at
<http://www.sdmagazine.com/documents/s=826/sdm0006j/>

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:
 list all the rules in one list, and then refer to the list from everywhere else ·
use cases, screen mockups, class diagrams, etc.;
 simply locate the rules in the use cases, as we have done in this course; and
 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 (e.g. does it involve lots of calculations), the size of the
application, the tools that are being used, etc.

So what are the business rules in VictoriaÊs Videos? Here are some examples:
 Only members can borrow videos.
 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.
 There are fines for overdue videos.
 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.

Copyright © Open University Malaysia (OUM)


54  TOPIC 2 STATIC MODELLING WITH UML

 Members can reserve a video.


 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.
 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.
 Every three months the shop does a stocktake.
 Any missing videos are updated to be shown as missing.

You should recognize 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.15B

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.

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 (i.e. what is included) and, have
some use cases and may be a use case diagram been 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 modeling using analysis class diagram. While the material is
presented to you sequentially, in reality the object-oriented modeling happens in
parallel with the use case writing.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  55

This section is all about „analysis class diagram‰. The example of an analysis
class diagram is shown below (Larman, 2002):

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 understand 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:
 Conceptual classes · conceptual classes represent business objects or
business entity or concept, e.g. shop, video CD, member, etc.
 Associations between conceptual classes · which define relevant
relationships, those that capture business information that needs to be
preserved, and their multiplicity, e.g. a shop has many video CDs, a member
borrows many video CDs.
 Attributes · which are logical data values of an object, e.g. 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 visualization of things in


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

Copyright © Open University Malaysia (OUM)


56  TOPIC 2 STATIC MODELLING WITH UML

Remember..
Analysis class diagram which is produced during the analysis phase is a
visualization 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.
Design class diagram is beyond of the syllabus.

EXERCISE 2.16

Before we go into the details of the domain model, letÊs make sure we are
clear about its function. Refer to the diagram below:

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 (e.g. 15 Jalan XYZ, Ipoh) and a name (e.g. 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 as depicted in the figure above. See if it gives you a better
understanding of the „payment sale‰ process of the NextGen POS case.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  57

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 some of the object-oriented literature
terms them). 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.7: 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 or she is probably talking about
the process that goes on in the factory rather than a specific car. So too in software
modeling 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 class that we will
encounter in business modeling:
 Concrete objects are tangible, i.e. 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.
 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 doesnÊt exist anymore. It can be
rebuilt. Similarly, video title is also a conceptual object.
 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

Copyright © Open University Malaysia (OUM)


58  TOPIC 2 STATIC MODELLING WITH UML

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 (e.g. 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
modeling 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:

 Symbol- words or images that represents a conceptual class


 Intension- the definition of a conceptual class
 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 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.

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 categorized conceptual classes into three broad categories,
namely concrete objects, conceptual objects and event and state objects. These

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  59

three categories are further expanded into finer categories according to Table 2.7
as shown below:

Table 2.7: Conceptual Class Category List


Source: Adapted from Larman (2002)

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 CreditPaymentAuthorizationSystem
system
Abstract Noun Concepts Hunger
Organization SalesDepartment
Events Sales, Payment, Meeting
Processes SellingAProduct
Rules/Policy RefundPolicy
Catalogs ProductCatalog
Records of finance, work, contracts, legal Receipt, Ledger, EmploymentContract
matters
Financial Instruments and services LineOfCredit
Manuals, documents, reference papers, DailyPriceChangeList
books

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

Copyright © Open University Malaysia (OUM)


60  TOPIC 2 STATIC MODELLING WITH UML

EXERCISE 2.17

Using Table 2.7 as a guide, produce a conceptual class categorization for


VictoriaÊs Videos.

Another technique for identifying conceptual classes is the use of noun phrase
identification. You will see that one of the arguments for developing use cases
before domain modeling is that they are an excellent source of noun phrases for
conceptual class identification. However, note about 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 see one example in which we going to use noun phrase identification
to identify conceptual classes.

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

An Internet-based ticket reservation company specializes 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 ă donÊt model the supply of tickets from
„the usual ticket agencies‰.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  61

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 or not
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:

 They must be distinct.


 There must be a way of telling them apart.

We will discuss ÂattributesÊ of conceptual classes in the coming section.


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 organization 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.7 This category of conceptual
class requires a bit of elaboration. The following example will help you to grasp
the 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,
etc., that go with it. After the video has been borrowed by a member and he/she
has lost it, the video will be deleted from the system. If the management needs to
obtain some information about the video (e.g. 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)


62  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:
 There is a need to describe about an item or service, independent of the
current existence of these items or services
 Deleting instances of things that they describe (for Example: Item) results in a
loss of information that need to be maintained
 It reduces duplicated information

EXERCISE 2.18

Update domain model shown in Exercise 2.16 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, etc. 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Ê, etc.

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 shows the relationship between two conceptual classes
ÂMemberÊ and ÂVideoÊ.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  63

Figure 2.8: 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.5.1 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.9. Pick the
first and second classes in the list, i.e. Â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.9: 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)


64  TOPIC 2 STATIC MODELLING WITH UML

The process is repeated with the other items down the list, i.e. 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 link 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.10: 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.11.

Figure 2.11: Association Identification Final Step

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  65

The above 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 may not be significant or meaningful to
the model. Hence, Larman (2002) has proposed Â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. Â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 follws for the airline reservation system
(Table 2.8).

Table 2.8: Common Association List (as proposed by Larman (2002))

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/on B Passenger-Airplane
A is logically contained in/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/captured Reservation-FlightManifest
in B
A is member of B Pilot-Airplane
A is an organizational 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

Copyright © Open University Malaysia (OUM)


66  TOPIC 2 STATIC MODELLING WITH UML

2.7.5.2 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, e.g. Â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.

Table 2.9: 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.12 depicts the domain model of the video shop system with multiplicity
added.

Figure 2.12: Associations with Multiplicity

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  67

2.7.5.3 Aggregation and Composition Relationships


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

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:

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 below shows a design class diagram which has association, composition
and aggregation relationships. Multiplicity of an association between classes also
shown in the figure as follows:

(Source: Modified from www.agilemodeling.com/ style/classDiagram.htm)

Copyright © Open University Malaysia (OUM)


68  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,
2nd edn, page 85:

„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.6 Other Issues of Association


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

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

(ii) Multiple associations between two classes


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

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  69

(iii) 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
(i.e coding). You may also discover new associations need to be
implemented but were missed in the analysis class diagram.

(iv) „Need-to-know‰ vs comprehensive associations


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

 Focus on the associations for which knowledge of the relationship need


to be preserved for some duration („need-to-know‰ associations).
 Avoid showing redundant or derivable associations

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


associations in a analysis class diagram will provide a minimal information on
the analysis class diagram. It means it may not convey a full understanding of the
problem to the user. According to Larman (2002), in the 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, use the following:

Emphasize need-to-know associations, but add choice comprehension-


only associations to enrich critical understanding of the model (Larman,
2002).

Copyright © Open University Malaysia (OUM)


70  TOPIC 2 STATIC MODELLING WITH UML

In principal, use the following association guidelines when identifying


associations between classes (Larman (2002):

 Focus on the „need-to-know‰ associations


 It is more important to identify the conceptual classes than to identify
associations
 Too many associations will lead to confusion and marginal benefit
 Avoid showing redundant or derivable associations

EXERCISE 2.19

Redraw Figure 2.12 to add in a ÂVideoSpecificationÊ conceptual class to the


video shop domain model.

2.7.7 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 colour 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, etc.

For the video shop system, the following are possible attributes to the conceptual
classes identified:
 Member · memberÊs number
 Video · video ID, classification
 FrontDesk · front desk register number
 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.13.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  71

Figure 2.13: 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. Each
date may be described by many other variables, e.g. maximum, minimum and
average temperature, hours of sunshine, total rainfall, average wind speed, etc.
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:
 If the independent existence of an entity is important, rather than just its
value, then it is a separate class.
 An entity that has features of its own within the given application is a
separate class.
 If the value of an attribute depends on a particular context then consider
restating the attribute as a qualifier.
 A name is a class attribute when it does not depend on context, especially
when it need not be unique.
Copyright © Open University Malaysia (OUM)
72  TOPIC 2 STATIC MODELLING WITH UML

 Do not list object identifiers that are used purely for unambiguously
referencing an object.
 If an attribute describes the internal state of a class that is invisible outside the
class then eliminate it from the analysis.
 Omit minor attributes that are unlikely to affect most operations.

READING 2.4

Download Reading 2.4 from myLMS to learn how attributes have been
discovered for NextGen domain model besides the domain model
conclusion for this case study.

EXERCISE 2.20

Similar to Exercise 2.19, add in the conceptual class ÂVideoSpecificationÊ and


its corresponding attributes to Figure 2.13.

The following tips by Larman (2002) is very useful when creating analysis class
diagram:
 Use Conceptual Class Category (from Table 2.7) or noun phrase identification
to identify the conceptual classes.
 Draw them in the analysis class diagram.
 Add the associations necessary to show the relationship between the classes.
 Add the attributes necessary to fulfill the information requirements.

Copyright © Open University Malaysia (OUM)


TOPIC 2 STATIC MODELLING WITH UML  73

 System can be modeled 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 visualize the static features of system: use case, use case diagram, activity
diagram, analysis class diagram.

 Every system development project starts with functional requirements


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 to understand the overall
picture of the system, the flow of events and the relationship between actors
and use cases.

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

 You modelled a business domain with 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.

Copyright © Open University Malaysia (OUM)


74  TOPIC 2 STATIC MODELLING WITH UML

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)


Topic 3  Dynamic 
Modelling  
with UML  

LEARNING OUTCOMES
When you have completed this topic you will be able to:
1. Describe the meaning dynamic modeling;
2. Draw a state diagram for a given problem;
3. Use state diagram to identify for 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
Previous topic has dealt with static modeling using UML. This topic will focus on
dynamic modeling using UML.

Software design is about behavior and behavior is dynamic. The ways a system
behaves in response to certain events or actions are the dynamic characteristics of
a system. Therefore an emphasis upon 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 diagram fall into this
category called Interaction diagrams. They both describe the flow of messages

Copyright © Open University Malaysia (OUM)


76  TOPIC 3 DYNAMIC MODELLING WITH UML

between objects. However, sequence diagrams focus on the order in which the
messages are sent. They are very useful for describing the procedural flow
through many objects. They are also quite useful for finding race conditions in
concurrent systems. Collaboration diagram, on the other hand, focus upon the
relationships between the objects. They are very useful for visualizing 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 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, etc.
Asset management Asset, purchase, sale, location, etc. Asset
Prisoner Prisoner, bed, sentence, medical Prisoner
management report, court orders, etc.
Student enrolment Student, course, university, Student, course
lecturer, etc.

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  77

EXERCISE 3.1

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


diagram.

As an example, letÊs consider a prison system.

Suppose weÊve just started work and weÊve identified three use cases:
 Admission · Handles the prisoner being transferred from the police or
courts to the prison, and being admitted.
 Transfer · Handles transferring a prisoner to a half-way house.
 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 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.

Figure 3.1: State Diagram for Prisoner · Version 1


Note: 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.

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 this:

Copyright © Open University Malaysia (OUM)


78  TOPIC 3 DYNAMIC MODELLING WITH UML

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Ês all fine, but what if a prisoner escapes?Ê

After some discussion with the user, we could redraw the diagram like this:

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Êve 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 recognize that some escaped prisoners
never get recaptured.

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  79

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Ês 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:

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 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.

Copyright © Open University Malaysia (OUM)


80  TOPIC 3 DYNAMIC MODELLING WITH UML

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 organized in time and space. These diagrams contain the
following elements:
 Classes, denoted as class rectangles, to represent the objects involved in the
interaction.
 Association roles, which represent roles that links may play within the
interaction.
 Messages, denoted as labeled 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.

Figure 3.6: Example of a Collaboration Diagram

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


operation, is realized 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)


TOPIC 3 DYNAMIC MODELLING WITH UML  81

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.

The following table 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 numbering Sequence numbers are needed to show the order in which
sequence the messages are sent.
Conditional Rarely used. Only send a certain message if a condition is
messages met.
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
collection of 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)


82  TOPIC 3 DYNAMIC MODELLING WITH UML

READING 3.1

Download Reading 3.1 from myLMS to learn the details of collaboration


diagram.

In addition to the notation in the reading, there is also the concept of a multi
object. 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 drinker 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 Drinker walks into a Restaurant

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  83

3.3 SEQUENCE DIAGRAM


Sequence diagrams depict an interaction among elements of a system organised
in time sequence (Refer to Figure 3.1). These diagrams contain the following
elements:
 Class roles, denoted as class rectangles, represent roles that objects may play
within the interaction.
 Lifelines, denoted as dashed lines, represent the existence of an object over a
period of time.
 Activations, denoted as thin rectangles, represent the time during which an
object is performing an operation.
 Messages, denoted as labeled horizontal arrows between lifelines, represent
communication between objects.

Object 1 Object 2
name name

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.

The following table summarises the details of sequence diagrams.

Copyright © Open University Malaysia (OUM)


84  TOPIC 3 DYNAMIC MODELLING WITH UML

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 This is extremely useful when you are new to
activation 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 show when
the message is answered.
Messages to ÂselfÊ or A simple line from an object to itself. Nested activation
ÂthisÊ boxes, as shown in the text, are not really necessary.
Creation of instances Very important
Object lifelines and Sometimes useful
object destruction
Conditional messages As for collaboration diagrams
Mutually exclusive
conditional messages
Iteration for a single As for collaboration diagrams
message
Iteration for a series of
messages
Iteration over a
collection (multi object)
Messages to class objects As for collaboration diagrams

READING 3.2

Download Reading 3.2 from myLMS to learn the details of sequence


diagram as shown in the table above.

EXERCISE 3.4

Take the collaboration diagram in Exercise 3.3, and translate it into a


sequence diagram.

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  85

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 artifact.

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, Jacobson and Rumbaugh 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 its types of ÂdoingÊ responsibilities that must be
defined appropriately for classes in a system.

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:


 doing something itself, such as creating an object or doing a calculation
 initiating action in other objects
 controlling and coordinating activities in other objects.

Knowing responsibilities of an object include:


 knowing about private encapsulated data (e.g. the glass in Exercise 3.3 knew
its size)
 knowing about related objects
 knowing about things it can derive or calculate.

Example: Process a Sale


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

Copyright © Open University Malaysia (OUM)


86  TOPIC 3 DYNAMIC MODELLING WITH UML

Where to begin? We start with the GUI telling the Register its 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Ês just check that this is
correct. So look at the conceptual class model on page below:

(Source: Larman(2002))

What do you notice about the itemId? Is this attribute on the Item class? No, itÊs
not · itÊs 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.10. 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,

Copyright © Open University Malaysia (OUM)


TOPIC 3 DYNAMIC MODELLING WITH UML  87

and we would have to do some work to get them out. Getting data in and out of
databases is not covered in this module.)

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Ês cash only, and that correct money is
given) and the Payment object is created.

Figure 3.10: Collaboration Diagram for Process a Sale

Copyright © Open University Malaysia (OUM)


88  TOPIC 3 DYNAMIC MODELLING WITH UML

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.

EXERCISE 3.5

Draw a sequence diagram for Process a Sale, based on the understanding of


the collaboration diagram that has been given in Figure 3.10.

EXERCISE 3.6

Draw a collaboration diagram and a sequence diagram for the use case
Borrow Videos in the VictoriaÊs Video case.

 Software design is about behavior and behavior is dynamic

 The ways a system behaves in response to certain events or actions are the
dynamic characteristics of a system.

 Therefore an emphasis upon dynamic models is very important in designing


a system.

 Dynamic modelling for object-oriented system 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 exist 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  89

Collaboration diagram Sequence diagram


Interaction diagram State Diagram

Copyright © Open University Malaysia (OUM)


Topic 4 X Introduction 
 
 
to Java 
 
 
 
 
 
  LEARNING OUTCOMES
 
 
When you have completed this topic you will be able to:
1. Describe the Java environment;
2. Describe the strength of Java;
3. Explain the types of Java program; and
4. Compile and execute a Java program.

X INTRODUCTION
The previous topics have dealt on how to create models of object-oriented
systems. In particular, you have learned on 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. Model is just a model in the
sense that it cannot be executed. Model gives us a solid understanding about the
nature and behaviour of the system. Model acts as a blueprint in order to
implement the system. Object-oriented programming language such as Java is the
popular language used to implement UML models. This topic and onwards will
focus on 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 had
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 - JavaOne Developer ConferenceTM in 1996.

Copyright © Open University Malaysia (OUM)


TOPIC 4 INTRODUCTION TO JAVA W 91

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 the next subtopic ă
4.2 Characteristics of Java. The next section will give 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 (Figure 4.1)
below. 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.

Compiler (Pentium) Binary File (Pentium)

Source code File Compiler (PowerPC) Binary File (PowerPC)

Compiler (SPARC) Binary File (SPARC)

Figure 4.1: Traditional Language Environment

Figure 4.2 illustrates the Java programming environment. The output of Java
program compilation is in the form of bytecode. 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),
any machine that will interpret the bytecode.

Copyright © Open University Malaysia (OUM)


92 X TOPIC 4 INTRODUCTION TO JAVA

Java Interpreter
(Pentium)

Java Interpreter
Java Program Java Compiler Java Bytecode (Power PC)

Java Interpreter
(SPARC)

Figure 4.2: Java Language Environment

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.

Java Interpreter
(Pentium)

Java Interpreter
Java Program Java Compiler Java Bytecode
(Power PC)

Java Interpreter
(SPARC)

What are the advantages of using bytecode?


Using bytecode as an intermediate and not allowing each person compile it
into the machine language of whatever computer they want to run give us
advantages. A compiler has to understand Java in order to compile it.
Compiler, on the other hand, is a complex program. A Java bytecode
interpreter, on the other hand, is a simple program. This makes it 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

Copyright © Open University Malaysia (OUM)


TOPIC 4 INTRODUCTION TO JAVA W 93

wants to use it in his/her program development; furthermore, this library can


be extended by the programmer according to his or her requirements. Other
main characteristics of Java are highlighted below:

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

Object-Oriented
Almost everything in Java is either a class, an interface, a method or an
object.

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,
and Solaris 2.3 and later.

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.

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

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


4.4
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 IDE has features such as windows, drag-and-
Copyright © Open University Malaysia (OUM)
94 X TOPIC 4 INTRODUCTION TO JAVA

drop, and other graphic elements. The aim is to make the software development
process fast, efficient, and easy to debug.

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 IDE available in the market uses the graphic interface
builder to support RAD.

The following are some Java IDE software with their URLs:
WinEdit (http://www.winedit.com/)
Jcreator (http://www.jcreator.com)
Java WebIDE (http://www.chami.com/webide)
Symantec Café/Visual Café (http://www.symantec.com/)
Forte for Java (http://www.sun.com/forte/ffj/)
Microsoft Visual J++ (http://www.microsoft.com/java/sdk)
Visual Age (http://www-4.ibm.com/software/ad/vajava/)

ACTIVITY 4.1
Exercise 8.1 JDK can be downloaded free from the website
http://java.sun.com/j2se.

4.4 WRITING JAVA PROGRAMS


There are two types of program 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 application will be illustrated in

Copyright © Open University Malaysia (OUM)


TOPIC 4 INTRODUCTION TO JAVA W 95

the next section. Applet and Frame are not covered in the syllabus. Applet are
covered in another course, CDOP3203 ă Java Programming. We will skip any
elaboration about Frame and Applet in this module.

Java Program

Application Applet

Applet is a web-based program


which supports GUI

Text-based Frame
application
Frame is non-Web stand alone GUI program

4.5 WRITING TEXT-BASED APPLICATION


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

Program 4.1 shows an example of non-GUI stand alone application written using
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 structured approach, all the statements and instructions are dump into main
method. Sometime, extra methods could be added to perform specific tasks. No
objects are required to be created when writing Java programs using structured
approach. The Program 4.1 above is described below.

Copyright © Open University Malaysia (OUM)


96 X TOPIC 4 INTRODUCTION TO JAVA

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.

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 (i.e. It is the where the program
starts to execute). The Java technology interpreter must find this defined exactly
as given or it refuses 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 (i.e.: 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.

Copyright © Open University Malaysia (OUM)


TOPIC 4 INTRODUCTION TO JAVA W 97

How to compile and execute Java application?

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

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

STEP 1
By using notepad in Windows, type Program 4.1. Then save it in a file with
the name Hello.java in the correct directory (For JDK, the program is to be
saved in jdk1.x.x/bin directory unless you have given a new name to this
directory).

Note: x.x in jdk1.x.x refers to the jdk version installed in your computer.
Latest jdk use abbreviation j2sdk1.x.x

STEP 2
Now enter the DOS window (also known as Command Prompt or C

Copyright © Open University Malaysia (OUM)


98 X TOPIC 4 INTRODUCTION TO JAVA

Then, you need to enter to the directory that stores the program that you
have typed in step 1.Use the DOS command cd to enter the correct directory
namely jdk1.x.x/bin

STEP 3
Compile the Java program using the instruction javac Hello.java in the DOS
environment. Example is shown below:

C:\jdk1.x.x\bin>javac Hello.java

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


displayed, go to Step 5.

STEP 4
Go back to notepad and open the file that you have typed in Step 1 (and at
the same time do not close DOS window). Do the necessary correction in
your program. Make sure you save your file after the corrections. Now go
back DOS window and repeat Step 3.

Copyright © Open University Malaysia (OUM)


TOPIC 4 INTRODUCTION TO JAVA W 99

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 DOS Window as shown below:

C:\jdk1.x.x\bin>java Hello

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 will generate the following output.

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)


100 X 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 on its object-oriented paradigm has


contributed to this success.

• Object oriented paradigm in Java makes us easy to reuse the applications.

• In addition, the types of Java program also have been discussed in this topic.

• It important for the students to understand the types of Java program and be
able to compile and execute those programs.

• Below is the summary of Java applications and Applet discussed in the


previous sections:

Type of Java How it could be Where the output will be


program written? 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, Netscape, etc)

Applet Object-Oriented Programming


Bytecode Text-based Application
Frame
 

Copyright © Open University Malaysia (OUM)


Topic 5 X Basic 
Constructs  
of Java 

 
  LEARNING OUTCOMES
When you have completed this topic you will be able to:
1. Describe the importance of data type and variable in Java;
2. List the primitive data type in Java;
3. List the rules of naming a variable in Java;
4. Describe about assignment;
5. Describe about boolean operators and relational operators; and
6. Explain about operator precedence.

X INTRODUCTION
What is a computer program? A program is a sequence of instructions that a
computer can execute to perform some task. There are two basic blocks of
programming: data and instructions and 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)


102 X TOPIC 5 BASIC CONSTRUCTS OF JAVA

5.1 DATA TYPES

Java is a kind of language that places importance on the 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 the others are 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 section 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 this data type is shown in Table 5.1 below:

Table 5.1: Value Range for the Integer Data Type

Type Storage 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, 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 W 103

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 is shown in Table 5.2
below.

Table 5.2: Value Range for the Real Type Data

Type Storage 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 7
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)
104 X 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 the 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 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 (™).

ACTIVITY 5.1

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


explanations on the Unicode.

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

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

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA W 105

Although Java allows any Unicode character in the Applet or Java applications,
the question 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 US version.

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 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 by using the casting operation. 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 above 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, i.e. 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)
106 X TOPIC 5 BASIC CONSTRUCTS OF JAVA

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 values below.


a) 51
b) ă31444843
c) 3.14
d) 5.301E ă 10

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 section, we will learn how to name and
declare a variable with the appropriate data type.

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 below shows the concept
of memory location in a CPU of a computer.

Figure 2.1: Memory Location showing the Name and Value of Variable Age

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA W 107

Figure 2.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 section, you have
learned data types that could be used in a Java program. This section 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 section because when you fail to declare
the right variable, it will cause the Java program that has been developed unable
to be compiled and 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 (Source: David J. Eck, 2006). The
rule to name a variable in Java is as follows:
• The name of a variable must start with a letter
• The name of the variable must consist of letters and digits
• 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 symbolizes 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 symbolizes a digit in a particular language. Symbols such as
Â+Ê or Â©Ê and also empty spaces cannot be used in the name of a variable.

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

Copyright © Open University Malaysia (OUM)


108 X TOPIC 5 BASIC CONSTRUCTS OF JAVA

a variable. The reserved words for Java cannot be used as the name of the
variable.

Table 5.4 below 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 synchronized
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 above 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. Character Â_Ê is not selected event though it does
not break the above rules. Below is an example of the name of a variable.
studentName, totalMarks, pricePerunit

is the style suggested compared to


student_name,total_marks,price_perunit

ACTIVITY 5.3

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

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA W 109

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
and followed by the name of the variable. The syntax for variable declaration is
given below:

data_type name_variable;

Some examples of declaration are shown below:


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

but normally only one variables 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
Copyright © Open University Malaysia (OUM)
110 X TOPIC 5 BASIC CONSTRUCTS OF JAVA

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

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 declaration below:

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

final double PI = 3.14159


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

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA W 111

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

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

ACTIVITY 5.4

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

Copyright © Open University Malaysia (OUM)


112 X TOPIC 5 BASIC CONSTRUCTS OF JAVA

EXERCISE 5.2

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

(a) nameLength
(b) Name_length
(c) Import
(d) 43650BBB
(e) BBB43650
(f) touch&go
(g) touch-and-go
(h) 2nd
(i) break
(j) OUM

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

5.3 ASSIGNMENT STATEMENT, INITIAL


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

5.3.1 Assignment Statement

SELF CHECK 5.1

What is meant by Assignment Statement and Initial Value?

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;
Copyright © Open University Malaysia (OUM)
TOPIC 5 BASIC CONSTRUCTS OF JAVA W 113

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 (modified from
David J. 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 (modified from David J. Eck, 2006).

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

Copyright © Open University Malaysia (OUM)


114 X TOPIC 5 BASIC CONSTRUCTS OF JAVA

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.

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:

• If one is of the double type operant, the other operant would be changed to
double.
• On the other hand, if one of it is a float type operant, the other operant
would be changed to float.
• On the other hand, 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.

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA W 115

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 that
may be 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.

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 by 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 the sequence below:
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 (Source: David J. 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

Copyright © Open University Malaysia (OUM)


116 X TOPIC 5 BASIC CONSTRUCTS OF JAVA

In some cases, you might want to force a conversion that wouldn't be done
automatically. For this, you can use casting. For example (Source: David J. 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 (Source: David J. Eck, 2006).

EXERCISE 5.3

The following Java program has 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 of how to give initial value to the variable and performing binary
operations to numerics with different data types without data lost, you will learn
in detail on operators and operatorÊs operation that involve numeric values in the
next section.

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.

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA W 117

Arithmetic operation, assignment as well as addition and reduction in Java is the


same as in C language.

5.4.1 Arithmetic
Table 1.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 below.

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

5.4.2 Multiple Assignments


Multiple assignment operator provides a short cut to using the arithmetic
operation in the assignment statement. Table 5.7 below shows a multiple
assignment operator, an example of its usage and the meaning of that
assignment statement.

Copyright © Open University Malaysia (OUM)


118 X TOPIC 5 BASIC CONSTRUCTS OF JAVA

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
table below shows an addition and reduction operator, an example of its usage
and the meaning of each particular operators.

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

This operation will change the value of the variable. Therefore, it cannot be done
on a constant, for example 7++. See several examples below:

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

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA W 119

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 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 above. However, it can be used in cases such as follows:

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:

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

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:

Copyright © Open University Malaysia (OUM)


120 X TOPIC 5 BASIC CONSTRUCTS OF JAVA

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 could not be 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 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 don't use parentheses
to explicitly indicate the order of evaluation, then you have to worry about the
precedence rules that determine the order of evaluation.

Table 5.10 below 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 see
more examples below.

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA W 121

Example 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 2: Evaluating (2 + 4)/2


(2 + 4) / 2

6 /2 = 3

(Note: Those operands and operator 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.

5.4.5 Boolean Operators


"And", "or", and "not" are the boolean operators in Java that allow us to do
complicated condition.

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.
Copyright © Open University Malaysia (OUM)
122 X TOPIC 5 BASIC CONSTRUCTS OF JAVA

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.

EXERCISE 5.4

1. Give the value for each of the arithmetic statements below:

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
(h) 5.0 / 2 * 3 % 2

2. What are the values of j and k after the statement below 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 --;
(e) k % = j ă 3;

Copyright © Open University Malaysia (OUM)


TOPIC 5 BASIC CONSTRUCTS OF JAVA W 123

In conclusion, you should have recognized the operators that could be suitably
used with arithmetic operations that will be used in a particular Java program.

• 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 the students.

• This topic has discussed the basic Java constructs that should be known by
the students to enable them to write a complete Java program and is free
form errors.

Boolean Expression
Boolean Operator Relational Operator
Data Types Variable

Copyright © Open University Malaysia (OUM)


Topic 6 X Control 
 
 
Structure & 
 
 
 
Method
 
 
 
 
  LEARNING OUTCOMES
When you have completed this topic, you will 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.

X 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.

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

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE & METHOD W 125

located in the next line. This scenario is known as transfer of program control.
Bohm and Jacopini have conducted research in the 1960s and have concluded
that all programs can be written in a structured way by only using three control
structures, that is shown in Table 6.1.
Table 6.1: Three Control Stuctures

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.

The above three structures that are capable to change the flow of control in a
program can be implemented in the Java language. The following sections with
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:


• single selection
• bi-selection
• multi-selection.

Single selection as in C, is implemented using the if statement.

Copyright © Open University Malaysia (OUM)


126 X TOPIC 6 CONTROL STRUCTURE & METHOD

6.2.1 The if, else Statements

(a) Single selection


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?
A step-by-step problem-solving procedure written in natural language
such 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)


TOPIC 6 CONTROL STRUCTURE & METHOD W 127

Age < 55
False True

Compulsory Retirement

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)


128 X TOPIC 6 CONTROL STRUCTURE & METHOD

Generally, the syntax in the Figure 6.2 as follows represents the if-else
statement.

Expression
False True

Statement 2

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 above example,
if the age is or more than 55, the words ‘compulsory retirement” will
be printed.

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

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE & METHOD W 129

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, i.e. 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 below.

Copyright © Open University Malaysia (OUM)


130 X TOPIC 6 CONTROL STRUCTURE & METHOD

False True
raceCode=M

True
raceCode=C

False

True
raceCode=I

False

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

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE & METHOD W 131

will accomplish statement 1 value if the requisite value is true. 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 expression.


Example:
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 expression with combination of more than one boolean operations is valid to


use such as shown in the above code.

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

6.2.2 Switch Statement


The multi selection structure is sometimes difficult or too long to write.
Therefore, Java also provides switch statement as its alternative. The following
is the syntax for the switch statement that can replace the if-else if
statement (Source: David J. Eck, 2006). Note that there is a break statement at
each case block.
switch (expression) {
case constant-1:
statements-1
break;
Copyright © Open University Malaysia (OUM)
132 X TOPIC 6 CONTROL STRUCTURE & METHOD

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

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 users


requirement. if statement is normally used to make decision based on the range
of the value or specific conditions while switch statement is used to make
decision based on a integer or character value. Also, the value for every case
must be different.
Copyright © Open University Malaysia (OUM)
TOPIC 6 CONTROL STRUCTURE & METHOD W 133

Figure 6.4: Selection Structure in Multi Selection using switch and break

Copyright © Open University Malaysia (OUM)


134 X TOPIC 6 CONTROL STRUCTURE & METHOD

The example below shows of 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 as follows:
Table 6.2: Sequential Vs. 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 & METHOD W 135

Observe that repetition takes few lines compare to sequential solution to


accomplish a same task. From here you can see the advantages of using repetition
in loop. 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 example below 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 above example 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.

1. Initial statement.
This statement will assign initial value for the variable that will be used in
the loop. In our example, the i = 1 statement is the initial statement.

2. Stop requisite.
This requisite will be tested to determine whether the next iteration needs to
be accomplished. In the above example, i < = 100 is the stop requisite.

Copyright © Open University Malaysia (OUM)


136 X TOPIC 6 CONTROL STRUCTURE & METHOD

3. The process that needs to be accomplished.


In our example, sum + = i statement will be accomplished if the requisite
is true.

4. 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
below:

do {
Statement1
Statement2
……
……
StatementN
} while (condition)

For the do-while loop, the loop body will be executed first, Then 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;requisite;update){
block_statement
}

Unlike while and do-while statements, for loop is used for the
number of loop repetitions that already known in advance.

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 is
updates that describes how to update to change the initial_value
Copyright © Open University Malaysia (OUM)
TOPIC 6 CONTROL STRUCTURE & METHOD W 137

(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

6.3.3 The break and continue Statements


Some times 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 the above program, the program will exit the loop when the value of line
becomes 3 event though the requisite for the loop line <=5. The result that
will be displayed is:

HI
HI
HI

Copyright © Open University Malaysia (OUM)


138 X TOPIC 6 CONTROL STRUCTURE & METHOD

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 statement. 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.

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 nested for loop:

The result that will be displayed is:


*
**
***
****
*****

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE & METHOD  139

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?

6.3.5 Compound Statements

SELF-CHECK 6.1

When using if/else, for while loops, there is one important concept that you
should know that is Compound Statement. What is Compound Statement?

We will start with two examples in order to explain the concept of compound
statements. Consider the following two examples:

Example 1:
1 int x=2;
2 if (x==2)
3 System.out.println(“Hi”);
4 System.out.println(“Hello”);
5 System.out.println(“Bye”);

Example 2:
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”);
Copyright © Open University Malaysia (OUM)
140 X TOPIC 6 CONTROL STRUCTURE & METHOD

The output for Example 1 is:


Hi
Hello
Bye

while the output for Example 2 is


Bye

Do you know why there is a difference between the output for the Example 1 and
Example2?

In Example 1, there is 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 (i.e. If line 2 returns a true boolean value then line 3 will be
executed where as line 3 will not be executed if line 2 returns a false value). Line
4 and 5 will be executed irrespective whether line 2 returns true or false value.

In Example 2, there is 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
(i.e. 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 whether line 2 returns true or false value because it is not inside the
braces.

Line 4 ăLine 5 in Example 2 is known as compound statement. Any number of


statements can be enclosed within a set of braces, including other if and
compound statements as shown in the example given below:

Example 3:
int x=2;
int y=3;
if (x==2)
{
if (y==1)
System.out.println(“Hi”);
System.out.println(“Hello”);
}
System.out.println(“Bye”);

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE & METHOD W 141

The above program will produce the following output:


Hello
Bye

Can you explain how we get the above output?

Besides if-else statement, compound statement also could be included in for


and while loops such as shown below:

Example 4:
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 is no braces in
System.out.println(“Hi”); this line
System.out.println(“Hello”);

The above program will produce the following output:


Hi
Hello
Hi
Hello
Hi
Hello
*********************
Hi
Hi
Hi
Hello

Can you explain how we get the above output?

Copyright © Open University Malaysia (OUM)


142 X TOPIC 6 CONTROL STRUCTURE & METHOD

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

6.4 METHOD
Methods allow the programmer to modularize a program - each method will
perform a single specialized task.

A method is subprogram. When code becomes 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 same with the name of the
class. (We will learn more about constructor method in CDOP3203 course).

Query method is used to access only the objectÊs state and this operation does not
change the state of a object. Example of this method are:
• getName()
• getPay()
• RetrieveID()
• checkPassword()
Copyright © Open University Malaysia (OUM)
TOPIC 6 CONTROL STRUCTURE & METHOD W 143

Update method is used to update or change the value of attribute(s) of a object.


This update operation will change the state of the object. Example of this method
are:
• setName()
• updateAge()

Finally, task methods is used to perform some specific task. This method may
change the state of the object. Example of this method are:
• calculateAge()
• 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 programs. Java methods are similar to
functions or procedures in other programming languages. Methods in Java could
be divided into two, namely:
• Library methods such as main(), max (x,y), sqrt(x), etc
• User defined methods written by the programmer such as method display()
shown above in Program 1.2.

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


144 X TOPIC 6 CONTROL STRUCTURE & METHOD

Example:

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, etc.

<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 donÊt 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
below:
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 example below:

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)


TOPIC 6 CONTROL STRUCTURE & METHOD W 145

If the method returns a value a String value, then the method should be declared
as String as shown in the example below:

public String getAverage(){


…..
…..
return ..;
}

The same goes for other methods that returns other data types such float, double,
char, boolean, etc. Use return statement within the method to pass back value if
the method return 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
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 itÊs data
types and a identifier as shown in the next example:

Data type Identifier

Example 1:
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)


146 X TOPIC 6 CONTROL STRUCTURE & METHOD

Example 2:
/* 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 3:
Public int getId(){
int id = 4567
return id;
}

Example 4:
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 definition of what the method suppose to do.
In order to execute the method, you need to call or invoke it. When a program
calls a method, 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 (i.e. it is a void method), then method must
be statement. For example:
 

calculateAge(); 
 

Copyright © Open University Malaysia (OUM)


TOPIC 6 CONTROL STRUCTURE & METHOD W 147

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 compatible as defined in the method signature.
 
Example 5 below shows a complete program which has method declaration and
method invocation
 
Example 5:
 
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.

Any variable declared inside a method is known as local variable. Local


variables are only recognised inside its method.

Copyright © Open University Malaysia (OUM)


148 X TOPIC 6 CONTROL STRUCTURE & METHOD

Tips of using methods:


• Each method should be used to perform single task such as calculate
average, determine maximum number, etc
• Avoid having a multiple tasks in a method such calculate average, and
determine maximum that are combined in one method

6.4.4 Method Overloading


Consider the program shown in the previous Example 5. 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 that 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;
}
   public static float getMax(float no1, float no2){ //second method
float max;
if (no1>no2)
max= no1;
else
max= no2;
return max;
}
}
Copyright © Open University Malaysia (OUM)
TOPIC 6 CONTROL STRUCTURE & METHOD W 149

In line 5 of the above program, it will invoke the first method that will determine
the maximum value between two integer numbers. In line 6, it will invoke the
second method that will determine the maximum value between two float
numbers.

As you can see in the above 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 have conducted research in the 1960s and have 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 implements using if, if-else, if-else if and
switch statements

• Repetitive structure in Java could be implemented using while, do-while and


for loops

• Methods inside the program allow us to modularize the program. Thus, it


makes the program more readable and organized.

Copyright © Open University Malaysia (OUM)


150 X TOPIC 6 CONTROL STRUCTURE & METHOD

break method
case nested loops
continue Repetitive Structure
do-while Selestion Structure
for Sequential Structure
if switch
if-else while

Copyright © Open University Malaysia (OUM)


Topic 7 X Array, String 
and Input 
Reading 
LEARNING OUTCOMES
When you have completed this topic, you will be able to:
1. Describe the meaning of array;
2. Write Java program using array;
3. Write Java program that capable to perform String manipulation; and
4. Write a interactive Java program using Pembaca class.
 
 

X INTRODUCTION
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 as listed as follow:
• Array
• String
• Input Reading

The above constructs enable us to write a complete and comprehensive Java


programs such as programs that will (just to name a few):

Copyright © Open University Malaysia (OUM)


152 X TOPIC 7 ARRAY, STRING & INPUT READING

• Process the marks of 100 students and determine the highest and lowest
marks
• Determine number of characters in a String
• Enable an user to key in data during program run-time

Next sections will elaborate on these constructs.

7.1 ARRAY

Array is a group of memory locations that are connected and has the same
name and data type.

Ever wonder 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 5 students‰

For the above problem, you are just required to declare five variables type of
integer 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 as shown below:

int student1, student2, student3, tudent4,….,student499,


student500;

It is very obvious that the above approach to write 500 variables is „tiring‰
and it is not a good approach. The solution is to use array:
int[] student = new int [500];

Do not worry if you donÊt understand the above declaration because we are
going to discuss it in a short while.

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING & INPUT READING W 153

We need to state the name of the array and the location in order to refer 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 text. 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 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)


154 X TOPIC 7 ARRAY, STRING & INPUT READING

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 it


x = new int[10]; 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 below:

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 above, the new operator is not used. We can also
give an initial value to an array that has no name definition as shown below:

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 localized variable for it. For
example:

printFiveEven(new int [ ] {2, 4, 6, 8, 10});

actually is the abbreviation for

int[] evenNum = { 2, 4, 6, 8, 10};


printFiveEven(evenNum); //send as a parameter in method

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING & INPUT READING W 155

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.

7.1.2.1 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
evenNum array above, 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.

7.1.2.2 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);
• source ă is the source array name whose contents are intended for copying.
• target – is a new array which will store values that are copied.
• sourceIndex – indicates the start of the content position of the array that is
to be copied from the source array.
• targetIndex – shows the start of the position at the target array that will
be used to store the values that are to be copied.
• no – is the number of the values copied.

Copyright © Open University Malaysia (OUM)


156 X TOPIC 7 ARRAY, STRING & INPUT READING

The following is an example of the program segment that shows how three out of
five values 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 above program segment is executed:

Figure 2.2: Array memory space

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

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING & INPUT READING W 157

Do you know that⁄


We are allowed to assign an integer array to another integer array such as follows:
Ex:
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 visual below 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.

EXERCISE 7.1

1. Each declaration in the table as follows contains error. Give reason for
the error.
(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 and 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]

Copyright © Open University Malaysia (OUM)


158 X TOPIC 7 ARRAY, STRING & INPUT READING

(d) k[‘j’]
(e) k[j]
(f) j[x + y]
(g) j[x % y]
(h) j[10]
(i) c[-1]
(j) j[j [4] ]

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 variable in Java.

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING & INPUT READING  159

7.2.1 String Declaration


String zero = “ ”;//an empty string
String university = Open University Malaysia”;
String courseCode = “CBOP3203”;
String courseName= “Object Oriented Programming”;

Each declaration of the character string as shown in the above example is an


object from the String class.

7.2.2 String Operation

SELF-CHECK 7.1

You have already learned about arrays. Do you know the difference between
array and String?

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 above 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” + 2000;

Copyright © Open University Malaysia (OUM)


160 X TOPIC 7 ARRAY, STRING & INPUT READING

Here the software is assigned to “OFFICE2000”. This approach is


normally used in output statements and it mostly helps when we intend to
print constant string and variable value. Below is one of its examples.

System.out.println(“Software that is used” +software);

The output obtained from the accomplishment of the above statement is as


follows:
Software that is used OFFICE2000

(b) Sub String


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

The above 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 above 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.

(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 length
attribute that represents array size.

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING & INPUT READING W 161

d) String Comparison
To test whether two strings have the same value, we can use 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 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 Â==Ê 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 from more than 50 methods to


manipulate the string. The list of methods in the java.lang.String
class can be seen in http://java.sun.com/products/jdk 1.2/docs/api/
java/lang/String.html

Copyright © Open University Malaysia (OUM)


162 X TOPIC 7 ARRAY, STRING & 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 om String library. The method
getChars was not discussed in the module. Please refer 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 & INPUT READING W 163

7.3 CAPTURING INPUT FROM USER DURING


RUNTIME
An interesting thing in writing the Java program is that the reading input process
from the keyboard is not as simple as expected. Java allows the input/output
process to use the process of inflow and outflow of data. With this concept, the
data flow is received in the form of a byte sequence. The resources as well as the
byte sequence destination of this data can consist of file, network link or a
memory space block. Although data is usually in the byte sequence, it is easier to
picture it as a high level structure such as a character or object sequence. In the
Java program language, the object that allows us to read a data byte sequence
from it is called input stream and the object that enables us to write outputs from
it is known as output stream. Each is implemented by the InputStream class
and the OutputStream class.

7.3.1 Using Pembaca Class


From the above explanation, it is clear that the difficulty that has to be faced to
perform the input process. To write a program that can receive simple and easy
input (Using the Java applications) is more difficult that reading the input using
the program that uses the face-to-face user graphics (using the Java Applet).

Seeing that it is difficult for a new programmer learning the Java language to
write Java program that using InputStream class to capture input, we have
prepared a simple class to read input integer, character, real numbers, character
or strings. This class is named Pembaca class.

Pembaca class can be downloaded from myLMS

All the Java applications that involve input reading in this module will use Pembaca
class. You can download this Pembaca class from myLMS in order to use it in your
program. Make sure you copy this class to the directory jdk1.x.x/bin in your PC. The
program will not function properly if Pembaca class is not copied to this directory.

We will look at the details of the Pembaca Class. This class has methods
(that are defined in this class) which are allocated to read certain types of data.
These methods are called member methods.
• bacaFloat() method
• bacaFloat () method

Copyright © Open University Malaysia (OUM)


164 X TOPIC 7 ARRAY, STRING & INPUT READING

• bacaDouble()method
• bacaLong()method
• bacaShort() method
• bacaChar() method
• bacaString() method

Table 7.1: Methods Available in Pembaca Class

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING & INPUT READING W 165

The following is an example of a program that uses Pembaca Class to read input:

Program 7.1: Example Using Pembaca Class

We have to only declare a variable as a type of the Pembaca Class. In the


Program 7.1 (line 7), the variable name that is used is read which is a type of
Pembaca. Before using the variable, we should create a an object of Pembaca
class so that the read variable can accessed the methods available in Pembaca
class. This is done by the new statement as shown below:

read = new Pembaca();

Now the memory space size for Pembaca Class is assigned and the variable
read is now referred or shows to that memory space. To use the methods defined
in that class, we can call the method in Table 7.1 by the following syntax:

read.method_name;

Copyright © Open University Malaysia (OUM)


166 X TOPIC 7 ARRAY, STRING & INPUT READING

For example, to call bacaInt() method, the call has to be in the form
read.bacaInt();. As this method returns the value int that is input by the
user, thus the call should be in the form assignment as shown in line 14 that is
integerValue = read.bacaInt();. Next, we can manipulate the value
input whether to print or to use in arithmetic operations.

EXERCISE 7.3

Write a Java program that will accept three integer numbers from an user
and display the maximun number among these three inputs.

7.4 OUTPUT FORMATTING


How can you format a numeric value or numeric number in Java? 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 a example, the statement as follows will display the first three digits after the
decimal point.

DecimalFormat num = new DecimalFormat(„.000‰);

The statement below 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 is greater than three, then all the digits in the number will be
displayed.

DecimalFormat num = new DecimalFormat(„000‰);

Try to execute the program below 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‰);

Copyright © Open University Malaysia (OUM)


TOPIC 7 ARRAY, STRING & INPUT READING W 167

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 above program.

DecimalFormat num = new DecimalFormat(„0,000.000‰);

Can you see any difference in the output upon executing the 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


method.

• All these have been elaborated in Topic 5 and Topic 6.

• This topic has focuses on array, String and how to capture input from user
during program runtime.

• Array is a group of memory locations that are connected and has the same
name and data type.

• String class in Java enable us to perform various manipulation 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.

• Thus, we have prepared class Pembaca for you so that that it could be used
to develop interactive programs.

• In this module, you have learned to write Java program in a structured


manner. If you are interested to write Java programs in an object-oriented
manner, you are encouraged to take CDOP3203 ă Java Programming course.

Copyright © Open University Malaysia (OUM)


168 X TOPIC 7 ARRAY, STRING & INPUT READING

Array String
Pembaca Class
 

Copyright © Open University Malaysia (OUM)


ANSWERS W 169

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% accurate
Ć a front desk clerk should be able to become familiar with all the functions of
the system within one week.

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 · joining,
borrowing videos, asking questions.

Copyright © Open University Malaysia (OUM)


170 X ANSWERS

Back office clerk · primary · This actor deals with all the back office functions,
such as sending data to the general ledger system. (Will probably find later that
this ÂactorÊ is actually several actors.)

Stocktaker · primary or secondary, depending on implementation. Require


more information on what a stocktake entails.

Management · secondary, as their reporting needs are met from the data
warehouse. Need sufficient information 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.

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.

Copyright © Open University Malaysia (OUM)


ANSWERS W 171

Actor Use cases Notes/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

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.

Copyright © Open University Malaysia (OUM)


172 X ANSWERS

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.

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)


ANSWERS W 173

Exercise 2.11

Cash register terminal


Take money
There are other use cases that
have no direct connection with
the video tracking system, and
so are not shown

Borrow Video tracking


Member Front desk videos system
clerk
Return
videos
Enter
Maintain
Create reservation
valid users
members
Search for
titles
Maintain
members Maintain Generate
members data
Security
Do stocktake
Back office clerk manager
(need more info)
Note: Additional use cases not Data warehouse
shown on diagram are:
• logon
• logoff
Back office clerk
• change password
• get online help.

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.
Ć 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.

Copyright © Open University Malaysia (OUM)


174 X ANSWERS

Later in the unit we show you a way for dealing with large systems with
hundreds of use cases.

Exercise 2.12

Customer Front desk clerk Cash register


(external)
Used italics as
nothing to do Select Borrow
with computer videos videos
system
Create
member
Take
money

Exercise 2.14

Perhaps you can already envisage the answer, but letÊs work through it slowly.
We need a use case to sell old videos. So hereÊs 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Ês the same as the last line of the Borrow
Videos use case.

So we could create a new sub-use 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)


ANSWERS W 175

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


176 X ANSWERS

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 (e.g. total number
borrowed, total number of overdues, current
number borrowed, 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)


ANSWERS W 177

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 they are Generate Birthday Letters
sent a special letter inviting them to
borrow any video of their 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)


178 X ANSWERS

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 catalogue
Manuals, documents, reference, paper, Member records
books New releases
New employee training

Copyright © Open University Malaysia (OUM)


ANSWERS W 179

Exercise 2.18

Copyright © Open University Malaysia (OUM)


180 X ANSWERS

Exercise 2.19

Copyright © Open University Malaysia (OUM)


ANSWERS W 181

Exercise 2.20

Copyright © Open University Malaysia (OUM)


182 X ANSWERS

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 discussion did not mention that if a member has too many
overdues, then she 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:

Borrow Videos
On-Shelf Borrowed

Return Videos

Then you could think about how a video tape comes into existence. Clearly we
are missing a use case here · letÊs call it Get New Video Tapes.

And 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.

So now the diagram looks like this:

Copyright © Open University Malaysia (OUM)


ANSWERS W 183

Lastly, letÊs think about lost or missing video tapes. Once again, we would need
to discuss this with Victoria, and the answer could be the following.

Record Stocktake Borrow


Findings Videos Borrowed
On-Shelf
Return Videos
Get New Video Tapes
Record Video
Return Tape Missing
Retire Video Videos
Tapes
Missing

Record Stocktake
Findings Write-off
Video Tape

Now to the state diagram for the member:

Copyright © Open University Malaysia (OUM)


184 X ANSWERS

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) 285 ml.
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)


ANSWERS W 185

Exercise 3.5

Copyright © Open University Malaysia (OUM)


186 X ANSWERS

Exercise 3.6

Copyright © Open University Malaysia (OUM)


ANSWERS W 187

Suggested Answers to Exercises for 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

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

Copyright © Open University Malaysia (OUM)


188 X ANSWERS

(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

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

Copyright © Open University Malaysia (OUM)


ANSWERS W 189

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

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

Copyright © Open University Malaysia (OUM)


190 X ANSWERS

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

Exercise 7.3

import java.io.*;

class Maks {
public static void main( String args[ ] ) throws IOException
{
int temp, maks;
Pembaca read = new Pembaca();
System.out.println("Enter first number:");
int no1=read.bacaInt();

System.out.println("Enter second number:");


int no2=read.bacaInt();

System.out.println("Enter third number:");


int no3=read.bacaInt();

if (no1>no2)
temp=no1;
else
temp=no2;

if (temp>no3)
maks=temp;
else
maks=no3;

System.out.println("Maks number is:"+maks);

}//main
}//class

Copyright © Open University Malaysia (OUM)


REFERENCES W 191

References
Addison-Wesley. (This is a great reference for UML, providing more detail than
you will ever need.)

Booch, G (1991) Object-oriented Design with Applications, Redwood City, CA:


Benjamin Cummings.

Booch, G., Rumbaugh, J. and Jacobson, J. (1999). The Unified Modelling


Language.

Cockburn, A. (2002). Writing Effective Use Cases, Addison Wesley.

Constantine, L. L. and Lockwood, L. A. D. (1999). Software for Use, Addison-


Wesley. (Gives a detailed treatment of using use cases to design the user
interface. See also their website <www.foruse.com>.)

David J. Eck. „Introduction to Programming Using Java‰. 2006. (retrieved from


http://math.hws.edu/javanotes/)

Eriksson, H.-E. and Penkus, M. (2000) Business Modelling with UML · Business
Patterns at Work, Wiley.

Fowler, M. and Scott, K. (2000). UML Distilled, 2nd edn, Addison-Wesley. (This is
a short and practical overview to using UML in actual practice.)

Karin Kolbe, Geoffrey Phipps. „Object-Oriented Approach for Software


Development‰. Open University Malaysia. (Adopted from OUHK). 2006.

Larman, C. (2002). Applying UML and Patterns, Prentice Hall.

Richter, C. (1999). Designing Flexible Object-Oriented Systems with UML,


Macmillan Technical Publishing.

Robertson, S. and Robertson, J. (1999). Managing Requirements. Mastering the


Requirements Process, Addison-Wesley. (See also their website for a
requirements template, <http://www.atlsysguild.com/GuildSite/Robs/
Template.html>.)

Copyright © Open University Malaysia (OUM)


192 X REFERENCES

Scott, K. (2001). UML Explained, Addison-Wesley. (This book presents the basics
of UML.).

Shalloway, A and Trott, J R (2002) Design Patterns Explained: A New Perspective


on Object-Oriented Design, Addison Wesley, ISBN 0201715945.

Y Daniel Liang. „Introduction to Java Programming: Fundamentals First‰. 6/E.


Prentice Hall. 2007.

Zachman, J., The Zachman Framework at <http://www.zifa.com/>. (Select


ÂFrameworkÊ from the left menu. The Zachman Framework provides a
complete view of requirements from an enterprise perspective.)

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 myVLE.

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)