Documente Academic
Documente Profesional
Documente Cultură
2.7.7 Multiplicity 70
2.7.8 Aggregation and Composition Relationships 71
2.7.9 Other Issues of Association 72
2.7.10 Attributes 73
Summary 76
Key Terms 77
Answers 177
INTRODUCTION
CDOP3103 Introduction to Object-oriented Approach is one of the courses
offered at Open University Malaysia (OUM).
COURSE AUDIENCE
This course is offered to all students undertaking the Diploma in Information
Technology (DIT). This module aims to introduce the concepts of object
orientation, systems modelling using UML and basic Java programming.
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.
Study
Study Activities
Hours
Briefly go through the course content and participate in initial discussions 5
Study the module 60
Attend 3 to 5 tutorial sessions 10
Online participation 12
Revision 18
Assignment(s), Test(s) and Examination(s) 15
TOTAL STUDY HOURS ACCUMULATED 120
COURSE OUTCOMES
By the end of this course, you should be able to:
3. Write UMLÊs use case, draw use case diagrams, activity diagrams, analysis
diagrams, sequence diagrams, collaboration diagrams and state diagrams
for a given problem; and
COURSE SYNOPSIS
This course is divided into 7 topics. The synopsis for each topic can be listed as
follows:
Topic 1 will introduce the concepts of object orientation. In particular, you will
learn about the object and its characteristics, class, message passing mechanisms
between objects, object interface, encapsulation and inheritance. Besides that, you
also will be introduced to how UML is fit to develop object-oriented systems.
Specifically, you will be shown some of the main UML diagrams that can be used
to perform static and dynamic modelling. This topic includes many examples to
reinforce your understanding on object orientation.
Topic 2 explains how a system can be modelled from two angles ă static and
dynamic aspects. The static characteristic of a system is essentially the structural
aspect of the system. The static characteristics define what parts the system is
made up of. In this topic we will briefly introduce to you some of the UML
notations used to visualise the static features of system using use case, use case
diagrams and analysis class diagrams.
Topic 3 will focus on dynamic modelling using UML. Software design is about
behaviour and behaviour is dynamic. The ways in which a system behaves in
response to certain events or actions are the dynamic characteristics of a system.
Therefore, an emphasis on dynamic models is very important in designing a
system.
Topic 4 gives an overview about Java including its advantages. The types of Java
programs with their sample codes will be elaborated in this topic. In addition,
learners will be exposed to how to compile and execute a Java program.
Topic 6 discusses the two basic aspects of programming ă data and instructions,
as highlighted in Topic 2. As mentioned before, to work with data, you need to
understand variables and data types; to work with instructions, you need to
understand control structures and methods. This topic will focus on control
structures (such as if-else statements, switch-case statements and loops) and
methods.
ADDITIONAL READING
There will be a number of additional „short‰ readings for certain topics as shown
in the following table. These readings are provided as part of your course
package in myINSPIRE.
Topic Reading
Topic 1 ă
Topic 2 Reading 2.1 ă Reading 2.4
Topic 3 Reading 3.1 ă Reading 3.2
Topic 4 ă
Topic 5 ă
Topic 6 ă
Topic 7 ă
It is compulsory for learners to read these readings as it will give them a solid
understanding of the particular concepts related to the course. These readings are
part of the syllabus. Hence, it can be used for tests and in the final examination.
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.
Summary: You will find this component at the end of each topic. This component
helps you to recap the whole topic. By going through the summary, you should
be able to gauge your knowledge retention level. Should you find points in the
summary that you do not fully understand, it would be a good idea for you to
revisit the details in the module.
Key Terms: This component can be found at the end of each topic. You should go
through this component to remind yourself of important terms or jargon used
throughout the module. Should you find terms here that you are not able to
explain, you should look for the terms in the module.
PRIOR KNOWLEDGE
No prior knowledge required.
ASSESSMENT METHOD
Please refer to myINSPIRE.
REFERENCES
Booch, G., Rumbaugh, J., & Jacobson, I. (1999). The unified modeling language
user guide. Upper Saddle River, NJ: Addison-Wesley.
Böhm, C., & Jacopini, G. (1966). „Flow diagrams, Turing Machines and
Languages with only Two Formation Rules‰, Comm. of the ACM, 9(5): 366ă
371.
Chitnis, M., Tiwari, P., & Lakshmi Ananthamurthy. (2002). UML Overview.
Available from:
http://www.developer.com/design/article.php/1553851
ONLINE DISCUSSION
Online discussion with your tutors and fellow students is one of the important
components of teaching and learning activities at OUM. To help you to go
through your online discussion, OUM has developed myINSPIRE. The system
has a number of functionalities which enable the students to access OUMÊs
digital library as well as communicate with the tutors and their fellow students.
We strongly advise you to use this system.
Assignment
For CDOP3103 ă Introduction to Object-oriented Approach, you are required to
do one assignment. The objective of the assignment is:
1. To provide a mechanism for you to check your progress and make sure that
you have met certain learning objectives;
Stott, V. (2002). Web server technology (2nd ed.). London, England: ABC
Publishing.
Assignment Schedule
The assignment will be posted to myINSPIRE before Tutorial 1.
Learners are required to submit the assignment during Tutorial 4. Learners will
get their assignment marks from their tutors during Tutorial 5. Please make sure
to ask for the marks during Tutorial 5. The tutor will post his feedback of your
assignment answer online via myINSPIRE.
Tutorials
The course includes five tutorial meetings of two hours each ă 10 contact hours in
total. The tutorials are conducted to provide an opportunity for you to meet your
tutors and discuss important points in the module. In addition, you have an
opportunity to share your study experiences and difficulties in your peer-to-peer
group discussions. Although the tutorials are not compulsory, you are
encouraged to attend the tutorial meetings as far as possible. It is strongly
recommended that you attend all tutorials, as they will provide considerable
assistance in your study of this course. Moreover, you will have the chance to
meet with other distance learners who are taking the same course.
Table 2
Topic Tutorial
1 Tutorial 1
2 Tutorial 2
3 Tutorial 3
4 Tutorial 4
5 Tutorial 4
6 Tutorial 5
7 Tutorial 5
Case Studies
Topic 2 ă Topic 3 in this module will make use of the following two case studies.
You are required to read and understand the following case studies prior to
learning Topic 2 and Topic 3.
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.
The length of time that a video can be borrowed depends on the video. New
releases are only lent out overnight, current releases are for three-day hire and
the rest are for a week.
MembersÊ birthdays are marked with a special letter inviting them to borrow any
video of their choice for a week for free.
Every three months the shop does a stocktake. Any missing videos are updated
to show them as „Missing‰.
The system Victoria has includes three very good intelligent cash register
terminals to handle all the financial transactions. These terminals handle the
credit card facilities, cash reconciliation, banking and interface with the
accounting system.
However, the current computer system runs on very old hardware (Windows 95)
and is written in an obscure programming language that nobody understands. It
is a very slow and unfriendly system that requires a fair bit of training for new
staff. So Victoria has decided to invest in a completely new system with current
hardware, operating system and software. Hardware and operating system
decisions have not been made.
While she is doing this, she wants to add a data warehouse so that management
can get various statistical reports. For example, they would like to see which
types of videos are most popular or unpopular, who are the best customers, how
many overdue videos there are and so on.
In addition, in the current system, a barcode reader is required to scan the videos,
and members need to present their ID cards to take the video out. This causes
problems when members forget to bring their cards, so Victoria would like to
explore other options.
The following is the functional decomposition of the targeted new system for
VictoriaÊs Videos:
As there are always new staff members joining the shop, the new system has to
be easy to learn and use.
The case study is the NextGen point-of-sale (POS) system. In this case study, we
shall see that there are many interesting requirements and design problems to
solve. This is a realistic problem as organisations really do write POS systems
using object technologies. A POS system is a computerised application used (in
part) to record sales and handle payments and it is typically used in a retail store.
It includes hardware components such as a computer and a bar code scanner and
software to run the system. It is interfaced to various service applications such as
third party tax calculators and inventory control. These systems must be
relatively fault-tolerant. A POS system must increasingly support multiple and
varied client-side terminals and interfaces. These include a web browser, a
regular PC which supports graphical user interface (GUI), touch screen input,
wireless PDAs and so forth.
INTRODUCTION
Writing a big and complex program is not an easy task. There are approaches
such as spiral, prototype, waterfall, modular and object-oriented approaches
that software developers may apply in the development process. One approach
used by human beings to solve complexity problems is the divide and conquer
approach. This approach can also be used in designing computer programs. In
this approach, the main problem is decomposed or broken into smaller problems
or subproblems, each of which is then solved independently.
Figure 1.1 shows this approach for the Student Information System. The solution
designed is based on the algorithmic approach. One important thing in the
algorithmic approach is that it concentrates on the process aspect of the program.
EXERCISE 1.1
(a) Waiter object is responsible for integrating all the relevant activities;
(b) French fries cook object is responsible for frying the french fries;
(c) Sandwich maker object is responsible for preparing the sandwich; and
(d) Hot drink machine object is responsible for preparing hot drinks.
(a) A packet of french fries message is sent to the French Fries cook object;
(b) Chicken sandwich message is sent to the Sandwich maker object; and
(c) A cup of hot chocolate drink message is sent to the Hot drink
machine object.
EXERCISE 1.2
1.2.1 Objects
An object is the most important thing in the object-oriented paradigm. Objects in
an object-oriented software collaborate and work together by sending messages
to implement the behaviour of the software.
What is an object? We can define an object as a thing that has state, behaviour
and identity. All these three properties will be explained in more detail. A few
object examples are given as follows:
(iii) 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 reference. For
example, the car object has a property, where its value is a reference to its
four wheels.
Object properties are also called object attributes. An object state is all the
object attributes plus their values. Figure 1.3 shows the current state of a
Box object. Notice that the content attribute value is a reference to another
object.
EXERCISE 1.3
Again, let us take the vending machine object. One of the messages that it
probably receives is ă release the can drink selected by the buyer. This
message will be sent to the vending machine when the buyer pushes a
button on the machine. The message received causes the object to show a
behaviour, that is, the drink can selected by the buyer is released. This
behaviour actually changes the vending machine’s state since the total
number of can drinks in the machine is one less now.
Besides changing the state, an object can also send messages to other objects
in response to a received message. Figure 1.5 shows the cooperation
between audience, television and remote control objects. When the
button for Channel 5 is pressed on the remote control, the audience
object will send the message change Channel TV(5) to the remote
control object, to change the television channel to Channel 5. The
following are message sequences sent to the television when the remote
control object receives the message:
EXERCISE 1.4
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.
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. Let us
look at Figure 1.8.
EXERCISE 1.5
State how an objectÊs state can influence its behaviour for every event
listed in Exercise 1.4.
1.2.2 Encapsulation
Imagine this scenario. You enter a restaurant. After reading the menu given by
the waiter, you order a plate of fried rice. The waiter goes to the kitchen to
convey your order to the restaurant cook. After about 15 minutes, the waiter
comes back with the fried rice that you just ordered.
In this scenario, you as the restaurant customer do not need to know about the
process that happens in the kitchen to prepare the fried rice. In another words,
you do not need to know about how the fried rice is prepared in the restaurant.
You do not need to know whether the restaurant cook used his grandmotherÊs
secret fried rice recipe or whether the fried rice was bought from the sundry shop
next to the restaurant. As far as you are concerned, your order has been fulfilled
(you got your fried rice). In object orientation, we say that the restaurant
encapsulates the implementation of the fried rice and thus hides the food
preparation from the customer (that is the client).
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
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.
The Square object interface states the messages that can be sent to the object (see
Table 1.1).
Message Purpose
area() When the object receives this message, it will calculate its
area and return the result.
circumference() When the object receives this message, it will calculate its
circumference and return the result.
setwidth(width) When the object receives this message, it will change its
width to the new parameter value.
setHeight(height) When the object receives this message, it will change its
height to the new parameter value.
Because the object interface is general, the information encapsulated in the object
is not revealed in the interface. For example, the Square object interface in
Figure 1.9 does not state the details used by the object to calculate area and
circumference. It also does not reveal the hidden attributes to the client.
An object interface acts like a message menu for the object. A message menu
consists of a list of messages that we can send to an object. If the object is sent a
message that is not listed in its interface, no response can be expected from the
object because it does not understand the message.
Figure 1.10 shows the relationship between the object and its client and the
connection between the object interface and the encapsulated information in
the object. The figure shows the Square object receiving the message
circumference() from the client. Because the message circumference() is
listed in the interface, the object will respond when this message is received.
EXERCISE 1.7
1. Give an example of interface for an ATM machine.
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.
The object that does not interact with any other object is useless in object-oriented
systems. Communication between objects is very important in object-oriented
software because the software must modell the collaboration of objects. For
example, Figure 1.12 shows the communication that occurs between the objects
to change a studentÊs course grade in a student information system.
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.
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.
1.2.5 Class
A big and complex object-oriented software system usually involves many
objects, attributes and behaviours. An example of the system is the student
record system in a university. In this system, the student is modelled as an object.
The system development certainly cannot specify the attributes and behaviours
of every student object as there may be too many students (see Figure 1.13).
This problem can be handled by using the class concept. The entire student object
can be grouped into one category. This category enables us to define the
attributes and behaviours of every object in the category. For example, all
students have the attributes name, age, address, gender and so on. There is also
the behaviour for every student. For example, every student object will respond
when it receives a message to update its address attribute. With the class concept,
we do not have to define this for every object in the system individually.
Instead, we define a category for the objects and their attributes and behaviours.
For example, we can define the Student category to contain all the student
objects in the student record system. In object orientation, the object category like
this is called a class. Class is the template that enables the creation of an object.
Every object in the Student class has the same attributes and behaviours
defined in the class (see Figure 1.14).
(b) Behaviour list for every object in the class. Every behaviour that is listed
contains text that describes the objectÊs response.
The object created from a class is sometimes called a member of the class. The
Student class defined in Figure 1.14 states that every member has the attributes
name, birth date and so on. Also, it lists the messages understood by its
members, that is, changeAddress(newAddress), addCourse(newCourse)
and so on. Besides, it also describes its memberÊs behaviour when receiving a
message.
EXERCISE 1.8
Given in Figure 1.15 are several objects. Put them into suitable classes.
For every class that you have identified, state its members.
1.2.6 Inheritance
To determine the classes for an object-oriented software system, we must actually
categorise the objects involved in the system. An object category can be further
refined into subcategories.
Figure 1.16 shows the Shape class specification. Every object from this class has
the attributes color and location. Besides, the Shape class objects can also
understand the message setColor(newColor), which is to set the color of the
object attribute to newColor. Take note for programming, we use US spelling to
write the coding.
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
Behaviours
The object-oriented term for the object subcategory is subclass. Thus, there are
two subclasses under the Shape class ă Square and Circle classes. The
relationship that exists between the Shape class and both the subclasses is called
inheritance, because every attribute and behaviour in the Shape class definition
will be included (inherited) in the subclasses definition.
Subclasses have all the characteristics and behaviours inherited from the
superclass, but have added characteristics and behaviours for themselves. For
example, after we have created Student class, we could also define another
class for Diploma students, MasterÊs students, etc. in which all will inherit the
Student superclass. It would involve a lot of effort to create a brand new class.
However, it would be easier if we could take an existing class, clone it and then
make modifications to the clone to reflect the extra functionality. Another
example is the employee records system. You could create a generic employee
class with states and actions that are common to all employees. Then more
specific classes could be defined for salaried, commissioned and hourly
employees. The generic class is known as the parent (or superclass or base class)
and the specific classes as children (or subclasses or derived classes). The concept
of inheritance greatly enhances the ability to reuse codes as well as making
design a much simpler and cleaner process.
EXERCISE 1.9
Build two inheritance hierarchies using the classes identified in Exercise
1.8.
(a) Static: The static characteristic of a system is essentially the structural aspect
of the system. The static characteristics define what parts the system is
made up of.
(b) Dynamic: This is the behavioural features of a system. For example, the
ways a system behaves in response to certain events or actions are the
dynamic characteristics of a system.
The static modelling which models the structural part of the system and dynamic
modelling which models the behaviour part of the system need to be performed
by the system analyst before developing a system. This is to ensure that an
effective system can be developed. The static modelling and dynamic modelling
are the subsets that make up the systems modelling which is the key aspect of
most systems development methodologies.
UML defines standardised models and notations for expressing different aspects
of an OO design. Version 1.1 was submitted to the Object Management Group
(OMG) in 1997 and they published it as Version 1.2. Version 1.4 is current. A
major revision for Version 2.0 is in progress. At the core of the UML is the model,
which in the context of a software development process is a simplification of
reality that helps the project team understand certain aspects of the complexity
inherent in software.
The UML was designed to help the participants in software development efforts
build models that enable the team to visualise the system, specify the structure
and behaviour of that system, construct the system and document the decisions
made along the way. While this standard is not perfect for all situations, it does
mean that all practitioners are able to read each otherÊs diagrams. Most IT
professionals use only a tiny part of UML.
Figure 1.18: Overview of the main UML diagrams according to the phases of software
development life-cycle
Copyright © Open University Malaysia (OUM)
24 TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION
The main UML diagrams that can be used for static modelling are:
On the other hand, the main UML diagrams that can be used for dynamic
modelling are:
The object interface is a protocol that must be used to interact with other
objects. It lists all the messages received by an object.
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 that inherits another class is known as subclass. Subclasses have all
the characteristics and behaviours inherited from the superclass, but have
added characteristics and behaviours for themselves.
The static modelling and dynamic modelling are the subsets that make up the
systems modelling, which is the key aspect of most systems development
methodology.
INTRODUCTION
Before developing a system, it is important for the system developer to understand
the system thoroughly. This is done to ensure that the developed system will
behave as expected. Software developers normally will create the model of the
system prior to developing the system. The model will highlight important aspects
of the system such as data flow and interaction between the modules. so that the
implementation can be done without any bugs or defects. An object-oriented
system which is developed using object-oriented programming normally will be
modelled using object modelling techniques. UML is the common „tool‰ used to
perform object modelling in developing object-oriented systems. UML was the
result of the collaboration between three methodologists: Jim Rumbaugh, Grady
Booch and Ivar Jacobson.
Systems can be modelled from two angles: static and dynamic aspects. The static
characteristic of a system is essentially the structural aspect of the system. The
static characteristics define what parts the system is made up of. In this topic, we
will briefly introduce to you some of the UML notations used to visualise the static
features of system using the use case, use case diagram and analysis class diagram.
The next topic will touch on using UML to perform dynamic modelling of a
system.
In addition to use cases, you will learn about three UML diagrams that are used in
conjunction with use cases. Use case diagrams give a pictorial view of the actors
and use cases. Activity diagrams show how some use cases interact to achieve a
business task or process. Use case package diagrams logically group the use cases
to make it easier to understand the big picture.
The requirements for the system are the outcome of this process and represent an
agreement between the system development team members, customers and users.
Note that the requirements will tell what the system will do, rather than how it
will do it. Writing the requirements involve:
(a) Defining the purpose of the system, prioritising its functionality and
specifying its context (that is, who are its users and what systems interact
with it).
(c) Identifying major functionality that must be provided by the system and
describing it.
(d) Documenting assumptions upon which the requirements are based. If the
assumptions change, then so might the requirements.
(e) Communicating with users, clients, business analysts and developers so that
the system that is developed meets the clientsÊ expectations.
The requirements may also involve „proof of concept‰ prototypes, which early on
in the life cycle of the development process confirm or shape the direction of the
solution. The prototypes can be an implemented mockup of some function in the
system, or could simply be sketches of the GUI through which scenarios can be
navigated and confirmed.
(a) Business requirements These define the high-level processes that occur in
an organisation. For example, in terms of a banking system, what is the
purpose of developing a new banking system? Is it going to replace an old
system or is it going to be used in a new line of business?
(b) System requirements What the computer system must do for its users.
These are the functional requirements of the system.
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
(c) Each POS terminal is able to process 100 sales items per minute.
EXERCISE 2.2
VictoriaÊs Videos
In this exercise, we will use VictoriaÊs Videos system, which you were
introduced to in the Course Guide as the basis for some activities.
Have another look at the case study and list two functional requirements
and two non-functional requirements for the system.
The Use Case Model consists of actors and use cases. Actors represent the
entities external to the system, either users or other systems. Use cases
represent the functional behaviour of the system. Actors help define the
system and give you a clearer picture of what it is supposed to do. We will
look at actors further on in the next subtopic.
A use case represents events triggered by actors and describes how the
system must respond. Because use cases are developed according to the
actorsÊ needs, the system is more likely to be relevant to the users.
Figure 2.1 shows the main steps of building and delivering some
functionality. Use cases live through the entire system life cycle and act as a
unifying thread. The same Use Case Model is used during all subsequent
workflows. This topic covers the first three steps in more detail. However,
Step 4 is not covered in the syllabus.
Figure 2.1: The main steps of building and delivering some functionality
(a) Primary ă A person in this role directly uses the system to enter, view process
or extract information. Depending on the user interface, these people will use
a keyboard, a mouse, buttons on a machine or talk to a voice activated
system. Examples in the case study are the checkout clerk and backroom
stock handler.
(b) Secondary A person in this role does not directly use the system, but uses
or generates data for the system. A classic example is a person who receives
reports from a system, particularly in another department in the
organisation. This person may or may not access the system to get the report,
but is a user of the information (typically, these roles are overlooked in the
requirements analysis.) An example in the case study is the managers.
(c) External Any system that receives or generates data for the system these
are external systems. For example, tax office systems, bank, accounts
systems.
Note that this taxonomy differs slightly from UML and in Larman (2002).
Particularly, in UML, users and external systems are treated the same. It is true
that they are both external to the system, but treating people and computers in the
same way is not conducive to building usable systems. Furthermore, our
experience shows that frequently the needs of the secondary actors are often
omitted. Often the need for reporting is known, but instead of the needs being
closely examined, the standard response is to simply add an end-user reporting
tool. Very rarely does this simplistic approach satisfy. If senior management does
not receive any benefits from a system, then the project may be terminated.
EXERCISE 2.3
Identify possible actors for VictoriaÊs Videos system and categorise them
as primary, secondary or external.
There are three types of format for writing use cases. The format to be considered
depends on the need. The explanation for these three types of use cases format are
given as follows:
(a) Brief use case ă It has one paragraph summary and is normally used for main
success scenarios. Here is an example of a brief format use case for Process
Sale (modified from Larman, 2002):
Process Sale:
1. Customer arrives at POS checkout with goods and/or services to
purchase.
2. Cashier starts a new sale.
3. Cashier enters item identifier.
4. System records sale line item and presents item description, price
and running total.
5. Price calculated from a set of price rules.
6. System presents total with taxes calculated.
7. Cashier tells customer the total, and asks for payment.
8. Customer pays and system handles payment.
9. System logs completed sale and sends sale and payment information
to the external accounting system (for accounting and commissions)
and inventory system (to update inventory).
10. System presents receipt. Customer leaves with receipt and goods (if
any).
(b) Casual use case ă It is an informal paragraph which has multiple paragraphs
that cover various scenarios. The Handle Returns given in Reading 2.2 is the
example.
(c) Fully dressed ă This is the most comprehensive case that shows all the
steps and variations. It has supporting sections, such as preconditions and
success guarantees. However, a detailed discussion about a fully dressed use
case is beyond the scope of this syllabus.
Writing a use case is, to a certain extent, like writing a report and as you will know
if you have ever written a report, it is much easier if you can follow some kind of
format. Most companies and organisations have report templates for people to
refer to. Similarly, for use cases there are templates that system analysts can refer
to. One of the most popular use case templates was developed by Alistair
Cockburn. However, use case templates are not covered in this course.
EXERCISE 2.4
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.
Now select another use case and also write it in a brief format.
(c) Represents the goal of an interaction between an actor and the system; the
goal represents a meaningful and measurable objective for the actor;
(d) Records a set of paths (scenarios) that take an actor from a trigger event (start
of the use case) to the goal (success scenarios). The Process Sale use case given
in Subtopic 2.2 is an example of success scenario; and
(e) Records a set of scenarios that traverse an actor from a trigger event toward
a goal but fall short of the goal (alternate scenarios). The format to write an
alternate scenario is as follows:
condition:
handling
Example of alternate scenarios for Process Sale are given as follows (Larman, 2002)
based on the previous format:
Write the condition as something that can be detected by the system or an actor.
The previously mentioned examples only have one handling for the conditions.
There can be more than one handling for certain conditions.
Remember that a use case may have a main success scenario and some alternate
scenarios. Sometimes, when we have a large and complicated system to develop,
there will be lots of different scenarios. It would be impossible to discover all the
possible scenarios at the very beginning. Hence, when you first start writing use
cases for a system, it is best to ignore all the alternate scenarios and only think
about everything going well the „sunny day scenario‰. Alternative scenarios can
be added later after you have identified all the success scenarios. Of course,
successful scenarios can also be revised and changed in later stages.
EXERCISE 2.7
We have written up a main success scenario for the borrow videos use
case in Exercise 2.4. Try to think up a few alternate scenarios and present
them in a brief format similar to the main success scenario. Compare
your answer with your coursemates.
A model such as a Use Case Model helps system developers to build their systems
in a systematic manner. Poor system development tends to be done by developers
who cannot judge what they should be doing at each phase of the development
cycle. A common mistake is to jump into the system design before a good
requirements analysis is available. The black-box use cases approach is usually
adopted to help system developers avoid making the same mistake twice. Let us
now discuss the term. Something is a black box if we cannot see the inner workings
of it.
For example, from a car driverÊs perspective, a car is a black box. The car either
moves properly or it does not. If there is a problem, then the car mechanic comes
and, with a white-box view, lifts the car bonnet and looks at the engine and
internals. Hence, in the black-box approach of use cases writing, we do not care
about how the system will perform the tasks but just focus on what we should
expect from the system. In other words, we are only focusing on the
responsibilities of the system. Examples of black box use cases are shown in
Table 2.1.
Sometimes confusion will still arise even if we adopt the black-box approach,
because different people have a different understanding of „what the system
does‰. For example, a cashier might think of his goal as „logging in‰, but in fact,
this is just the mechanism that achieves the higher-level goal of identifying and
authenticating himself. When writing use cases, keep the user interface out and
focus only on actor intent.
EXERCISE 2.8
Now take the three use cases from Exercises 2.4 and 2.6 and rewrite them
in the essential two-column format. (Yes, writing use cases is hard work,
but the more you write, the easier it gets. It is not good enough to just
look at the answers. You must practise).
Well, which one of these two requirements should be turned into a use case? In
fact, neither of them would make a good use case. The general managerÊs goal is
at too high a level while the cashierÊs goal is too low. So what level of user goals
can be transformed into use cases? The general guideline is to look at elementary
business processes (EBPs). The following Reading 2.1 will explain to you the
concept of EBP. It also gives a very lively example of how a system analyst
investigates the user goal of the cashier through a series of questions and identifies
the appropriate goal level for writing a use case.
READING 2.1
Now download Reading 2.1 from myINSPIRE to learn about goals and
scopes of the use case.
READING 2.2
Now download Reading 2.2 from myINSPIRE to learn more about the
four-step procedure to define use cases as listed just now.
EXERCISE 2.9
For VictoriaÊs Videos, up to now we have tried to identify the actors
and some brief use cases. However, all these were produced by our
imagination. In a real system, the proper way to do requirements analysis
is to carry out a combination of many activities such as:
(b) Look at any systems that currently exist. Look at screens and
reports. See if you can track some real examples all the way
through. For example, for an insurance system, you could see how
a policy is created, and then later how a claim might be processed.
Prepare a list of questions that you would like to ask various people from
VictoriaÊs Videos.
It is important that you understand the use case model as it is a crucial element in
requirementÊs analysis and it is one of the earliest tasks in the whole system
development project. The future success of the project depends on getting the use
case right. As it is sometimes helpful to approach a topic from a different angle,
we would like you to reinforce your understanding of the Use Case Model by
working through the next reading by Cockburn.
ACTIVITY 2.1
Internet Reading
Cockburn, A. Structuring use case with goals at
http://alistair.cockburn.us/Structuring+use+cases+with+goals
(b) Actors can be defined as something that interacts with the system. It can be
human users, some internal or external applications; and
The following figure is the simple UML notation to depict a use case.
A collection of use case diagrams will form a context that show the scope of the
system and the relationship between the actors and the use cases. It serves as a
diagrammatic summary of the behaviour of the system. According to Larman
(2002), use case diagrams are only secondary in use case writing. System
developers should not spend too much time drawing use case diagrams. Writing
use case text should be the primary focus.
READING 2.3
Now download Reading 2.3 from myINSPIRE to learn about use case
diagrams in detail.
EXERCISE 2.10
By using the example of the use case diagram shown in this exercise as a
guide, draw a use case diagram for VictoriaÊs Videos.
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.
EXERCISE 2.11
Do you think an activity diagram would help explain how a subset of the
use cases for VictoriaÊs Videos system fit together to form a whole? If so,
then draw it. Note: We are not trying to draw all the use cases of the
whole system, but only some of them that make up a process that makes
sense to the users as a whole.
(b) The use cases are written from the systemÊs point of view;
(h) The use case does not correctly describe functional entitlement;
(i) The customer does not understand the use cases; and
In writing this list, Lilly (1999) is not arguing against use cases, but trying to alert
newcomers to the potential problems, and suggesting ways to avoid them. She
advises:
(a) Explicitly define the systemÊs boundary. This makes clear what is inside and
outside the system.
(c) When writing use cases, focus on the goals of the actors. This will help you
find use cases from the usersÊ perspective and keep a focus on the primary
function of the system.
To help catch potential problems, Lilly suggests that you review your Use
Case Model, the diagrams and specifications, in incremental steps with the
development team, clients and users. Start by reviewing your use-case diagram
before you have defined use case details; check that the system boundary has been
clearly defined, that obvious actors have not been missed and that the use cases
focus on the usersÊ goals.
EXERCISE 2.12
Deciding on the packages for a system requires a little experience, and there
are generally several valid approaches for one system. Some possibilities for
packaging the use case are listed as follows:
(a) By functional areas. For example, put everything to do with money in one
package, and inventory in another;
(b) By actor. For example, put all the cashierÊs use cases in one package;
(c) By „style‰ of use case. For example, put all the simple setup or maintenance
style use cases in one package;
(d) By importance or iteration. For example, all the use cases that are going to be
built first could be in one package; and
(e) By physical implementation. For example, all the use cases that are delivered
via the Web are in one package, and use cases accessed via the head office
computer are in another package.
The UML notation for a package is a folder. But, as emphasised earlier, the text of
the use case is more important than the diagrams. So often a use case package is
simply a short description of the use case, followed by a list of the use cases that
comprise the package. Optionally, include a use case diagram of the use cases.
Figure 2.5 summarises the use case package.
There are many different approaches and styles to writing use cases. Reasons for
these differences include personal preferences, different styles of application (for
example, a website selling books is different from a stock market trading system),
and different scales or styles of development (for example, two people on a three-
month project work very differently than 50 people on a two-year project).
The next reading is a review of use cases, written by their inventor, Ivar Jacobsen.
He starts with a short history of their development.
ACTIVITY 2.2
Internet Reading
Jacobsen, I (2003) Use cases ă yesterday, today and tomorrow at
https://goo.gl/ld1bmw
Read up to the end of page 4, up to the start of the section titled „How
many use cases is enough?‰
As you can see from this reading, one aspect of use cases that has been evolving
since 1986 is how we can relate one use case with other use cases. Relating use
cases to each other allows us to see commonalities and differences between them.
(a) Include ă Typically where a set of use cases each includes some common
functionality that is expressed in one shared subuse case;
One more word of caution. As you saw in the reading, Jacobsen has changed his
views on how best to relate use cases. Use cases are not mathematically defined,
so the relationships between them are not rigorously defined, either. You will
probably find that when you read the details on the different types of relationships,
it will all seem quite simple, but that when you try to apply this knowledge, it can
be quite hard. Everyone, both novices and skilled practitioners, face the same
problem. The solution is to remember that use cases are for human use.
ACTIVITY 2.3
Internet Reading
Jacobsen, I (2003) Use cases ă yesterday, today and tomorrow at
<http://www.therationaledge.com/content/mar_03/f_useCase
s_ij.jsp?from=inbrief>
Read pages 4ă5, that is, the sections „Use cases and the unified modelling
language‰ and „Use caution when formalising use cases‰.
Note: The rest of this reading, starting from the heading ÂTomorrow:
potential next stepsÊ, is more advanced and theoretical.
As an example, let us consider VictoriaÊs Videos. We have identified the use case
Maintain Members (from Exercise 2.6). The next table is a first draft for that use
case.
Now compare this use case with Borrow Videos (from the answer for Exercise 2.9).
Is there anything in common? Yes. The first line for each is the same: „Identify the
borrower‰. As we are looking at use cases in essential format, this might not seem
like very much. But before we can build this system, we will have to decide how
the borrower will be identified. Will the user have a card to be scanned or will he
give us his name or an identification number? Will he need to quote a password?
So to cater for all these later concerns, we can create a subuse case that we will call
„Get Borrower‰. Now both the Borrow Videos and Identify Members use cases
will ÿincludeŸ the Get Borrower subuse case (note the UML notation of placing the
special characters ÿ Ÿ around the word „include‰).
So now, how do our use cases look? In long hand we could have:
These days, the use of underlined text in a website means a hyperlink to something
else. This convention is used for use cases to indicate a subuse case. So a short way
of writing is simply to underline the use case name as shown in Table 2.4.
Level: Subfunction
Actor Intention System Responsibility
Identify the borrower Display personal details (name, address, date of
birth, date joined) 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 subuse case, as it only gives us a subfunction, that is, this use case
makes no sense by itself. It needs to be called by another use case.
EXERCISE 2.13
Let us again think back to the situation of VictoriaÊs Videos. You already
have a use case to borrow videos. But now Victoria tells you that she
would also like to sell old videos that she does not need.
Update your use case diagram (from Exercise 2.10) with any new use
cases.
They include relationship is the most useful relationship between use cases and
you can build very sophisticated models using only this relationship. Indeed,
Cockburn (2002) writes:
As a first rule of thumb, always use the include relationship between use
cases. People who follow this rule report that they and their readers have less
confusion with their writing than people who mix includes and extends and
[generalises].
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.
MemberÊs birthdays are marked with a special letter inviting them to borrow
any video of their choice for a week for free.
So we obviously we need a use case to generate the birthday letters that is, a
straightforward use case. But how do we handle the situation when a person
comes to the shop with their birthday letter wanting to borrow a video for free?
Clearly this is an extension to the use case Borrow Videos.
So how would these use cases look? Let us look at Table 2.6.
Level: Subfunction
Trigger: Customer has a birthday letter
Extension point: Calculate total fee due in Borrow Videos
Actor Intention System Responsibility
Indicate that the borrower has a birthday Confirm birthday borrowing has not
letter already been used this year
Record use of birthday letter
Adjust total due
Once again you can see we are at the subfunction level. The trigger clause tells us
when it gets started, namely when a customer has a birthday letter. The extension
point tells us that the use case Handle a Birthday Letter gets started from the use
case Borrow Videos when it reaches the part „calculate total fee due‰. This is called
an extension point.
Lastly, to keep the use cases tidy, we can document the Borrow Videos use case to
show that there is an extension. In other words, we make it clear to someone
reading this use case that, as part of „calculate total fee due‰, there is something
more happening.
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.
A very common use of the extend relationship is for some action that can be taken
at any time. A common example is the ability to print the information on the screen
at any time.
So, for example, if we had the Maintain Members use case, then at any time the
front-desk clerk should be able to print out a summary of the member.
EXERCISE 2.14A
As discussed in the preceding section, a print function is an example of
the extend relationship. Write the Maintain Members use case, including
anything required to allow the user to print. Also draw the use case
diagram.
Figure 2.9: The generalisation relationship also can be used for actors in the use case
diagram
ACTIVITY 2.4
Internet Reading
Gottesdiener, E. (1999). Capturing business rules. Software Development
Magazine, 7(12), at
https://goo.gl/1pu6yh
In fact, besides their role in the use cases, business rules are also linked to other
artifacts in the software development process. The following reading discusses
such links, in particular to user interface designs, data cleansing and validation.
ACTIVITY 2.5
Internet Reading
Ambler, S. (2000). Object-oriented business rules. Software Development
Magazine at https://goo.gl/mBJA4d
In the last section of the reading, Ambler mentions the object constraint language
(OCL) as a means to express business rules. Other experts disagree. For example,
Gottesdiener says that business rules should be written in a language that the users
understand. We also like to adopt this approach in writing business rules. The
following are some options that we suggest can best express business rules:
(a) List all the rules in one list, and then refer to the list from everywhere else
Use cases, screen mockups, class diagrams and others;
(b) Simply locate the rules in the use cases, as we have done in this course; and
(c) Keep the use cases simple, but add a section to your use case template to
explicitly refer to the business rules that each use case implements.
So, as you can see, there is a range of possibilities. Additional factors to consider
are the style of system (for example, does it involve lots of calculations), the size of
the application, the tools that are being used and so on.
So what are the business rules in VictoriaÊs Videos? Here are some examples:
(b) When a new person requests to become a member, they must show their
driverÊs license or other photo ID;
(d) A member can borrow any number of videos, as long as they have no
overdue videos;
(f) The length of time that a video can be borrowed for depends on the video.
New releases are only lent out overnight, current releases are for three-day
hire, and the rest are for a week;
(h) Every video has a classification, (general G, parental guidance PG, mature
audiences MA and restricted R). Members must be over 18 to borrow R
videos. Every video also has a category: Romance, General, Sci-Fi, Foreign
Language and Children;
(i) When a member has a birthday, they are sent a special letter inviting them to
borrow any video of their choice for a week for free;
You should recognise most of this text as it is pretty close to the initial description
that you saw from Victoria Videos Case Study. When describing a system, one
very common method is to list and describe the business rules. The skill of a
requirements analyst is to capture these rules and make them into something that
the rest of the design and programming team can work with. Use cases are a key
way of weaving the business rules together to create a system.
EXERCISE 2.14B
For each of the example business rules we have just given for VictoriaÊs
Videos, decide if the rule has been captured in any use case(s). If so, name
them. Or, you might note that a business rule has not yet been captured
in any use case.
The previous exercise should have helped you to appreciate the fact that quite a
strong link exists between use cases and business rules, but that each form is quite
different.
Up to now there has been nothing object-oriented in the material. We could write
use cases and then continue in a non-object-oriented manner. Now, we will start
the object-oriented modelling using the analysis class diagram. While the material
is presented to you sequentially, in reality, the object-oriented modelling happens
in parallel with the use case writing.
This subtopic is all about „analysis class diagrams‰. The example of an analysis
class diagram is shown as follows (Larman, 2002):
(c) Attributes Which are logical data values of an object. For example, each
member may have a „memberÊs number‰ which is an attribute of the object
„member‰.
Remember ⁄
Analysis class diagram which is produced during the analysis phase is a
visualisation of things in the real world domain of interest and NOT the
software components such as Java classes. On the other hand, the relationship
between the software classes, which depicts the details of the classes are done
through the design class diagram which takes place during the design phase.
However, design class diagram is beyond the scope of this syllabus.
EXERCISE 2.15
Before we go into the details of the domain model, let us make sure we
are clear about its function. Refer to the following diagram:
Do not be concerned with the exact meanings of the notation ă the lines,
words, arrows, etc. ă as this is all explained later in this topic. For the
moment, just try to read the diagram with the following words, starting
in the top right-hand corner: Items are Stocked-in a Store. A Store. has
an address (for example, 15 Jalan XYZ, Ipoh) and a name (for example,
Kedai Perabot Ali). Each Store houses, or has, some Registers. Every
Sale is captured-on, or recorded on, a Register.
Continue with this description to cover all the domain objects and
relationships.
As the relationship between a class and its objects is so clear, we often get a bit lazy
with our language. If the head of engineering for a car factory says: „The painting
on the car needs to be done better‰, he is probably talking about the process that
goes on in the factory rather than a specific car. So, too, in software modelling; we
swap between using the words class and object.
The entity objects fall into a number of categories, based on the real-world objects
that they represent. Here are three kinds of conceptual classes that we will
encounter in business modelling:
(a) Concrete objects are tangible, that is, have a physical presence. Concrete
objects are the most easily understood by analysts and users. In the video
shop example, video CD is a concrete object.
(b) Conceptual objects are intangible and often far more difficult to understand.
For example, school is a conceptual object. You may argue that a school
tangibly exists it has buildings. However, the concept of a school is not just
the buildings. Imagine that all the buildings in a school collapse in an
earthquake. We cannot say that the school does not exist anymore. It can be
rebuilt. Similarly, a video title is also a conceptual object.
(c) Event and state objects are highly abstract in nature. They are related in that
typically when an event of any significance occurs, some or more objects will
switch to a different state. An example of an event and state object in the
video shop is borrow video. We can see that borrow video events will
typically change the status (for example, borrow video list) of the object.
(c) Extension ă The set of examples to which the conceptual class applies.
For example, in a credit transaction, the conceptual class can have the symbol
Borrow. The intension of Borrow could be „represents the event of borrowing
transaction which has a date and transaction ID‰. The extension of Borrow is all
the examples of borrow.
There are a number of ways that we can identify conceptual classes systematically.
One method is to come up with a conceptual class category list. We have already
categorised conceptual classes into three broad categories, namely concrete
objects, conceptual objects and event and state objects. These three categories are
further expanded into finer categories according to Table 2.8.
Even though the category list as presented is drawn from some particular domains
(in the Table 2.8 case, the store domain), it more or less covers many common
categories in other business domains.
EXERCISE 2.16
Another technique for identifying conceptual classes is the use of the noun phrase
identification. You will see that one of the arguments for developing use cases
before domain modelling is that they are an excellent source of noun phrases for
conceptual class identification. However, note the danger of ambiguities in the
natural language of use cases translating to the conceptual classes if the
transformation of one to the other is made too mechanically.
Now, let us look at one example in which we are going to use the noun phrase
identification to identify conceptual classes.
Example 2.1:
Below is a description of a Web-based ticket reservation system. All the noun
phrases that are candidates for conceptual classes are highlighted in bold.
Before they can use the site, customers must register their contact details or
enter sufficient information to identify them if they have registered before. They
may then view publicity material and ticket availability information for a
number of different events and add tickets for chosen events to their order.
When they have finished, they enter their credit card details and, if all is well,
their tickets will be dispatched through the post. The company keeps a contact
address and a billing (credit card) address (which may be the same) for each
registered customer.
Concentrate just on the customer side ă do not model the supply of tickets from
„the usual ticket agencies‰.
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:
In the video shop example, suppose we have the video Star Trek that has once been
in stock. The video has a video title, video classification and video category and
others that go with it. After the video has been borrowed by a member and he has
lost it, the video will be deleted from the system. If the management needs to
obtain some information about the video (for example, what classification it is)
there is no way they can obtain that information. To solve this problem, we need a
(b) Deleting instances of things that they describe (for example: Item) results in
a loss of information that need to be maintained; and
EXERCISE 2.17
2.7.5 Associations
Now, we have successfully identified the conceptual classes in the business
domain. Say, in the video shop system, we have identified „Member‰, „Video‰,
„FrontDesk‰, „MemberRecord‰ as the conceptual classes (please note that this is a
highly simplified domain model and may not be the real domain model for the
video shop case). What are we going to do with all these objects (or conceptual
classes)? An obvious answer is to find out how they are related. An association is
an object-oriented term for relationship.
People in the real world have relationships with other people, with things and with
places. So we can say a person has a mother, is married to their spouse, likes to
drive their Porsche, lives in a house and so on. These are the associations of the
object „people‰ to other objects in the real world. We notice that most of the
relationships between the object „people‰ and the other objects are described by
verbs such as „has‰, „married to‰, „likes to‰, „lives in‰ and so on.
The following Figure 2.13 shows the relationship between two conceptual classes
„Member‰ and „Video‰.
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.
Begin with a list of all the classes on the left and the UML diagram of all the classes
drawn (without association) on the right, as shown in Figure 2.14. Pick the first
and second classes in the list, that is, „Member‰ and „Video‰ and check whether
they have a relationship (either from the use case or discussion with users). If there
is a relationship (in this case „Member Borrow Video‰), add an association to the
UML diagram. At the same time, a line is drawn linking the „Member‰ and
„Video‰ items in the list, indicating that the relationship of these two classes has
been checked.
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.
The process is repeated with the other items down the list, that is, the „Member‰
ă „MemberRecord‰ pair. If a relationship exists, an association is added in the
UML diagram. For the items in the list, even though there is no relationship
between two items, such as „Member‰ and „MemberRecord‰, a link is also drawn
to connect the two items to indicate that the relationship between the two has been
considered. When „Member‰ and all the other items down the list have been
linked, it indicates that the relationship between „Member‰ and all the other
classes has been considered (regardless of whether or not they have an association
in the UML diagram). We can move on to the next step.
In the next step, the relationship between the class „Video‰ and the other classes
down the list is considered. Similarly, items are linked after their relationship has
been checked and an association is added between any two classes in the UML
diagram if a relationship exists.
This step is repeated with class pairs down the list until all class pairs have been
considered. The final model will look like Figure 2.16.
The effort involved may not be justified when some of the associations are not
significant or meaningful to the model. Hence, Larman (2002) has proposed the
„common association list‰. This method is based on the „need-to-know‰
association principle to avoid too many resulting associations, which would lead
to confusion in the model. The „common association list‰ by Larman (2002)
contains common categories that are usually worth considering in determining the
relationships between the classes. The common association list is given as follows
for the airline reservation system (see Table 2.9).
Category Examples
A is a physical part of B Wing-Airplane
A is a logical part of B FlightLeg-FlightRoute
A is physically contained in or on B Passenger-Airplane
A is logically contained in or on B Flight-FlightSchedule
A is description for B FlightDescription-Flight
A is a line item of a transaction or report B MaintenanceJob-MaintenanceLog
A is known, logged, recorded, reported or Reservation-FlightManifest
captured in B
A is member of B Pilot-Airplane
A is an organisational subunit of B Maintenance-Airplane
A uses or manages B Pilot-Airplane
A communicates with B ReservationAgent-Passenger
A is related to a transaction B Passenger-Ticket
A is transaction related to another transaction B Reservation-Cancellation
A is next to B City-City
A is owned by B Plane-Airplane
A is an event related to B Departure-Flight
2.7.7 Multiplicity
As you identify and draw each association, you will initially draw it as a simple
line joining two boxes in the UML diagram. Once you have established the
association, for example, „Member Borrow Video‰, there is another question to
ask: How many videos will the member borrow? This question relates to the
multiplicity of the association.
The multiplicity of an association is the number of instances of each class that can
participate in an occurrence of the association. The following table lists some
possible multiplicity values for associations. Multiplicity is an important piece of
information for the later system design stage. It communicates important domain
constraints that will affect the software design, especially in database design in the
implementation stage. Let us look at Table 2.10 for multiplicity values.
Multiplicities Meaning
11 one-to-one
1* one-to-many
1 1..* one-to-one or more
1 0,1 one-to-zero or one-to-one
Figure 2.17 depicts the domain model of the video shop system with multiplicity
added.
Figure 2.18 shows a design class diagram which has association, composition and
aggregation relationships. Multiplicity of an association between classes is also
shown in the figure as follows:
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:
(c) Too many associations will lead to confusion and marginal benefit; and
EXERCISE 2.18
2.7.10 Attributes
Attributes are the pieces of data we use to identify or describe things. For example,
a person has a name, date of birth and eye colour. Attributes usually correspond
to nouns followed by possessive phrases, such as „the cour of that car‰. In this
case, colour is the attribute of car. Attributes are usually simple data types or
primitive data types such as integer, float, string, date, time and others.
For the video shop system, the following are possible attributes to the conceptual
classes identified:
In UML, attributes are shown in the lower compartment of the rectangular box
representing the conceptual class. Hence the completed domain model, as
represented in UML for the video shop system is as shown in Figure 2.20.
Each date may be described by many other variables. For example, maximum,
minimum and average temperature, hours of sunshine, total rainfall, average wind
speed and so on. These analyses might also require separate attributes for the day
of the week, month and year. In this case, we might then choose to treat „Date‰ as
a separate conceptual class with the other variables as its attributes.
(a) If the independent existence of an entity is important, rather than just its
value, then it is a separate class;
(b) An entity that has features of its own within the given application is a
separate class;
(d) A name is a class attribute when it does not depend on context, especially
when it need not be unique;
(e) Do not list object identifiers that are used purely for unambiguously
referencing an object;
(f) If an attribute describes the internal state of a class that is invisible outside
the class then eliminate it from the analysis; and
(g) Omit minor attributes that are unlikely to affect most operations.
READING 2.4
EXERCISE 2.19
The following tips by Larman (2002) are very useful when creating analysis class
diagrams:
(a) Use Conceptual Class Category (from Table 2.8) or noun phrase
identification to identify the conceptual classes.
(c) Add the associations necessary to show the relationship between the classes.
A system can be modelled from two angles: static and dynamic aspects.
The static characteristics define what parts the system is made up of.
In this topic we will briefly introduce to you some of the UML notations used
to visualise the static features of a system: use case, use case diagram, activity
diagram and analysis class diagram.
The use case model includes the identification of actors, their goals and the
writing of use cases.
Sometimes, use case diagrams can be used to help understand the overall
picture of the system, the flow of events and the relationship between actors
and use cases.
Basically, use cases are textual in nature where, probably to a minimal extent,
the help of some use case diagrams facilitate the understanding of the use
cases.
You modelled a business domain with a highly abstract analysis class diagram.
You learned how use cases are used to aid conceptual class identification.
You also identified the associations between conceptual classes and found their
intrinsic properties by identifying their attributes.
INTRODUCTION
The previous topic has dealt with static modelling using UML. Now, this topic
will focus on dynamic modelling using UML.
There are three kinds of diagrams in UML that depict dynamic models. State
diagrams describe how a system responds to events in a manner that is
dependent upon its state. The other two kinds of dynamic diagrams fall into the
category called interaction diagrams. They both describe the flow of messages
between objects. However, sequence diagrams focus on the order in which the
messages are sent. They are very useful for describing the procedural flow
through many objects. They are also quite useful for finding race conditions in
concurrent systems. Collaboration diagrams, on the other hand, focus on the
relationships between the objects.
They are very useful for visualising the way several objects collaborate to get a
job done and for comparing a dynamic model with a static model. Collaboration
and sequence diagrams describe the same information and can be transformed
into one another without difficulty. The choice between the two depends upon
what the designer wants to make visually apparent.
The following Table 3.1 gives some examples of systems and a list of their
conceptual classes. The third column suggests the conceptual classes that
probably require a state diagram. As you can see, the words in the third column
are really the core of each system.
Table 3.1: Examples of Systems and Conceptual Classes that Require State Diagrams
EXERCISE 3.1
Suppose we have just started work and we have identified three use cases:
(a) Admission Handles the prisoner being transferred from the police or
courts to the prison, and being admitted.
(c) Release Handles the way in which a prisoner is released back into the
community.
In parallel with identifying and writing use cases, we are also working on the
conceptual class model. Quickly we will realise that Prisoner is a key conceptual
class, so we start to draw its state diagram.
What does a state diagram look like? Here is an example (see Figure 3.1).
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 as shown in
Figure 3.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:
After some discussion with the user, we could redraw the diagram like this (see
Figure 3.3).
This new version has a new state called Escaped (notice that it ends in „ed‰), and
we have identified two new use cases, namely Escape and Re-capture. This is the
crucial point of drawing state diagrams they help us to quickly find missing
use cases.
Notice in this last diagram that we now recognise that some escaped prisoners
never get re-captured.
EXERCISE 3.2
For VictoriaÊs Videos, draw two separate state diagrams, one for Video
Tape and one for Member.
That is fine, but prisoners can also escape from being in the half-way house.
Of course if we capture them, then they go back into custody.
You will notice that there are two transitions, or use cases, called Escape. Now
since these refer to the same use case, we can simplify the diagram by
introducing the concept of a super state.
In the next version you can see that there is a super state called Admitted. So
what we are now saying is that if a prisoner is In custody or In a half-way house,
and they Escape, then they will be in the state Escaped. Once they are in the state
Escaped, if they are re-captured, they go to the state In custody (see Figure 3.5).
(a) Classes, denoted as class rectangles, to represent the objects involved in the
interaction;
(b) Association roles, which represent roles that links may play within the
interaction; and
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.
READING 3.1
Download Reading 3.1 from myINSPIRE to learn the details of
collaboration diagrams.
In addition to the notation in the reading, there is also the concept of a multi
object (see Figure 3.7). This is also known as a collection object (such as a list). So
a message which is shown as being sent to a multi object, is really a message sent
to the collector of that object. The collector then finds the correct object.
EXERCISE 3.3
Look at the following collaboration diagram. It shows the use case of a
thirsty person coming into a restaurant and requesting a drink from a
Bot. Think of a Bot as a robot that interacts with the other parts of the
restaurant.
(a) Class roles, denoted as class rectangles, represent roles that objects may
play within the interaction.
(b) Lifelines, denoted as dashed lines, represent the existence of an object over
a period of time.
(c) Activations, denoted as thin rectangles, represent the time during which an
object is performing an operation.
Typically a sequence diagram shows one use case. However, to adequately show
how errors are handled, often extra diagrams are required. Figure 3.10 shows the
example of an ATM machine system.
READING 3.2
Download Reading 3.2 from myINSPIRE to learn the details of a
sequence diagram as shown in Table 3.3.
EXERCISE 3.4
Take the collaboration diagram in Exercise 3.3 and translate it into a
sequence diagram.
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.
In terms of its actions, an instance of a class may do something itself, may cause
another class to do something by initiating an action or controlling or
coordinating its actions. These are a few types of „doing‰ responsibilities that
must be defined appropriately for classes in a system.
A classÊs responsibilities might be: knowing about its own data, knowing about a
related object or knowing about things it can figure out.
(a) Knowing about private encapsulated data (for example, the knowledge of
size of the glass in Exercise 3.3);
Where do we begin? We start with the GUI telling the Register it is ready to
create a new sale. This is a simple create operation on the class Sale. Next, the
GUI sends the Register the id or barcode of the item and the quantity. Next we
need to find out what the item is, as per our robustness diagram. Let us just
check that this is correct. For this, look at the conceptual class model as shown in
Figure 3.11.
What do you notice about the itemId? Is this attribute on the Item class?
No, it is not it is on ProductSpecification. But how do we get to
ProductSpecification? From the domain model, we know that it is from the
ProductCatalog. We are trying to get a whole ProductSpecification
object back, so note the syntax of message 5 from Figure 3.11. Next the
ProductCatalog object sends a message to the ProductSpecification
collection object, denoted with the special notation. This collection object finds
the correct ProductSpecification and sends it back.
(Note: At this point we have assumed that all these objects are sitting around just
waiting for us to talk to them. In reality, of course, they would be in a database
and we would have to do some work to get them out. However, getting data in
and out of databases is not covered in this module.)
Lastly, the payment is made (assume it is cash only, and that correct money is
given) and the Payment object is created (see Figure 3.12).
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
1. Draw a sequence diagram for Process a Sale, based on the
understanding of the collaboration diagram that has been given in
Figure 3.12.
2. Draw a collaboration diagram and a sequence diagram for the use
case Borrow Videos in the VictoriaÊs Video case.
Thus, the designer must iterate between the two kinds of models, driving
them to converge on an acceptable solution.
INTRODUCTION
The previous topics have dealt on how to create models of object-oriented
systems. In particular, you have learned how to perform systems modelling
using UML. You have learned that UML can be used to perform static and
dynamic modelling for object-oriented systems. A model is just a model in the
sense that it cannot be executed. A model gives us a solid understanding about
the nature and behaviour of the system. A model acts as a blueprint in order to
implement the system. The object-oriented programming language such as Java
is the popular language used to implement UML models. This topic and onwards
will focus on the Java programming language.
What is so special in Java that computer industries and businesses can accept it
within a very short period of time compared to other new technologies in the
computer history? The answer to this question is provided in Subtopic 4.2
Characteristics of Java. The next subtopic will give an overview of Java.
Figure 4.2 illustrates the Java programming environment. The output of a Java
program compilation is in the form of a bytecode. The Java bytecode is a set of
instructions that is quite similar to the machine code instructions or native code
for a machine. The difference is that the bytecode is not specific to any processor.
The result of compilation can be implemented by a Java Virtual Machine (JVM),
or any machine that will interpret the bytecode.
(a) Simple
Java has functionality needed to implement its rich feature set. It does not
add lots of syntactic structure or unnecessary features.
(b) Object-oriented
Almost everything in Java is either a class, an interface, a method or an
object.
(d) Safe
Java code can be executed in an environment that prohibits it from
introducing viruses, deleting or modifying files, or otherwise performing
data destroying and computer crashing operations.
(f) Multi-threaded
Java is inherently multi-threaded. A single Java program can have many
different things processing independently and continuously.
Part of IDE uses the Rapid Application Development (RAD) approach. RAD
accelerates the software development process by using tools such as the interface
designer. Many of the Java IDEs available in the market use the graphic interface
builder to support RAD.
The following are some Java IDE softwares with their URLs:
WinEdit (http://www.winedit.com/)
Jcreator (http://www.jcreator.com)
ACTIVITY 4.1
Apart from application, another type of Java program is applet. Applet is a web-
enabled program. The examples of test-based applications will be illustrated in
the next subtopic. Applet and frame are not covered in the syllabus. Applets are
covered in another course, CDOP3203 ă Java Programming. We will skip any
elaboration about frame and applet in this module.
Line Number
In the structured approach, all the statements and instructions are dumped into
the main method. Sometimes, extra methods could be added to perform specific
tasks. No objects are required to be created when writing Java programs using
structured approach. The previous Program 4.1 is described as follows:
Line 1
Line 1 in the program is comments written by the programmer. It helps others to
understand the nature of the program. Thus, the program becomes more
readable.
Line 2
Line 2 declares the name of the class as Hello.
Line 3
Line 3 is where the program starts to execute. In this class, a method called
main() contains the statements to display the „Hello world!‰ string. The
main() method must be present in all Java applications because it is the first
method that will be executed when an application runs (that is, it is where the
program starts to execute). The Java technology interpreter must find this
defined exactly as given or it will refuse to run the program. The following
describes each element of line 3:
static: This keyword tells the compiler that the main() method is usable
in the context of the class Hello. No object is needed to execute static
methods.
void: This keyword indicates that the method main() does not return any
values (that is, there is no return keyword in the main() method).
String[ ] args: This method declares the single parameter to the main()
method. The name of the parameter is args with the type of string array.
Line 4
The statement System.out.println(“Hello world!”) in Line 4 in the body
of the method will instruct the computer to display the message „Hello world‰
upon execution.
Line 5, 6
Line 5 and 6 contain two braces to close the method main() and class Hello
respectively.
Note: Before doing this activity, please download Java Development Kit (JDK)
which is downloadable from myINSPIRE (click eServices Resources for IT).
The JDK version available in myINSPIRE is version 6.0 (1.6; jdk1.6.0 update
24).
The purpose of this exercise is for you to compile and execute Program 4.1. It
is compulsory for you to follow all the steps to ensure that you learn how to
compile and execute a Java program using JDK.
Step 1
By using Notepad in Windows, type Program 1.1. Then, save it in a file with
the name Hello.java in the jdk1.6.0_24/bin directory. (In this example, the Java
file is saved in the C:\jdk1.6.0_24/bin directory. You may have a different
directory for jdk1.6.0. Check your correct jdk directory from Windows
Explorer).
Step 2a
Now lauch the Command Prompt from the Start button of your Windows
by typing „cmd‰ without the quotes and then press <enter> as shown in the
following:
Step 2b
In your command prompt, type cd:\ to enter the directory C:\ as shown in
the following:
Then, you need to enter the directory that stores the Java program that you
have typed in Step 1. Use the command cd to enter the correct directory as
shown in the following:
(In this example, the Java file is saved in the C:\jdk1.6.0_24/bin directory. You
may have a different directory name. Check your correct jdk directory from
Windows Explorer).
Step 3
Compile the Java program using the instruction javac Hello.java in the DOS
environment. The example is shown as follows:
Step 4
Go back to Notepad and open the file that you have typed in Step 1; however,
do not close the DOS window. Do the necessary correction in your program.
Make sure you save your file after the corrections. Now go back to the DOS
window and repeat Step 3.
Step 5
If there is no error, the compiler will generate the bytecode file ă that is
Hello.class. Now you are ready to execute your program. In order to do this,
type the command java Hello in the eDOS Window as shown in the
following:
Take note that this instruction consists of two parts. The first part (java)
refers to the Java runtime interpreter. The second part (Hello) refers to the
class name which has the main() method that is to be executed by the
interpreter.
The program generates the output given as follows. It displays the string sent
as a parameter to the System.out.println() method ă the first statement
in the main() method.
In addition, the types of Java programs have also been discussed in this topic.
It is important for the learners to understand the types of Java programs and
be able to compile and execute those programs.
INTRODUCTION
What is a computer program? A program is a sequence of instructions that a
computer can execute to perform some tasks. There are two basic blocks of
programming: data and instructions. To work with data, you need to understand
variables and data types; to work with instructions, you need to understand
control structures and subroutines (methods). This topic will focus on how
variables and data types and its related concepts can be implemented in Java.
5.1.1 Integer
The integer type of data is used for numbers that do not have decimals. The
negative values are also allowed. Java prepares four types of integer data,
namely int, short, long and byte. The storage size and the value range for
each of these data types are shown in Table 5.1.
Storage
Type Minimum Value Maximum Value
Capacity
In many cases, the int type data is the most practical. If the integer value used is
too large, for example, in representing the income of PETRONAS, then the most
appropriate data is long. The byte and short data type are for the use of
specific application such as keeping files at a lower level or a larger array if the
storage space is insufficient.
In the Java language, the range for the integer data type does not depend on the
machine where the Java code is executed. Unlike Java, in C or C++ language, the
int data type is different according to the machine. For the 16 bytes processor
such as the 8086, the int cell size is 2 bytes while for the 32 bytes processor such
as the Sun SPARC, the cell size is 4 bytes. For the Intel Pentium processor, the
integer data type depends on the operation system: for DOS and Windows 3.1,
the integer cell size is 2 bytes and when using the 32 bytes processor on Windows
95 or Windows NT, the cell size is 4 bytes.
As the range for all types of Java data is fixed, the Java program will produce the
same results if run on any machine. This makes it easier for the programmers
who wish to transfer their codes from one machine to another or between the
operational systems on the same platform.
The long type of numerical integer has the L suffix (for example, 2412345600L).
The hexadecimal numbers have the initial 0x (for example, 0xA9B9). Take note
that Java does not have the type of data with unsigned descriptor as in C.
5.1.2 Real
The real data type or floating point represents numbers that have the decimal
parts. There are two types of real data types, which are float and double. The
storage size and value range for each of these data are shown in Table 5.2.
Storage
Type Minimum Value Maximum Value
Capacity
float 32 bit 3.40282347E+38F 1.40239846E-45F
double 64 bit 1.797693134862+31570E+308 4.9406545645841246544E-324
The name double is used because the number from this type has two times the
precision of the float type numbers. Sometimes it is called the variable with
double precision. In many applications, the double type is picked to represent
real numbers. This is because the float data type can only represent seven
meaningful digits (decimals). The precision of limited float data is insufficient
in most cases. One of the reasons for using it is when there is a need for quick
processing or when the real number count that needs to be stored is large.
The real number from the float type has the F suffix, for example 75.43F. The
floating point number without the suffix F such as 75.43 would be considered
double. This is because the double data type is the default data that represents
real numbers in Java. This is different from C language that uses the float as its
default data type.
We could also add the D suffix to represent the double type numbers. All the
floating point data types follow the IEEE 754 specifications. An overflow occurs
when the range error takes place and an underflow when the zero division
operation takes place.
5.1.3 Characters
The character data type is represented by char. The single open inverted sign (Â)
is used to show character constant.
The char data type follows the Unicode coding scheme. Unicode was created to
facilitate the programmer to deal with non-Roman characters. As the Unicode
was invented to handle all characters existent in all the written languages in the
world, the cell size is 2 bytes. This size allows character representation of up to 65
536 compared to the ASCII/ANSI code, which is the 1 byte code and only allows
a 255 character representation. Until recently, only 35 000 character codes were
used.
Java has also allowed us to use the escape sequence for special characters as
shown in Table 5.3.
Although Java allows any Unicode character in the applet or Java applications,
the question of whether that character can be displayed on the applet or console
depends on the support provided. For example, we cannot display the Kanji
character (a type of Japanese writing) on the machine that operates using the
Windows 95 of the US version.
/*
Java char Example
This Java Example shows how to declare and use Java
primitive char variable inside a java class.
*/
/*
* char is 16 bit type and used to represent Unicode
characters.
* Range of char is 0 to 65,536.
*
* Declare char variable as below
*
* char <variable name> = <default value>;
*
* here assigning default value is optional.
* /
/*
Output would be
Value of char variable ch1 is :a
ACTIVITY 5.1
5.1.4 Boolean
Boolean types have two values: true and false. These literals are typed without
quotes, but they represent values, not variables. Boolean-valued expressions are
used extensively in control structures and to test the mantic expressions. Boolean
values can also be assigned to variables of type Boolean.
Boolean data type does not exist in C language. However, the non-zero value is
used to represent true and zero for false. In C++, a data type called bool is used.
It, too, can take either the true or false value. As C++ has a history that relates
closely to C, therefore the exchange between the Boolean value and integer is
allowed. This means that the integer value can still be used to test a signal. But in
Java, the exchange of the Boolean value and integer is not allowed, even though
the casting operation is used. The following is an example of the use of the
Boolean data type to represent the status of a room.
class test1 {
public static void main (String args[]){
Boolean dark;
dark = true;
while (dark) {
System.out.println(“Switch on lights”);
dark = false;
}//while
}//main
}//class
Therefore, the statement for the while loop body would be executed, that is,
output „switch on lights‰ would be printed on the display. Then, the dark
variable is assigned the false value. Logically, after the lights are switched on,
the room would no longer be dark. Thus, it is appropriate if the dark variable
value be given false value. The accomplishment of the program would exit
from the loop because the loop requisite is no longer valid.
At the end of this section, you should be able to list the types of data that could
be used in developing a Java program and differentiate the four data types that
have been discussed. In the subsequent subtopic, we will learn how to name and
declare a variable with the appropriate data type.
ACTIVITY 5.2
You wish to develop a program to evaluate students based on the
marks obtained. What is the type of data involved in the development
of the said program?
EXERCISE 5.1
(e) 51;
(f) ă31444843;
Figure 5.1: Memory location showing the name and value of variable age
Figure 5.2: Memory location showing the name and value of variables age and name
A variable in Java is designed to hold only one particular type of data; it can
legally hold that type of data and no other. The compiler will consider it to be a
syntax error if you try to violate this rule. In the previous subtopic, you have
learned data types that could be used in a Java program. This subtopic will
describe how to name variables to be used according to the Java specification.
Remember: Declaring a variable will involve data type and the variable name.
You must focus on the content of this subtopic because when you fail to declare
the right variable, it will cause the Java program that has been developed to be
uncompilable and not able to be excuted if a variable is not properly declared.
(b) The name of the variable must consist of letters and digits; and
(c) The name of the variable cannot use JavaÊs reserved word.
The definition of letter and digit in Java encompasses a wider meaning than other
programming languages. The letter is defined as characters „A‰ ă „Z‰, „a‰ ă „z‰,
„_‰, „$‰ or any Unicode characters that symbolises a letter in a particular
language. For example, French users can use the character “Ç” in a name
variable; while Greeks can use the “µ” character. The same goes for digits. Digits
are from „0‰ ă „9‰ and any Unicode characters that symbolises a digit in a
particular language. Symbols such as „+‰ or „©‰ and also empty spaces cannot
be used in the name of a variable.
Java is sensitive towards cases. This means the capital letters and the small letters
are considered different characters. There is no limit to the length of the name of
a variable. The reserved words for Java cannot be used as the name of the
variable.
There is also a style in naming the variable, especially if that name consists of
several words. The rule discussed before does not allow empty space characters
to be used to separate words. The most popular among the programming
community is by starting the first word with a small letter and the capital letter to
start each of the next words. The character „_‰ is not selected even though it does
not break the above rules. The following is an example of the name of a variable.
student_name,total_marks,price_perunit
ACTIVITY 5.3
You intend to develop a program on workersÊ salary systems. Try to list
down the variables that represent the information that is going to be
used.
data_type name_variable;
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
class test4 {
public static void main (String args[]){
}//main
}//class
5.2.3 Constant
The variable whose value is always constant, which means it does not change,
is known as constant. The reserved word final is used in this constant
declaration as in the following format:
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.
class test5 {
public static void main (String args[]){
public static final double Pl = 3.14159;
public static final int COUNT = 10;
}//main
}//class
class test6 {
public static void main (String args[]){
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.
class test7 {
public static void main (String args[]){
System.out.println(“Welcome”); //one line comment
}//main
}//class
After reading through this subtopic, you should be able to declare a variable with
the appropriate data type. You should also enable to differentiate the three types
of comments and how to use them.
ACTIVITY 5.4
You know the type of comments that can be used logically. Do you
know the importance of comments in a program?
EXERCISE 5.2
State whether the following variables are valid or otherwise. For the
variables that are invalid, please state the reasons:
(a) nameLength;
(b) Name_length;
(c) Import;
(d) 43650BBB;
(e) BBB43650;
(f) touch&go;
(g) touch-and-go;
(h) 2nd;
(j) OUM.
Answer the following questions to test your knowledge on what you have
learned in this topic.
variable = expression;
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;
class test9 {
public static void main (String args[]){
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[]){
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.
(a) If one is of the double type operant, the other operant would be changed
to double.
(b) On the other hand, if one of it is a float type operant, the other operant
would be changed to float.
(c) Also, if one of it is a long type operant, the other operant would be
changed to long.
The same principle applies to integer types: int, short and byte.
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:
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 testing whether the intended value to be changed
is within the target type range before change can be made.
Java allows the change in value of a particular variable from one type to another
without the casting operation following this sequence:
and
char int
A value of a type that occurs earlier in this list can be converted automatically to
a value that occurs later. For example, according to Eck (2006):
int A;
double X;
short B;
A = 17;
X = A; // Acceptable; A is converted to a double
B = A; // illegal; no automatic conversion
// from int to short
In some cases, you might want to force a conversion that would not be done
automatically. For this, you can use casting. For example, according to Eck (2006):
int A;
short B;
A = 17;
B = (short)A; // Acceptable; A is explicitly type cast
// to a value of type short
You can do casting from any numeric type to any other numeric type. However,
you should note that you might change the numeric value of a number by type-
casting it. You can also type-cast between the type char and the numeric types.
The numeric value of a char is its Unicode code number. For example, (char)97
is „a‰, and (int)‘+’ is 43 (Eck, 2006).
SELF-CHECK 5.1
EXERCISE 5.3
The following Java program has a few mistakes. Rewrite the program
by correcting the mistakes.
class Error {
public static void main (String[ ] args){
width = 15
area = length * width;
System.out.println(“Area is “ + area);
}
}
After knowing how to give initial value to variables and performing binary
operations to numerics with different data types without data lost, you will learn
in detail about operators and the operatorÊs operation that involves numeric
values in the next subtopic.
5.4 OPERATOR
In developing a program, we will use mathematical operations to do the
calculation. In this topic, students will be exposed to the arithmetic operations,
assignment, increment and decrement that could be used in a Java program.
5.4.1 Arithmetic
Table 5.5 below shows the operator and operation that is used in Java. The
operation for this operator is the same as in C language.
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.
Operation Result
5/2 2
5.0 / 2 2.5
5.0 / 2.0 2.5
5 / 2.0 2.5
5%2 1
This operation will change the value of the variable. Therefore, it cannot be done
on a constant, for example 7++. See several examples as follows:
class test11 {
public static void main (String args[]){
int i = 1;
int j = 1;
int x = 7–++i;//the value of x is 5, and i becomes 2
int y = 7–j++;//the value of y is 6, and j becomes 2
}//main
}//class
Note that the values of x and y are different even though the original value of i
and j are the same. This is because in the third statement, the value of i is added
by 1 first before subtracting from 7 while in the last statement, the original value
of j is subtracted from 7 and then only added by 1. The use of the addition and
reduction operator in the statement can cause confusion which is difficult to
trace. Therefore, the use of this operator is not encouraged in statements such as
the examples shown previously. However, it can be used in the following cases:
int n = 0;
n++; // alternative to n = n + 1;
These operators can be used to compare values of any of the numeric types. They
can also be used to compare values of type char.
Boolean expressions are used intensively in loop and branch statements. But you
can also assign Boolean-valued expressions to Boolean variables, just as you can
assign numeric values to numeric variables.
By the way, the operators == and != can be used to compare Boolean values.
This is occasionally useful. For example, can you figure out what the following
program does?
class test12 {
public static void main (String args[]){
int age=30, height=40;
Boolean status;
status = ((age > 20) == (height > 55));
}//main
}//class
Relational operators <, >, <=, and <= are not used to compare values of type
string.
Please remember that Java uses different symbols for assignments and
equivalence tests. Assignments use symbol „=‰ while equivalence tests use the
symbol „==‰. For example, the value
(9 = = 6)
is false. Java avoids the possibility of the occurrence of errors arising from the use
of the symbol „=‰ at places where the symbol „==‰ is used.
If you use several operators in one expression, and if you do not use parentheses
to explicitly indicate the order of evaluation, then you have to worry about the
precedence rules that determine the order of evaluation.
Table 5.10 shows the priority level of the numeric operator including relations.
Operators on the same line have the same precedence. When they occur together,
unary operators and assignment operators are evaluated right-to-left, and the
remaining operators are evaluated left-to-right.
For example, A*B/C means (A*B)/C, while A = B = C means A = (B = C). Let us look
at the following examples:
2+4/2
2 + 2 = 4
(Note: 4/2 will be evaluated first as the operator/has higher priority than
operator +)
(2 + 4) / 2
6 /2 = 3
(Note: Those operands and operators in the parentheses will be evaluated first as
parentheses have the highest priority. Thus 2 + 4 in the parentheses will be
evaluated first and the result will be divided with 2).
Can you evaluate the expression 2 + (4/2) ă 4/2 ă (6 ă 2/2)? The answer is ă3.
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 && and II operators are evaluated using a short cut method. This means in
evaluating the following statement,
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.
test = !test;
will reverse the value of test, changing it from true to false, or from false to true.
In conclusion, you should have recognised the operators that could be suitably
used with arithmetic operations that will be used in a particular Java program.
EXERCISE 5.4
Statement Value
(a) 4 + 5.0 * 6;
(b) (4 + 5) * 6;
(c) 4 + 5 / 6;
(d) (4 + 5) / 6;
(e) 4 + 5 % 3;
(f) (4 + 5) % 3;
(g) 9 % 2 * 7 / 3; and
(h) 5.0 / 2 * 3 % 2.
2. What are the values of j and k after the following statement has
been executed? Assume that value j is 5 and value k is 7 before
the statement is accomplished.
(a) k + = j;
(b) k ă = j ++;
(c) k * = ++ j *2;
(e) k % = j ă 3.
To work with data, you need to understand variables and data types which is
the focus of this topic.
This topic has discussed the basic Java constructs that should be known by
learners to enable them to write a complete Java program which is free from
errors.
Boolean Expression
Boolean operator Relational operator
Data types Variable
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.
These three structures are capable of changing the flow of control in a program,
can be implemented in the Java language. The following subtopics will touch on
this.
(c) Multi-selection.
What is Algorithm?
Algorithm is a step-by-step problem-solving procedure written in natural
language such as English.
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 not
Print “Compulsory retirement”
Let us look at Figure 6.1 which shows the selection structures in bi-selection.
else
System.out.println(“Compulsory retirement”);
if(expression)
statement 1;
else
statement 2;
Generally, the syntax in the following Figure 6.2 represents the if-else
statement.
In the case of single selection, if the expression has false value, no action
will be taken. This is different with the case of bi-selection, where we are
given another alternative, that is, if the expression has false value,
statement 2 will be accomplished. With reference to the example before, if
the age is or more than 55, the words “compulsory retirement” will be
printed.
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
System.out.println (“Others”)
For example, say raceCode is valued ‘I’. With this value, the expression
raceCode ==’M’ will have false value, therefore the program control will
abandon the statement System.out.println (“Malay”); and tests the
next expression, that is raceCode == ‘C’. This statement also has a false
value and the action that matches it, that is, System.out.println
(“Chinese”); is abandoned. The next expression is tested and found that
the value to be true, then the expression System.out.println(“Indian”);
will be accomplished and the “Indian” string will be printed as shown in
Figure 6.3.
Java also supports the use of the ? operator, which is sometimes very useful. The
expression
On the other hand, if the requisite value is false, the expression will accomplish
statement2 value.
Example 6.1:
else
System.out.println(“Input error”);
EXERCISE 6.1
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.
Figure 6.4: Selection structure in multi selection using switch and break
The following example shows the use of switch statement from the previous
example of if-else if structure:
switch (raceCode){
case ‘M’: System.out.println (“Malay”); break;
case ‘C’: System.out.println (“Chinese”); break;
case‘I’ : System.out.printn (“Indian”); break;
default : System.out.println (“Others”);
}
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.
while (expression) {
block_statement
}
The while loop will not be accomplished at all if the expression value is false
the first time it is tested. Notice the following example to find the addition integer
from 1 to 100.
The while loop in the example before will stop when the value i exceeds 100.
When the i value exceeds 100, the requisite (expression) will become false.
For the repetitive structure while, there are four basic components that need to be
fulfilled.
In contrast, the do-while loop is a variation of the while loop. Its syntax is as
follows:
do {
Statement1
Statement2
……
……
StatementN
} while (condition);
For the do-while loop, the loop body will be executed first, then the condition
is evaluated. If the condition is true, the loop body will be executed. Otherwise
the loop will be terminated. The difference between while loop and do-while
loop is the order in which the condition is evaluated and the loop body
executed.
for(initial_value;stop_condition;updated_statement){
block_statement
}
Unlike while and do-while statements, for loop is used for the number of loop
repetitions that are already known in advance.
We can give initial value to several variables that usually act as the calculator in
the first slot. Unlike C, Java allows int type variable to be declared and given its
initial value at this slot. However, it is only valid in the body or for loop block
where it is declared.
The second slot requisite is used to test the requisite that determines whether the
body of a for loop will be accomplished or not. The third slot explains updates
that describe how to update to change the initial_value (counter).
block_statement can consist of only one simple statement or a block. Therefore,
nested loop is also allowed.
HI
HI
HI
HI
HI
The following examples show the comparison of three loop statements (while, do
while, for). The programs are to print number from 0 to 100.
break;
In this program, the program will exit the loop when the value of line becomes
3 even though the requisite for the loop line <=5. The result that will be
displayed is:
HI
HI
HI
break and continue can be used in while loops and do-while loops. They can
also be used in for loops and switch statements. Note that when a break occurs
inside an if statement, it breaks out of the loop or switch statement that contains
the if statement. If the if statement is not contained inside a loop or switch,
then the if statement cannot legally contain a break statement. A similar
consideration applies to continue statements.
*
**
***
****
*****
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?
Example 6.2:
1 int x=2;
2 if (x==2)
3 System.out.println(“Hi”);
4 System.out.println(“Hello”);
5 System.out.println(“Bye”);
Example 6.3:
1 int x=2;
2 if (x==3)
3 {
4 System.out.println(“Hi”);
5 System.out.println(“Hello”);
6 }
7 System.out.println(“Bye”);
Hi
Hello
Bye
Bye
Do you know why there is a difference between the output for the Example 6.2
and Example 6.3?
In Example 6.2, there are no braces { } for the if statement in Line 2. Thus, only
one statement that follows the if statement (that is Line 3) is subjected to the
condition of Line 2 (that is if Line 2 returns a true Boolean value then Line 3 will
be executed whereas Line 3 will not be executed if Line 2 returns a false value).
Line 4 and 5 will be executed irrespective of whether Line 2 returns a true or false
value.
In Example 6.3, there are braces { } for the if statement in Line 3 and Line 6. All
the statements inside the braces (Line 4ăLine 5) are subjected to the condition of
Line 2 (that is, Line 4ăLine 5 will be executed if Line 2 returns a true value whereas
Line 4ăLine 5 will not be executed if Line 2 returns a false value). Line 7 will be
executed irrespective of whether Line 2 returns a true or false value because it is
not inside the braces.
Example 6.4:
int x=2;
int y=3;
if (x==2)
{
if (y==1)
System.out.println(“Hi”);
System.out.println(“Hello”);
}
System.out.println(“Bye”);
Example 6.5:
Hi
Hello
Hi
Hello
Hi
Hello
*********************
Hi
Hi
Hi
Hello
EXERCISE 6.2
What is the output that is displayed from the following program segment?
6.4 METHOD
Methods allow the programmer to modularise a program ă each method will
perform a single specialised task.
Query method is used to access only the objectÊs state and this operation does not
change the state of an object. Examples of this method are:
(a) getName();
(b) getPay();
(d) checkPassword().
(b) updateAge().
Finally, task methods are used to perform some specific task. This method may
change the state of the object. Examples of this method are:
(b) convertToCelcius()
Line 3ă5 is the declaration of a method. A Java method is a set of Java statements
which can be included inside a Java program. Java methods are similar to functions
or procedures in other programming languages. Methods in Java could be divided
into two, namely:
Example 6.6:
int max;
if (no1>no2)
max= no1;
else Method body
max= no2;
return max;
}
Return value
<modifier access> could be private, public or protected. The public access modifier
indicates that the method can be called from other program. The private indicates
that a method can be called only by the other methods from the same class. If we
do not declare any access modifier for a method, then the system will assume that
the method is public.
The <return_type> indicates the type of value returned by the method. If the
method does not return any value, then it should be declared as void as shown in
the following:
If the method returns a value such an int value, then the method should be
declared as int as shown in the following example:
If the method returns a string value, then the method should be declared as
String as shown in the following example:
The same goes for other methods that return other data types such as float, double,
char and Boolean. Use return statement within the method to pass back value if
the method returns a value as shown in the next example:
Note that the return statement should not be included within the method if it is
a void method.
Example 6.6:
Example 6.7:
/* Note that this program does not have return statement within the
method as it is a void method. */
public void calculateAverage(int no1, int no2) {
int average = no1/no2;
}
Example 6.8:
Example 6.9:
Arguments
If a method does not return any value (that is, it is a void method), then the method
must be a statement. For example:
calculateAge();
If a method has a parameter, then you need to include the arguments during the
method invocation. The arguments must match the parameters in order, number
and be compatible as defined in the method signature.
The following Example 6.10 shows a complete program which has method
declaration and method invocation:
Example 6.10:
class obj {
public static void main (String[ ] args ){
int a=67;
pass the
int b=80; value
int max=getMax(a,b);
System.out.println(“Maximum is “ + max);
}
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.
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);
}
Line 5 of the program will invoke the first method that will determine the
maximum value between two integer numbers. Line 6 will invoke the second
method that will determine the maximum value between two float numbers.
As you can see in the previous program, two methods with the same name have
been declared. This approach of declaring more than one method with the same
name but with different parameter list is known as method overloading. You
cannot overload methods based on different modifiers or return types.
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.
Bohm and Jacopini conducted research in the 1960s and concluded that all
programs can be written in a structured way by only using three control
structures, namely: sequential structure, selection structure and repetitive
structure.
Sequential structure in Java could be implemented using if, if-else, if-else if and
switch statements.
break method
case nested loops
continue Repetitive structure
do-while Selection structure
for Sequential structure
if switch
if-else while
INTRODUCTION
To recap, a program is a sequence of instructions that a computer can execute
to perform some tasks. There are two basic blocks of programming: data and
instructions. To work with data, you need to understand variables and data
types; to work with instructions, you need to understand control structures and
methods. All these have been elaborated in Topic 5 and Topic 6.
Like other programming languages, there are also three other important
constructs in Java listed as follows:
(a) Array;
7.1 ARRAY
Array is a group of memory locations that are connected and have the same
name and data type.
„You have been required to write a program that will accept and store the
marks for five students‰.
For the above problem, you are just required to declare five variable types of
integers as shown below to store the studentsÊ marks:
„You have been required to write a program that will accept and store the
marks for 500 students‰.
For the above problem, are you going to declare 500 variables shown as follows:
It is very obvious that the above approach to write 500 variables is „tiring‰
and is not a good approach. The solution is to use array:
We need to state the name of the array and the location in order to refer to a
particular memory location in the array. Figure 7.1 shows a visual representation
of an array.
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.
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.
The definition and creation of the array object can also be done separately as
follows:
Observe how the initial value can be provided during array declaration:
Number[0] 3
Number[1] 5
Number[2] 4
Number[3] 0
letter[0] A
letter[1] B
Letter[2] Z
letter[3] E
Notice that in the two examples before, the new operator is not used. We can also
give an initial value to an array that has no name definition shown as follows:
This statement will allocate a new array and add the value in parenthesis { }. The
sum of initial value will be calculated and the array size is determined according
to that sum. This type of syntax is used if we wish to send an array as a
parameter to a particular method without creating a localised variable for it. For
example:
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;
array_name.length
length is an attribute for the array that stores information on the size of
the array. For example:
The following is an example of the program segment that shows how three out of
five values are copied from the evenNum array to the newNum array.
int[]evenNum = 2, 4, 6, 8, 10};
int[]evenNum = {1000, 2000, 3000, 4000, 5000, 6000};
System.arraycopy(evenNum, 1, newNum, 2, 3);
for (i = 0; i < newNum.length; i++){
System.out.println(“newNum[“+i+”]after
copying: “+newNum[i]);
}
The effect obtained is both arrays refer to a set of the same data. Changes in
one of the arrays will affect both arrays. The following visual will help you to
understand this explanation:
SELF-CHECK 7.1
You have already learned about arrays. Can you state the difference
between an array and a string?
EXERCISE 7.1
2. Assume that the declaration below was made and state whether it
is valid or otherwise. Give the reasons.
int j[ ] = new int [10];
char k [] = new char[6];
int x = 7, y = 2;
double m = 0.0;
(a) j[0]
(b) k[0]
(c) c[1.0]
(d) k[‘j’]
(e) k[j]
(f) j[x + y]
(g) j[x % y]
(h) j[10]
(i) c[-1]
(j) j[j[4]]
EXERCISE 7.1
3. The following program will create an array and then values will
be assigned to this array. These values will be displayed. Observe
the usage of the for command in the program. In your opinion,
what will be the output? Compare your answer with the
computerÊs output.
arraycopy class {
public static void main (String[ ] args){
7.2 STRING
The character string, which is a combination of individual characters, is
implemented as a string class. We no longer need to declare a variable that
stores character string values as char type array. String constant consists of
character strings that are in between two inverted signs „ ‰. This includes the
empty space character that separates the words. Words, digits and special
characters such as +, ă, *, /, $, etc. could be assigned to string variables in Java.
In the previous example, the use of the „+‰ operator will produce myName
character string with the value “FirdausMohd”. Note that there is no
empty space in this string. The „+‰ operator only acts to combine two
strings according to the sequence that is stated.
(b) Substring
To obtain only part of the complete string, we use the substring()
method. This method is a library method available in String class. For
example, let us look at the following program segment:
The call for substring() method in the previous example pass two
parameters, that is 0 and 10. The second parameter is the first position in
the IPTS string that we do not intend to copy. In this case, what we intend
to accomplish is to copy the character from position 0 to 9. Therefore, the
substring() method will calculate from position 0 (included) to position
10 (excluded).
Note here that length()is a method. This is different from the length
attribute that represents array size.
s.equals(r)
returns the true value if s and r strings are the same and false if
otherwise. s and r can be either constant or a string variable.
“Greetings”.equals(IPTS)
Never use the „==‰ operator to compare two strings. This operation will
only check whether both strings are stored in the same location. Definitely
the string stored at the same location will have the same value. But we can
also store many strings that have the same value at different locations.
ACTIVITY 7.1
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)?
For example, the following code shows how to read an integer from the
keyboard:
For each of the primitive types there is a corresponding nextXxx() method that
returns a value of that type. Example of nextXxx() methods that you can use to
capture inputs are shown in Table 7.1.
Methods Purpose
nextInt() To capture integer data type
nextFloat() To capture float data type
nextDouble() To capture double data type
next() Reads a string that ends before a white space
nextLine() Reads a line of character
The following program demonstrates how to read int and float values from
the keyboard.
import java.util.*;
} // main
} // class UsingScanner
EXERCISE 7.3
Write a Java program that will accept three integer numbers from a user
and display the maximum number among these three inputs.
We can use the command from the library class DecimalFormat to format the
numbers.
As an example, the statement as follows will display the first three digits after the
decimal point:
The following statement will display three digits of a number as an output. If the
number is less than three digits, then 0 will be appended at the front. If the digits
of a number are greater than three, then all the digits in the number will be
displayed.
class uji{
Now, replace the following statements to the statements that have been bolded in
the previous program.
Can you see any difference in the output upon executing the program?
This topic focuses on array, string and how to capture input from the user
during program runtime.
An array is a group of memory locations that are connected and have the
same name and data type.
An interesting thing in writing the Java program is that the reading input
process from the keyboard is not as simple as expected.
Array String
Scanner class
Answers
Suggested Answers to Exercises for Topic 2
Exercise 2.1
(a) functional
(b) non-functional
(c) functional
(d) non-functional
Exercise 2.2
Functional requirements:
register members
Non-functional requirements:
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 and includes
joining, borrowing videos and asking questions.
Back office clerk primary This actor deals with all the back office functions
such as sending data to the general ledger system. (You might find out later that
this „actor‰ is actually several actors.)
Management secondary, as their reporting needs are met from the data
warehouse. Sufficient information is needed to run the business.
Security manager primary maintains the user names to control access to the
system.
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.
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.)
The back office clerk performs this use case approximately once a week. The
system displays the range of birthday dates that was last produced. The clerk
then selects another date range, usually another week. The system produces the
letters. The clerk puts the letters in envelopes and posts them.
Exercise 2.8
Alternate flows in borrow videos
The memberÊs number might be invalid. Ask clerk to re-enter the number.
Member might have overdue videos. They are not allowed to borrow any
more videos, so end the use case.
Member might have fines to pay for videos that were returned late. They
must pay the fines as well as the fees for the new videos.
Exercise 2.9
Borrow videos
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?
Tell me about stocktakes. What are the issues? What are you trying to
achieve?
Have you thought about transferring the data from the old system to the new
system?
Exercise 2.11
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.
Later in the unit we will show you a way to deal with large systems with
hundreds of use cases.
Exercise 2.12
Exercise 2.14
Perhaps you can already envisage the answer, but let us work through it slowly.
We need a use case to sell old videos. So here is our first version:
What do you notice about the last line? It is the same as the last line of the
Borrow Videos use case.
Level: Subfunction
Actor Intention System Responsibility
Get payment Pass the total amount due to the cash register
terminal
Then, updating the other two use cases gives us the following:
Borrow Videos
Exercise 2.15a
Maintain Members
Extension point: At any point once the memberÊs details are displayed
Actor Intention System Responsibility
Get Borrower Display personal details (name, address, date
of birth, date joined, etc.), plus a summary of
current borrowings (for example, total number
borrowed, total number of overdues, current
number borrowed and current number
overdues)
Optionally, the user can Store the changes
modify the personal details
of the member
Optionally, the user can Check that the borrower has nothing borrowed
delete the member Delete the member
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
Exercise 2.15b
Business Rule Use Cases
Only members can borrow videos. Borrow Videos
When a new person requests to become a Handled by the clerk, not the
member, they must show ID. system
The minimum age is 16 years old. Handled by the clerk, not the
system
A member can borrow any number of Should be in Borrow Videos
videos, as long as they have no overdue
videos.
There are fines for overdue videos. Borrow Videos
Also look at Return Videos
The length of time that a video can be The Borrow Videos use case needs
borrowed for depends on the video. New to handle this
releases are only lent out overnight,
current releases are for three-day hire,
and the rest are for a week.
Members can reserve a video. Reserve Videos
Every video has a classification, (general The Classification and Category
G, parental guidance PG, mature are attributes of the Video
audiences MA and restricted R). Specification, so these are
Members must be over 18 to borrow R maintained by the use case
videos. Every video also has a category: Maintain Video Title, identified in
Romance, General, Sci-Fi, Foreign Exercise 4.5.
Language and Children.
When a member has a birthday, he is sent Generate Birthday Letters
a special letter inviting him to borrow any
video of his choice for a week for free.
Every three months the shop does a Do stocktake. Users have to
stocktake. remember to do it.
Any missing videos are updated to be Record Video Tape Missing. This
shown as missing. is the use case that we identified
in Exercise 4.4
Exercise 2.17
Conceptual Class Category Example
Physical or tangible objects Video CD
Specifications, designs or descriptions Video title
of things
Places Video shop
Front desk
Transactions Borrow a video
Return a video
Transaction line items Video CD
Roles of people Member
Front desk clerk,
Back room clerk,
Accountant
ă all the roles you identified would
go here
Abstract noun concepts Boring
Exciting
Organizations Companies that make videotapes
Banks
Events A new video is released
Processes Borrow a video
Return a video
Do a stocktake
ă many use cases fit here
Rules and policies Borrowing policy
Joining policy
Overdue policy
Catalog Video catalog
Manuals, documents, reference, paper, Member records
books New releases
New employee training
Exercise 2.18
Exercise 2.19
Exercise 2.20
The other entity for which a state diagram could be useful is the class Member.
The problem discussed did not mention that if a member has too many overdues,
then he is not allowed to borrow, but this is the sort of fact that should be verified
with individual users if a state diagram is used.
As we stated, it is not wrong to draw state diagrams for other classes, it is simply
that they will be very simple and you will not learn from them. But, of course,
the best way to find this out is to draw them.
Exercise 3.2
The first version for the state diagram for Video Tape might look like this:
Then you could think about how a video tape comes into existence. Clearly we
are missing a use case here ă let us call it Get New Video Tapes.
What about the final state? An initial answer could be to create another new use
case, this time called Retire Video Tapes. Clearly we have uncovered new
functionality and would need to go back to the users to discuss this. For example,
perhaps they try to sell some old video tapes.
Lastly, let us think about lost or missing video tapes. Once again, we would need
to discuss this with Victoria, and the answer could be the following:
Exercise 3.3
Thirsty drinker: (to the BarBot) Can I have a glass of beer?
GlassTray: (gets glass from GlassTray and passes it back to the BarBot)
BeerTap: (dispenses 285ml of beer into glass, and returns the filled
Glass to the BarBot)
Exercise 3.4
Exercise 3.5
Exercise 3.6
(b) long
(c) float
(d) float
Exercise 5.2
(a) valid
(b) valid
(e) valid
(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
(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
Exercise 6.2
(a) 0
6
12
18
24
30
36
(b) 1
8
15
22
29
36
43
Exercise 7.1
1. (a) intA is declared as integer array but was assigned with double array.
(c) doubleA is declared as double but was assigned with double array.
Also, the size of the array cannot be negative.
2. (a) valid
(b) valid
(d) valid
(f) valid
(g) valid
3. Output:
0
2
4
6
8
10
12
14
16
18
Exercise 7.2
1. (a) 32
(b) e
2. Output:
s1: hello there
Length of s1: 11
The string reversed is: e r e h t o l l e h
The character array is: hello
Exercise 7.3
import java.util.*;
class GetMaxValue
{
public static void main( String args[ ] )
{
int temp, max;
Scanner scanner = new Scanner(System.in);
if (no1>no2)
temp=no1;
else
temp=no2;
if (temp>no3)
max=temp;
else
max=no3;
OR
Thank you.