Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
INTRODUCTION
TO OBJECT-ORIENTED
APPROACH
Karin Kolbe
Dr Geoffrey Phipps
Assoc Prof Dr Nantha Kumar Subramaniam
Marini Abu Bakar
Dr Sufian Indris
Norleyza Jailani
Roziah Latih
Table of Contents
Course Guide ix ă xviii
2.7.7 Attributes 70
Summary 73
Key Terms 74
INTRODUCTION
CDOP3103 Introduction to Object-Oriented Approach is one of the courses
offered by Faculty of Science and Technology, Open University Malaysia (OUM).
COURSE AUDIENCE
This course is offered to all students taking the Diploma in Information
Technology (DIT). This module aims to introduce the concepts of object
orientation, systems modelling using UML and basic Java programming.
As an open and distance learner, you should be able to learn independently and
optimise the learning modes and environment available to you. Before you begin
this course, please confirm the course material, the course requirements and how
the course is conducted.
STUDY SCHEDULE
It is a standard OUM practice that learners accumulate 40 study hours for every
credit hour. As such, for a three-credit hour course, you are expected to spend
120 study hours. Table 1 gives an estimation of how the 120 study hours could be
accumulated.
Reading 8 topics 60
Online discussions 12
Completing assignment 15
Revision 18
LEARNING OUTCOMES
By the end of this course, learners should be able to:
1. Explain the fundamental concepts of object orientation;
2. Describe how systems modelling can be done using UML in order to
develop object oriented systems;
3. Write UMLÊs use case, draw use case diagram, activity diagram, analysis,
sequence diagram, collaboration diagram and state diagram for a given
problem; and
4. Write Java programs in a structured manner.
COURSE SYNOPSIS
This course is divided into 7 topics. The synopsis for each topic is presented
below:
Process the marks of 100 students and determine the highest and
lowest marks.
Determine number of characters in a String.
Enable an user to key in data during program run-time.
These constructs are listed below and will be discussed in this Topic:
Array
String
Input Reading
ADDITIONAL READING
There will be a number of additional „short‰ readings for certain topics as shown
in the table below. These readings are provided as part of your course package in
myLMS.
Topic Reading
Topic 1 -
Topic 2 Reading 2.1 – Reading 2.4
Topic 3 Reading 3.1 – Reading 3.2
Topic 4 -
Topic 5 -
Topic 6 -
Topic 7 -
It is compulsory for the students to read these readings as it will give them a
solid understanding of the particular concepts related to the course. These
readings is part of the syllabus. Hence, it can be tested for the tests and final
examination.
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 pre-requisile knowledge is required to take this course
ASSESSMENT METHOD
Refer to myVLE for information on assessment method for this subject.
COURSE ASSESSMENT
Refer to the latest announcement in myVLE.
ONLINE DISCUSSION
Online discussion with your tutors and fellow students is one of the important
components of teaching and learning activities at OUM. To help you to go
through your online discussion, OUM has developed a Computer-base Virtual
Learning Environment, known as MyVLE. The system have a number of
functionalities which enable the students to access OUMÊs digital library,
communicate with the tutors and their fellow students. We strongly advised you
to use this system.
Assignment
For CDOP3103 – Introduction to Object Oriented Approach, you are required to
do one assignment. The objective of the assignment is:
1. To provide a mechanism for you to check your progress and make sure that
you have met certain learning objective
Assignment Schedule
Assignment will be posted to MyLMS before Tutorial 1.
Student are required to submit the assignment together with during Tutorial 4
Student will get their assignment marks from their tutors during Tutorial 5.
Please make sure to ask for the marks during this Tutorial 5. The tutor will post
his/her feedback of your assignment answer online via myLMS.
Tutorials
The course includes 5 tutorial meetings of two hours each · 10 contact hours in
total. The tutorials are conducted to provide an opportunity for you to meet your
tutors and discussed important points in the module. In addition, you have an
opportunity to share your study experiences and difficulties in your peer-to-peer
group discussions. Although the tutorials are not compulsory, you are
encouraged to attend the tutorial meetings as far as possible. It is strongly
recommended that you attend all tutorials, as they will provide considerable
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 the following two case studies.
You are required to read and understand the following case studies prior of
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.
members have not borrowed for years. When a new person requests to become a
member, they must show their driverÊs license or other photo ID. The minimum
age is 16 years old. A member can borrow any number of videos, as long as they
have no overdue videos, and it is also possible to reserve a video. There are fines
for overdue videos.
The length of time that a video can be borrowed depends on the video. New
releases are only lent out overnight, current releases are for three-day hire, and
the rest are for a week.
MembersÊ birthdays are marked with a special letter inviting them to borrow any
video of their choice for a week for free.
Every three months the shop does a stocktake. Any missing videos are updated
to show them as ÂMissingÊ.
The system Victoria has three very good intelligent cash register terminals to
handle all the financial transactions. These terminals handle the credit card
facilities, cash reconciliation, banking and interface with the accounting system.
However, the current computer system runs on very old hardware (Windows 95)
and is written in an obscure programming language that nobody understands. It
is a very slow and unfriendly system that requires a fair bit of training for new
staff. So Victoria has decided to invest in a completely new system with current
hardware, operating system and software. Hardware and operating system
decisions have not been made.
While sheÊs doing this, she wants to add a data warehouse so that management
can get various statistical reports. For example, they would like to see which
types of videos are most popular or unpopular, who are the best customers, how
many overdue videos there are, etc.
In addition, in the current system a barcode reader is required to scan the videos,
and members need to present their ID cards to take the video out. This causes
problems when members forget to bring their cards, so Victoria would like to
explore other options.
The following is the functional decomposition of the targeted new system for
VictoriaÊs Video:
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 many interesting requirement and design problems to solve.
This is a realistic problem as organizations really do write POS system using
object technologies. A POS system is a computerized application used (in part)
to record sales and handle payments and it is typically used in a retail store. It
includes hardware components such as computer and bar code scanner and
software to run the system. It is interfaced to various service applications such as
third party tax calculator and inventory control. These system must be relatively
fault-tolerant. A POS system increasingly must support multiple and varied
client-side terminals and interfaces. These include Web browser, a regular PC
which supports graphical user interface (GUI), touch screen input, wireless
PDAÊs, and so forth.
X INTRODUCTION
Writing a big and complex program is not an easy task. One approach used by
human beings to solve complexity problems is the divide and conquer approach.
This approach can also be used in designing computer programs. In this
approach, the main problem is decomposed or broken into smaller or sub-
problems, each of which is then solved independently.
Prepare Lunch
Figure 1.1 shows this approach for preparing lunch. The solution designed is based
on the algorithmic approach. One important thing in the algorithmic approach is
that it concentrates on the processes aspect of the program.
EXERCISE 1.1
To illustrate, letÊs take the lunch preparation problem. We will propose a solution
that is quite different from the one shown in Figure 1.1. In this solution, the tasks
involved in preparing the lunch are assigned to a group of objects (agents). Every
task must be assigned to an object. The object and the task to be performed is
determined as follows:
Figure 1.2 shows the solution based on the object-oriented approach. Notice how
the above objects use the message-sending mechanism to cooperate with each
other in preparing the lunch. First, the Waiter object receives a lunch
message from the customer. In response, the object implements the message as
follows:
EXERCISE 1.2
Use the object oriented approach to design a solution for the problem in
Exercise 1.1.
1.2.1 Objects
Object is the most important thing in the object-oriented paradigm. Objects in an
object- oriented software collaborate and work together by sending messages
to implement the behavior of the software.
What is an object? We can define an object as a thing that has state, behaviour
and identity. All these three properties will be explained in more detail shortly.
A few object examples are given as follows:
• A car with plate number JEU 875;
• The carÊs steering; and
• The carÊs front left wheel.
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 objects.
Object properties are also called object attributes. An object state is all the
object attributes plus their values. Figure 1.3 shows the current state of a
Box object. Notice that the content attribute value is a reference to another
object.
Exercise 1.3
Again, letÊs take the vending machine object. One of the messages that it
probably receives is: release the can drink selected by the buyer. This
message will be sent to the vending machine when the buyer pushes a
button on the machine. The message received causes the object to show a
behaviour, that is, the drink can selected by the buyer is released. This
behaviour actually changes the vending machine’s state since the total
number of can drinks in the machine is less one now.
Besides changing the state, an object can also send messages to other
objects in response to a received message. Figure 1.5 shows the cooperation
between audience, television and remote control objects. When
the button for channel 5 is pressed on remote control, the audience
object will send the message change channel TV(5) to the remote
control object, to change the television channel to channel 5. The
following are message sequence sent to the television when the remote
control object receives the message:
(i) Message open communication channel
This causes the television object to open a communication
channel between it and the remote control object;
(ii) Message change channel TV(5)
The television object will change to channel 5 when the message
is received; and
(iii) Message close communication channel
The communication channel that was opened just now is now closed
by the television object.
EXERCISE 1.4
other records store data about three computer users. The record that stores
the computer data has two fields, idComputer and idUser. The
idComputer field represents the key because with this every computer in
the database is assigned a unique ID value. This enables the computers in
the database to be distinguished from one another. The idUser field stores
a reference to the record that stores data on users who use the computer.
There are three fields in the record that stores the user data. The idUser
field stores the user ID value; it is the key for this record. The remaining two
fields store the login name and the user password. The idUser field value
is used to join the user record with the computer record. Figure 1.7 shows
that computer with the ID 34 is joined to the user with ID 110. That means
that computer 34 is used by the user whose login name is azra.
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).
In object orientation, the attributes for object identities such as idComputer and
idUser in Figure 1.7 and Figure 1.8 do not have to be defined. This is because
every object already has its own built-in identity which no one can change.
Hence, the problem of identity changes do not arise.
A close relationship exists between an objectÊs state and its behaviour. The
cumulative effect of an objectÊs behaviour can be represented by its current
state. For example, the total money in a can drink vending machine represents
the objectÊs cumulative behaviour towards all the buying that occurs.
Exercise 1.5
State how an object stateÊs 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 fifteen minutes, the waiter comes back
with the fried rice that you just ordered.
In this scenario, you as the restaurant customer do not need to know about the
process that happens in the kitchen to prepare the fried rice. In another words,
you donÊt need to know about how the fried rice is prepared in the restaurant.
You donÊt need to know whether the restaurant cook used his grandmotherÊs
secret fried rice recipe or whether the fried rice was bought from the sundry
shop next to the restaurant. As far as you are concerned, your order has been
fulfilled (you got your fried rice). In object orientation, we say that the restaurant
encapsulates the implementation of the fried rice and thus hides the food
preparation from the customer (that is the client).
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
object is integrated with a message list that can be understood. This message list is
called the objectÊs interface.
The object interface is a protocol that must be used to interact with other
objects. It lists all the messages received by an object. For example, consider the
Square object interface shown in Figure 1.9.
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 changes its
height to the new parameter value.
Because the object interface is general, the information encapsulated in the object
is not revealed in the interface. For example, the Square object interface in
Figure 1.9 does not state the details used by the object to calculate area and
circumference. It also does not reveal the hidden attributes to the client.
An object interface acts like a message menu for the object. A message menu
consists of a list of messages that we can send to an object. If the object is sent a
message that is not listed in its interface, no response can be expected from the
object because it doesnÊt understand the message.
Figure 1.10 shows the relationship between the object and its client and the
connection between the object interface and the encapsulated information in the
object. The figure shows the Square object receiving the message
circumference() from the client. Because the message circumference() is
listed in the interface, the object will respond when this message is received.
EXERCISE 1.7
The object that doesnÊt interact with any other object is useless in object-oriented
systems. Communication between objects is very important in object- oriented
software because the software must model the collaboration of objects. For
example, Figure 1.12 shows the communications that occur between the objects to
change a studentÊs course grade in a student information system. This task
involves three objects, which are the Database Manager object, Database
File object and Student Record object. In this example, the student record
that consists of student information is represented by Student Record. The
Database File object is linked to every Student Record object. The
Database Manager objectÊs aim is to manage all the transactions on the
Database File object. In Figure 1.12, every message (except message
changeGrade that is received by the Database Manager object) is numbered.
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 too many
objects, attributes and behaviours. An example of the system is the student
record system in a university. In this system, the student is modeled as an object.
The system development certainly cannot specify the attributes and behaviours
of every student object as there may be too many students (see Figure 1.13).
This problem can be handled by using the class concept. The entire student object
can be grouped into one category. This category enables us to define the
attributes and behaviours of every object in the category. For example, all
students have the attributes name, age, address, gender and so on. There is also
the behaviour for every student. For example, every student object will respond
when it receives a message to update its address attribute. With the class concept,
we donÊt have to define this for every object in the system individually. Instead,
we define a category for the objects and their attributes and behaviours. For
example, we can define the Student category to contain all the student objects in
the student record system. In object orientation, the object category like this is
called a class. Class is the template that enables the creation of an object. Every
Copyright © Open University Malaysia (OUM)
16 X TOPIC 1 INTRODUCTION TO OBJECT ORIENTATION
object in the Student class has the same attributes and behaviours defined in the
class (see Figure 1.14).
The object created from a class is sometimes called as member of the class. The
Student class defined in Figure 1.14 states that every member has the attributes
name, birth date, and so on. Also, it lists the messages understood by its
members, that is, changeAddress(newAddress), addCourse(newCourse)
and so on. Besides, it also describes its member behaviour when received a
message.
EXERCISE 1.8
Given as follows are several objects in Figure 1.15. Put them into suitable
classes. For every class that you have identified, state its members.
1.2.6 Inheritance
To determine the classes for an object-oriented software system, we must actually
categorise the objects involved in the system. An object category can be further
refined into subcategories.
Figure 1.16 shows the Shape class specification. Every object from this class has
the attributes colour and location. Besides, the Shape class objects can also
understand the message setColour(newColour), which is to set the colour of
the object attribute to newColour.
Figure 1.17 also shows the Shape class with two subcategories (subclasses),
which are Square and Circle. The objects in these categories are part of the
Shape category and have the Shape properties and behaviours. Therefore, the
Square and Circle objects not only have the attributes and behaviours in their
respective subcategory definition but they also have the attributes and
behaviours in the Shape category definition. For example, the Square object has
the following attributes and behaviours:
Attributes
colour (from Shape class definition)
location (from Shape class definition)
width (from Square class definition)
height (from Square class definition)
Behaviours
changeColour(newColour) (from Shape class definition)
setWidth(newWidth) (from Square class definition)
setHeight(newHeight) (from Square class definition)
The object oriented term for the object subcategory is subclass. Thus, there are
two subclasses under the Shape class - Square and Circle classes. The
relationship that exists between the Shape class and both the subclasses is called
inheritance, because every attribute and behaviour in the Shape class definition
will be included (inherited) in the subclasses definition.
Subclasses have all the characteristics and behaviour inherited from the
superclass, but have added some more characteristics and behaviours for
themselves. For example, after we have created Student class, we could also
define another class for diploma students, master students, etc in which all will
inherit the Student superclass. It would involve a lot of effort to create a brand
new class. However, it would be easier if we could take an existing class, clone it
and then make modifications to the clone to reflect the extra functionality.
Another example is employee records system. You could create a generic
employee class with states and actions that are common to all employees. Then
more specific classes could be defined for salaried, commissioned and hourly
employees. The generic class is known as the parent (or superclass or base class)
and the specific classes as children (or subclasses or derived classes). The
concept of inheritance greatly enhances the ability to reuse code as well as
making design a much simpler and cleaner process.
EXERCISE 1.9
Build two inheritance hierarchies using the classes identified in Exercise 1.8.
The static modeling which models the structural part of the system and dynamic
modeling which models the behaviour part of the system need to be performed
by the system analyst before developing a system. This is to ensure that an
effective system can be developed. The static modeling and dynamic modeling
are the subsets that make up the systems modeling which is the key aspect of
most systems development methodology.
Systems modeling for object-oriented systems makes extensive use of the Unified
Modeling Language (UML). UML was the result of the collaboration between
three methodologists: Jim Rumbaugh, Grady Booch and Ivar Jacobson. What
they published in 1994 was an amalgamation of their own notations plus the
notations of several other authors.
UML defines standardised models and notations for expressing different aspects
of an OO design. Version 1.1 was submitted to the Object Management Group
(OMG) in 1997 and they published it as version 1.2. Version 1.4 is current. A
major revision for version 2.0 is in progress. At the core of the UML is the model,
which in the context of a software development process is a simplification of
reality that helps the project team understand certain aspects of the complexity
inherent in software. The UML was designed to help the participants in software
development efforts build models that enable the team to visualize the system,
specify the structure and behavior of that system, construct the system, and
document the decisions made along the way. While this standard is not perfect
for all situations, it does mean that all practitioners are able to read each otherÊs
diagrams. Most IT professionals use only a tiny part of UML.
Figure 1.18: Overview of the Main UML Diagrams according to the Phases of Software
Development Life-Cycle
The main UML diagrams that can be used for static modeling are:
• Use case
• Use case diagram
• Analysis class diagram
On the other hand, the main UML diagrams that can be used for dynamic
modeling are:
• State diagram
• Sequence diagram
• Collaboration diagram
• 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.
• Class that inherits other class is known as subclass. Subclass has all the
characteristics and behaviour inherited from the superclass, but has added
some more characteristics and behaviours for themselves.
• The static modeling and dynamic modeling are the subsets that make up the
systems modeling, which is the key aspect of most systems development
methodology.
LEARNING OUTCOMES
When you have completed this topic, you will be able to:
1. Describe the meaning of static modeling;
2. Write use case for a given problem;
3. Draw use case diagram for a given problem;
4. Draw an activity diagram for a given problem;
5. Describe the link between use cases and business rules;
6. Describe the issues in drawing an analysis class diagram;
7. Draw analysis class diagram for a given problem; and
8. Differentiate use case, use case diagram and analysis class diagram.
INTRODUCTION
Before developing a system, it is important for the system developer to
understand the system thoroughly. This is done to ensure that the developed
system will behave as expected. Software developers normally will create the
model of the system prior to developing the system. The model will highlight
important aspects of the system such as data flow, interaction between the
modules, etc so that the implementation can be done without any bugs or defects.
Object-oriented system which is developed using object-oriented programming
normally will be modeled using object modeling techniques. UML is the common
„tool‰ used to perform object modeling in developing object-oriented systems.
UML was the result of the collaboration between three methodologists: Jim
Rumbaugh, Grady Booch and Ivar Jacobson.
System can be modeled from two angles: static and dynamic aspects. The static
characteristic of a system is essentially the structural aspect of the system. The
static characteristics define what parts the system is made up of. In this topic, we
will briefly introduce to you some of the UML notations used to visualise the
static features of system using use case, use case diagram and analysis class
diagram. The next topic will touch on using UML to perform dynamic modeling
of a system.
In addition to use cases, you will learn about three UML diagrams that are used
in conjunction with use cases. Use case diagrams give a pictorial view of the
actors and use cases. Activity diagrams show how some use cases interact to
achieve a business task or process. Use case package diagrams to logically group
the use cases to make it easier to understand the big picture.
The requirements for the system are the outcome of this process and represent an
agreement between the system development team members, customers and
users. Note that the requirements will tell what the system will do, rather than
how it will do it. Writing the requirements involve:
Defining the purpose of the system, prioritising its functionality, and specifying
its context (i.e. who are its users and what systems does it interact with?).
Identifying external interfaces, both human and system-to-system. The
technology of an existing system with which the system must interface can
constrain the requirements and design.
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.
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
EXERCISE 2.2
VictoriaÊs VideosS
In this topic, we will use VictoriaÊs Videos system, which you were
introduced to in Appendix as the basis for some activities.
Have another look at the case study and list two functional requirements
and two non-functional requirements for the system.
especially true if the domain is a new one. Other domain related challenges
include: ascertaining the systemÊs role within the domain; achieving
immersion in the problem domain; translating what you learn about the
domain requirements specifications and system responsibilities. Obviously,
the bigger and more complex the system required, the more challenging
your task.
The Use Case Model consists of actors and use cases. Actors represent the
entities external to the system, either users or other systems. Use cases
represent the functional behaviour of the system. Actors help define the
system and give you a clearer picture of what it is supposed to do. WeÊll
look at actors further in the next section.
A use case represents events triggered by actors and describes how the
system must respond. Because use cases are developed according to the
actorsÊ needs, the system is more likely to be relevant to the users.
Figure 2.1 shows the main steps of building and delivering some
functionality. Use cases live through the entire system life cycle and act as a
unifying thread. The same Use Case Model is used during all subsequent
workflows. This topic covers the first three steps in more detail. Step 4 is
not covered in the syllabus.
2. Secondary · A person in this role does not directly use the system, but uses
or generates data for the system. A classic example is a person who receives
reports from a system, particularly in another department in the
organisation. This person may or may not access the system to get the
report, but is a user of the information. (Typically, these roles are
overlooked in the requirements analysis.) An example in the case study is
the managers.
3. External · Any system that receives or generates data for the system ·
these are external systems, e.g. tax office system, bank, accounts system, etc.
Note that this taxonomy differs slightly from UML and in Larman (2002). In
particular, in UML users and external systems are treated the same. It is true that
they are both external to the system, but treating people and computers in the
same way is not conducive to building usable systems. Further, our experience
shows that frequently the needs of the secondary actors are often omitted. Often
the need for reporting is known, but instead of the needs being closely examined,
the standard response is to simply add an end-user reporting tool. Very rarely
does this simplistic approach satisfy. If senior management does not receive any
benefits from a system then the project may be terminated.
EXERCISE 2.3
Identify possible actors for VictoriaÊs Videos system and categorise them as
primary, secondary or external.
There are three types of format for writing use cases. The format to be considered
is depends on the need. The explanation for these three types of use cases format
are given as follows:
Brief use case - it has one-paragraph summary and normally used for main
success scenario. Here is an example of brief format use case for Process Sale
(Modified from Larman, 2002):
Process Sale:
1. Customer arrives at POS checkout with goods and/or services to
purchase.
2. Cashier starts a new sale.
3. Cashier enters item identifier.
4. System records sale line item and presents item description, price,
and running total.
5. Price calculated from a set of price rules.
6. System presents total with taxes calculated.
7. Cashier tells Customer the total, and asks for payment.
8. Customer pays and System handles payment.
9. System logs completed sale and sends sale and payment
information to the external accounting system (for accounting and
commissions) and inventory system (to update inventory).
10. System presents receipt. Customer leaves with receipt and goods
(if any).
Writing a use case is, to a certain extent, is like writing a report, and as you will
know if youÊve ever written a report, itÊs much easier if you can follow some kind
of format. Most companies and organizations have report templates for people to
refer to. Similarly, for use cases there are templates that system analysts can refer
to. One of the most popular use case templates was developed by Alistair
Cockburn. The full version and a detailed description of the template are
available at http://members.aol.com/acockburn/papers/uctempla.doc. Use case
templates are not covered in this course.
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.
records a set of scenarios that traverse an actor from a trigger event toward a
goal but fall short of the goal (alternate scenarios). The format to write an
alternate scenario is as below:
condition:
handling
Example of alternate scenarios for Process Sale are given below (Larman, 2002)
based on the above format:
Write the condition as something that can be detected by the system or an actor.
The above examples only have one handling for the conditions. There can be
more than one handling for certain conditions.
EXERCISE 2.7
Identify success scenarios and alternate scenarios for NextGen POS example.
Remember that a use case may has a main success scenario and some alternate
scenarios. Sometimes, when we have a large and complicated system to develop,
there will be lots of different scenarios. It would be impossible to discover all the
possible scenarios at the very beginning. Hence, when you first start writing use
cases for a system, itÊs best to ignore all the alternate scenarios and only think
about everything going well · the Âsunny day scenarioÊ. Alternative scenarios
can be added later after you have identified all the success scenarios. Of course,
successful scenarios can also be revised and changed in later stages.
EXERCISE 2.8
We have written up a main success scenario for the borrow videos use case
in Exercise 2.4. Try to think up a few alternate scenarios and present them in
a brief format similar to the main success scenario. Compare your answer
with your course mates.
Model such as Use Case Model help system developers to build their systems in a
systematic manner. Poor system development tends to be done by developers
who cannot judge what they should be doing at each phase of the development
cycle. A common mistake is to jump into the system design before a good
requirements analysis is available. Black-box use cases approach is usually
adopted to help system developers avoid making the same mistake twice. Let us
know discuss the term. Something is a black box if we cannot see the inner
workings of it. For example, from a car driverÊs perspective, a car is a black box.
The car either moves properly or it does not. If there is a problem, then the car
mechanic comes and, with a white-box view, lifts the car bonnet and looks at the
engine and internals. Hence, in the black-box approach of use cases writing, we
donÊt care about how the system will perform the tasks but just focus on what we
should expect from the system. In other words, we are only focusing on the
responsibilities of the system. Example of black box use case shown in Table 2.1:
Table 2.1: Example of Black Box Use Case
The system updates the student The system writes the new marks to a database
marks
The system generates a SQL UPDATE
statement for the task
Sometimes confusion will still arise even if we adopt the black-box approach, because
different people have a different understanding of Âwhat the system doesÊ. For example,
a cashier might think of her goal as Âlogging inÊ, but in fact this is just the mechanism that
achieves the higher-level goal of identifying and authenticating herself. When writing
use cases, keep the user interface out and focus only on actor intent.
EXERCISE 2.9
Now take the three use cases from Exercises 2.4 and 2.6, and rewrite them in
the essential two-column format. (Yes, writing use cases is hard work, but
the more you write the easier it gets. It is not good enough to just look at the
answers. You must practise).
different goals. For example, the general manager of the retail store is expecting the
retail system in his company to streamline the whole retailing process. The cashier,
on the other hand, may expect the same system to read the barcodes of items
correctly and efficiently. Well, which one of these two requirements should be
turned into a use case? In fact, neither of them would make a good use case. The
general managerÊs goal is at too high a level while the cashierÊs goal is too low. So
what level of user goals can be transformed into use cases? The general guideline is
to look at elementary business processes (EBPs). The following Reading 2.4 will
explain to you the concept of EBP. It also gives a very lively example of how a
system analyst investigates the user goal of the cashier through a series of
questions and identifies the appropriate goal level for writing a use case.
READING 2.1
Now download Reading 2.1 from myLMS to learn about goals and scopes of
use case.
Information systems are rather abstract entities that consist of software, hardware
and applications. However, even though we cannot visualize the whole
information system, for the purpose of use cases we need to define a boundary
for it. ItÊs similar to building a house, when we need to perform a land survey to
fix the boundary of the site on which the house is going to be built. A clearly
defined system boundary helps in the correct identification of the right actors to
use cases, which in turn helps the system analyst to obtain the goals. The four-
step procedure proposed to define use cases is listed as follows:
1. Define the right system boundary
2. Identify the primary actors
3. Identify the actorsÊ goals
4. Define and name the use cases.
READING 2.2
EXERCISE 2.10
For VictoriaÊs Videos, up to now we have tried to identify the actors and
some brief use cases. However, all these were produced by our imagination.
In a real system, the proper way to do requirements analysis is to carry out
a combination of many activities such as:
Read any documentation that has been collected.
Look at any systems that currently exist. Look at screens and reports.
See if you can track some real examples all the way through. For
example, for an insurance system, you could see how a policy is created,
and then later how a claim might be processed.
Talk to the parties concerned. Commonly you begin by conducting
some user requirements workshops. Use the initial actor analysis work
as a guide to who should attend the workshop. For the first workshops
it is best to have more people rather than less as you need the broadest
possible range of views. Later, you can have much smaller workshops
to concentrate on particular areas.
Prepare a list of questions that you would like to ask various people from
VictoriaÊs Videos.
ItÊs important that you understand the use case model as itÊs a crucial element in
requirementÊs analysis and it is one of the earliest tasks in the whole system
development project. The future success of the project depends on getting the
use case right. As itÊs sometimes helpful to approach a topic from a different
angle, weÊd like you to reinforce your understanding of the Use Case Model by
working through the next reading by Cockburn.
ACTIVITY 2.1
Internet Reading
Cockburn, A, ÂStructuring use case with goalsÊ at
<http://members.aol.com/acockburn/papers/usecases.htm>
The following figure is the simple UML notation to depict a use case.
A collection of use case diagrams will form a context for use case diagrams that
shows the scope of the system, and the relationship between the actors and use
cases. It serves as a diagrammatic summary of the behaviour of the system.
According to Larman (2002), use case diagrams are only secondary in use case
writing. System developers should not spend too much time drawing use case
diagrams. Writing use case text should be the primary focus.
5.
READING 2.3
Now download Reading 2.3 from myLMS to learn about use case diagram in
detail.
EXERCISE 2.11
By using the example of use case diagram shown below as a guide, draw a
use case diagram for VictoriaÊs Videos.
The following diagram shows how the different actors invoke their own use cases
to achieve the overall task. The diagram has ÂswimlanesÊ for each of the different
actors.
Each system is different so you have to decide whether or not any activity
diagrams are useful or not.
EXERCISE 2.12
Do you think an activity diagram would help explain how a subset of the
use cases for VictoriaÊs Videos system fit together to form a whole? If so,
then draw it. Note: We are not trying to draw all the use cases of the whole
system, but only some of them that make up a process that makes sense to
the users as a whole.
In writing this list, Susan Lilly (1999) is not arguing against use cases, but trying
to alert newcomers to the potential problems, and suggest ways to avoid them.
She advises:
Explicitly define the systemÊs boundary. This makes clear what is inside the
system and what is outside the system.
Make use of a standardised template for documenting your use-case
specifications. If the team uses a template, it will help communications
between team members as well as help newcomers get started.
When writing use cases, focus on the goals of the actors. This will help you
find use cases from the usersÊ perspective and keep a focus on the primary
function of the system.
DonÊt make use-case specification synonymous with user-interface design.
You can use low-fidelity representation of user interfaces, but since user
interface design is particularly subject to design-specific change, it is best not
to include it as part of the requirements if you want to get them signed off
earlier rather than later.
To help catch potential problems, Lilly suggests that you review your Use Case
Model, the diagrams and specifications, in incremental steps with the
development team, clients, and users. Start by reviewing your use-case diagram
before youÊve defined use case details; check that the system boundary has been
clearly defined, that obvious actors have not been missed and that the use cases
focus on the usersÊ goals.
EXERCISE 2.13
Deciding on the packages for a system requires a little experience, and there are
generally several valid approaches for one system. Some possibilities for
packaging the use case are listed as follows:
By functional areas. For example, put everything to do with money in one
package, and inventory in another.
By actor. For example, put all the cashierÊs use cases in one package.
By ÂstyleÊ of use case. For example, put all the simple setup/maintenance
style use cases in one package.
By importance or iteration. For example, all the use cases that are going to be
built first could be in one package.
By physical implementation. For example, all the use cases that are delivered
via the Web are in one package, and use cases accessed via the head office
computer are in another package.
The UML notation for a package is a folder. But, as emphasized earlier, the text
of the use case is more important than the diagrams. So often a use case package
is simply a short description of the use case, followed by a list of the use cases
that comprise the package. Optionally, include a use case diagram of the use
cases.
There are many different approaches and styles to writing use cases. Reasons for
these differences include personal preferences, different styles of application (for
example, a website selling books is different from a stock market trading system),
and different scales/styles of development (for example, two people on a three-
month project work very differently than 50 people on a two-year project).
The next reading is a review of use cases, written by their inventor, Ivar Jacobsen.
He starts with a short history of their development.
ACTIVITY 2.2
Internet Reading
Jacobsen, I (2003) ÂUse cases · yesterday, today and tomorrowÊ at
<http://www.therationaledge.com/content/mar_03/f_useCases_ij.jsp?fro
m= inbrief>
Read up to the end of page 4, up to the start of the section titled ÂHow many
use cases is enough?Ê
As you can see from this reading, one aspect of use cases that has been evolving
since 1986 is how we can relate one use case with other use cases. Relating use
cases to each other allows us to see commonalities and differences between them.
Before we discuss these relationships in more detail, remember that we primarily write
use cases for people to read. Use cases are not read by a compiler (a software program
that turns a computer program into executable computer code) or by any other kind of
tool. So before we add relationships to our use cases, we must be sure that adding
complexity will help the (human) reader to better understand them.
One more word of caution. As you saw in the reading, Jacobsen has changed his
views on how best to relate use cases. Use cases are not mathematically defined,
so the relationships between them are not rigorously defined, either. You will
probably find that when you read the details on the different types of
relationships, it will all seem quite simple, but that when you try to apply this
knowledge, it can be quite hard. Everyone, both novices and skilled practitioners,
faces the same problem. The solution is to remember that use cases are for human
use.
ACTIVITY 2.3
Internet Reading
Jacobsen, I (2003) ÂUse cases · yesterday, today and tomorrowÊ at
<http://www.therationaledge.com/content/mar_03/f_useCases_ij.jsp?fr
om=inbrief>
Read pages 4ă5, i.e. the sections ÂUse cases and the unified modelling
languageÊ and ÂUse caution when formalising use casesÊ.
As an example, letÊs consider VictoriaÊs Videos. We have identified the use case
Maintain Members (from Exercise 2.6). The next table is a first draft for that use
case.
Maintain Members
ÂIdentify the borrowerÊ. As we are looking at use cases in essential format, this
might not seem like very much. But before we can build this system, we will have
to decide how the borrower will be identified. Will the user have a card to be
scanned, or will she give us her name or an identification number? Will she need
to quote a password? So to cater for all these later concerns, we can create a sub-
use case that we will call ÂGet BorrowerÊ. And now both the Borrow Videos and
Identify Members use cases will ÿincludeŸ the Get Borrower sub-use case. (Note
the UML notation of placing the special characters ÿ Ÿ around the word ÂincludeÊ.)
So now, how do our use cases look? In long hand we could have.
Maintain Members
Get Borrower
Level: Subfunction
Actor intention System responsibility
Identify the borrower Display personal details (name, address,
date of birth, date joined, etc.) of the
borrower ⁄
You will notice the headings at the start of the use case that has level clause. It
tells us that this is a sub-use case, as it only gives us a subfunction. That is, this
use case makes no sense by itself. It needs to be called by another use case.
Copyright © Open University Malaysia (OUM)
48 TOPIC 2 STATIC MODELLING WITH UML
EXERCISE 2.14
LetÊs again think back to the situation of VictoriaÊs Videos. You already have
a use case to borrow videos. But now Victoria tells you that she would also
like to sell old videos that she doesnÊt need.
Update your use case diagram (from Exercise 2.11) with any new use cases.
The include relationship is the most useful relationship between use cases, and
you can build very sophisticated models using only this relationship. Indeed,
Cockburn (2002, 207), writes:
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.
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.
Level: Subfunction
Trigger: Customer has a birthday letter
Extension point: Calculate total fee due in Borrow Videos
Actor intention System responsibility
Indicate that the borrower has a Confirm birthday borrowing has not
birthday letter already been used this year
Record use of birthday letter
Adjust total due
Once again you can see weÊre at the subfunction level. The trigger clause tells us
when it gets started, namely when a customer has a birthday letter. The extension
point tells us that the use case Handle a Birthday Letter gets started from the use
case Borrow Videos when it reaches the part Âcalculate total fee dueÊ. This is
called an extension point.
Lastly, to keep the use cases tidy, we can document the Borrow Videos use case
to show that there is an extension. In other words, we make it clear to someone
reading this use case that, as part of Âcalculate total fee dueÊ, there is something
more happening.
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.15A
The generalization relationship also can be used for actors in the use case
diagram as shown below:
general actor
specialised actors
ACTIVITY 2.4
Internet Reading
Gottesdiener, E. (1999). ÂCapturing business rulesÊ, Software Development
Magazine, 7(12), at
<http://www.ebgconsulting.com/Capturing%20Business%20Rules.pdf>
In fact, besides their role in the use cases, business rules are also linked to other
artifacts in the software development process. The following reading discusses
such links, in particular to user interface designs, data cleansing and validation.
ACTIVITY 2.5
Internet Reading
Ambler, S (2000) ÂObject-oriented business rulesÊ at
<http://www.sdmagazine.com/documents/s=826/sdm0006j/>
In the last section of the reading, Ambler mentions the object constraint language
(OCL) as a means to express business rules. Other experts disagree. For example,
Gottesdiener says that business rules should be written in a language that the
users understand. We also like to adopt this approach in writing business rules.
The following are some options that we suggest can best express business rules:
list all the rules in one list, and then refer to the list from everywhere else ·
use cases, screen mockups, class diagrams, etc.;
simply locate the rules in the use cases, as we have done in this course; and
keep the use cases simple, but add a section to your use case template to
explicitly refer to the business rules that each use case implements.
So, as you can see, there is a range of possibilities. Additional factors to consider
are the style of system (e.g. does it involve lots of calculations), the size of the
application, the tools that are being used, etc.
So what are the business rules in VictoriaÊs Videos? Here are some examples:
Only members can borrow videos.
When a new person requests to become a member, they must show their
driverÊs license or other photo ID.
The minimum age is 16 years old.
A member can borrow any number of videos, as long as they have no
overdue videos.
There are fines for overdue videos.
The length of time that a video can be borrowed for depends on the video.
New releases are only lent out overnight, current releases are for three-day
hire, and the rest are for a week.
You should recognize most of this text as it is pretty close to the initial description
that you saw from Victoria Videos Case Study. When describing a system, one
very common method is to list and describe the business rules. The skill of a
requirements analyst is to capture these rules and make them into something that
the rest of the design and programming team can work with. Use cases are a key
way of weaving the business rules together to create a system.
EXERCISE 2.15B
For each of the example business rules we have just given for VictoriaÊs Videos,
decide if the rule has been captured in any use case(s). If so, name them. Or, you
might note that a business rule has not yet been captured in any use case.
The previous exercise should have helped you to appreciate the fact that quite a strong
link exists between use cases and business rules, but that each form is quite different.
Up to now there has been nothing object-oriented in the material. We could write
use cases and then continue in a non-object-oriented manner. Now we will start
the object-oriented modeling using analysis class diagram. While the material is
presented to you sequentially, in reality the object-oriented modeling happens in
parallel with the use case writing.
This section is all about „analysis class diagram‰. The example of an analysis
class diagram is shown below (Larman, 2002):
Remember..
Analysis class diagram which is produced during the analysis phase is a
visualization of things in the real world domain of interest and NOT the
software components such as Java classes. On the other hand, the relationship
between the software classes, which depicts the details of the classes are done
through the design class diagram which takes place during the design phase.
Design class diagram is beyond of the syllabus.
EXERCISE 2.16
Before we go into the details of the domain model, letÊs make sure we are
clear about its function. Refer to the diagram below:
Do not be concerned with the exact meanings of the notation ă the lines,
words, arrows, etc. ă as this is all explained later in this topic. For the
moment, just try to read the diagram with the following words, starting in
the top right-hand corner: Items are Stocked-In a Store. A Store has an
address (e.g. 15 Jalan XYZ, Ipoh) and a name (e.g. Kedai Perabot Ali). Each
Store houses, or has, some Registers. Every Sale is captured-on, or recorded
on, a Register.
Continue with this description to cover all the domain objects and
relationships as depicted in the figure above. See if it gives you a better
understanding of the „payment sale‰ process of the NextGen POS case.
As the relationship between a class and its objects is so clear, we often get a bit
lazy with our language. If the head of engineering for a car factory says: ÂThe
painting on the car needs to be done betterÊ, he or she is probably talking about
the process that goes on in the factory rather than a specific car. So too in software
modeling we swap between using the words class and object.
The entity objects fall into a number of categories, based on the real-world objects
that they represent. Here are three kinds of conceptual class that we will
encounter in business modeling:
Concrete objects are tangible, i.e. have a physical presence. Concrete objects
are the most easily understood by analysts and users. In the video shop
example, video CD is a concrete object.
Conceptual objects are intangible and often far more difficult to understand.
For example, school is a conceptual object. You may argue that a school
tangibly exists · it has buildings. However, the concept of a school is not just
the buildings. Imagine that all the buildings in a school collapse in an
earthquake. We cannot say that the school doesnÊt exist anymore. It can be
rebuilt. Similarly, video title is also a conceptual object.
Event and state objects are highly abstract in nature. They are related in that
typically when an event of any significance occurs, some or more objects will
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.
three categories are further expanded into finer categories according to Table 2.7
as shown below:
Even though the category list as presented is drawn from some particular
domains (in the Table 2.7 case, the store domain), it more or less covers many
common categories in other business domains.
EXERCISE 2.17
Another technique for identifying conceptual classes is the use of noun phrase
identification. You will see that one of the arguments for developing use cases
before domain modeling is that they are an excellent source of noun phrases for
conceptual class identification. However, note about the danger of ambiguities in
the natural language of use cases translating to the conceptual classes if the
transformation of one to the other is made too mechanically.
Now let us see one example in which we going to use noun phrase identification
to identify conceptual classes.
EXAMPLE
Below is a description of a Web-based ticket reservation system. All the noun
phrases that are candidates for conceptual classes is highlighted in bold.
Concentrate just on the customer side ă donÊt model the supply of tickets from
„the usual ticket agencies‰.
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,
etc., that go with it. After the video has been borrowed by a member and he/she
has lost it, the video will be deleted from the system. If the management needs to
obtain some information about the video (e.g. what classification it is) there is no
way they can obtain that information. To solve this problem, we need a
EXERCISE 2.18
2.7.5 Associations
Now we have successfully identified the conceptual classes in the business
domain. Say, in the video shop system, we have identified ÂMemberÊ, ÂVideoÊ,
ÂFrontDeskÊ, ÂMemberRecordÊ as the conceptual classes (please note that this is a
highly simplified domain model and may not be the real domain model for the
video shop case). What are we going to do with all these objects (or conceptual
classes)? An obvious answer is to find out how they are related. An association is
an object-oriented term for relationship. People in the real world have
relationships with other people, with things and with places. So we can say a
person has a mother, is married to their spouse, likes to drive their Porsche, lives
in a house, etc. These are the associations of the object ÂpeopleÊ to other objects in
the real world. We notice that most of the relationships between the object
ÂpeopleÊ and the other objects are described by verbs such as ÂhasÊ, Âmarried toÊ,
Âlikes toÊ, Âlives inÊ, etc.
The following figure 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.9. Pick the
first and second classes in the list, i.e. ÂMemberÊ and ÂVideoÊ and check whether
they have a relationship (either from the use case or discussion with users). If
there is a relationship (in this case ÂMember Borrow VideoÊ), add an association to
the UML diagram. At the same time, a line is drawn linking the ÂMemberÊ and
ÂVideoÊ items in the list, indicating that the relationship of these two classes has
been checked.
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, i.e. the ÂMemberÊ-
ÂMemberRecordÊ pair. If a relationship exists, an association is added in the UML
diagram. For the items in the list, even though there is no relationship between
two items, such as ÂMemberÊ and ÂMemberRecordÊ, a link is also drawn to link the
two items to indicate that the relationship between the two has been considered.
When ÂMemberÊ and all the other items down the list have been linked, it
indicates that the relationship between ÂMemberÊ and all the other classes has
been considered (regardless of whether or not they have an association in the
UML diagram). We can move on to the next step.
In the next step, the relationship between the class ÂVideoÊ and the other classes
down the list is considered. Similarly, items are linked after their relationship has
been checked and an association is added between any two classes in the UML
diagram if a relationship exists.
This step is repeated with class pairs down the list until all class pairs have been
considered. The final model will look like Figure 2.11.
Category Examples
A is a physical part of B Wing-Airplane
A is a logical part of B FlightLeg-FlightRoute
A is physically contained in/on B Passenger-Airplane
A is logically contained in/on B Flight-FlightSchedule
A is description for B FlightDescription-Flight
A is a line item of a transaction or report B MaintenanceJob-MaintenanceLog
A is known/logged/recorded/reported/captured Reservation-FlightManifest
in B
A is member of B Pilot-Airplane
A is an organizational subunit of B Maintenance-Airplane
A uses or manages B Pilot-Airplane
A communicates with B ReservationAgent-Passenger
A is related to a transaction B Passenger-Ticket
A is transaction related to another transaction B Reservation-Cancellation
A is next to B City-City
A is owned by B Plane-Airplane
A is an event related to B Departure-Flight
2.7.5.2 Multiplicity
As you identify and draw each association, you will initially draw it as a simple
line joining two boxes in the UML diagram. Once you have established the
association, e.g. ÂMember Borrow VideoÊ, there is another question to ask: How
many videos will the member borrow? This question relates to the multiplicity of
the association.
The multiplicity of an association is the number of instances of each class that can
participate in an occurrence of the association. The following table lists some
possible multiplicity values for associations. Multiplicity is an important piece of
information for the later system design stage. It communicates important domain
constraints that will affect the software design, especially in database design in
the implementation stage.
Multiplicities Meaning
11 one-to-one
1* one-to-many
1 1..* one-to-one or more
1 0,1 one-to-zero or one-to-one
Figure 2.12 depicts the domain model of the video shop system with multiplicity
added.
Figure below shows a design class diagram which has association, composition
and aggregation relationships. Multiplicity of an association between classes also
shown in the figure as follows:
Notice that with both types of aggregation and composition relationships, the
diamond is located on the side of the line pointing to the class which represents
the "whole" in the relationship. Aggregation is a special form of association that is
tighter than a normal association. Aggregation means that there is a whole-part
relationship. Furthermore, the parts usually cannot exist without the whole.
Aggregation causes much confusion. As Martin Fowler writes in UML Distilled,
2nd edn, page 85:
EXERCISE 2.19
2.7.7 Attributes
Attributes are the pieces of data we use to identify or describe things. For
example, a person has a name, date of birth and eye colour. Attributes usually
correspond to nouns followed by possessive phrases, such as Âthe colour of that
carÊ. In this case, colour is the attribute of car. Attributes are usually simple data
types or primitive data types such as integer, float, string, date, time, etc.
For the video shop system, the following are possible attributes to the conceptual
classes identified:
Member · memberÊs number
Video · video ID, classification
FrontDesk · front desk register number
MemberRecord · number of video items borrowed, due dates of items
borrowed.
In UML, attributes are shown in the lower compartment of the rectangular box
representing the conceptual class. Hence the completed domain model, as
represented in UML for the video shop system is as shown in Figure 2.13.
Do not list object identifiers that are used purely for unambiguously
referencing an object.
If an attribute describes the internal state of a class that is invisible outside the
class then eliminate it from the analysis.
Omit minor attributes that are unlikely to affect most operations.
READING 2.4
Download Reading 2.4 from myLMS to learn how attributes have been
discovered for NextGen domain model besides the domain model
conclusion for this case study.
EXERCISE 2.20
The following tips by Larman (2002) is very useful when creating analysis class
diagram:
Use Conceptual Class Category (from Table 2.7) or noun phrase identification
to identify the conceptual classes.
Draw them in the analysis class diagram.
Add the associations necessary to show the relationship between the classes.
Add the attributes necessary to fulfill the information requirements.
System can be modeled 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 visualize the static features of system: use case, use case diagram, activity
diagram, 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 to understand the overall
picture of the system, the flow of events and the relationship between actors
and use cases.
Basically, use cases are textual in nature with, probably to a minimal extent,
the help of some use case diagrams to facilitate the understanding of the use
cases.
You modelled a business domain with highly abstract analysis class diagram.
You learned how use cases are used to aid conceptual class identification.
You also identified the associations between conceptual classes and found
their intrinsic properties by identifying their attributes.
LEARNING OUTCOMES
When you have completed this topic you will be able to:
1. Describe the meaning dynamic modeling;
2. Draw a state diagram for a given problem;
3. Use state diagram to identify for any missing use cases;
4. Draw a sequence diagram for a given problem;
5. Draw a collaboration diagram for a given problem; and
6. Convert a collaboration diagram into a sequence diagram.
INTRODUCTION
Previous topic has dealt with static modeling using UML. This topic will focus on
dynamic modeling using UML.
Software design is about behavior and behavior is dynamic. The ways a system
behaves in response to certain events or actions are the dynamic characteristics of
a system. Therefore an emphasis upon dynamic models is very important in
designing a system.
There are three kinds of diagrams in UML that depict dynamic models. State
diagrams describe how a system responds to events in a manner that is
dependent upon its state. The other two kinds of dynamic diagram fall into this
category called Interaction diagrams. They both describe the flow of messages
between objects. However, sequence diagrams focus on the order in which the
messages are sent. They are very useful for describing the procedural flow
through many objects. They are also quite useful for finding race conditions in
concurrent systems. Collaboration diagram, on the other hand, focus upon the
relationships between the objects. They are very useful for visualizing the way
several objects collaborate to get a job done and for comparing a dynamic model
with a static model. Collaboration and sequence diagrams describe the same
information, and can be transformed into one another without difficulty. The
choice between the two depends upon what the designer wants to make visually
apparent.
The following table gives some examples of systems and a list of their conceptual
classes. The third column suggests the conceptual classes that probably require a
state diagram. As you can see, the words in the third column are really the core of
each system.
Table 3.1: Examples of Systems and Conceptual Classes that require State Diagrams
EXERCISE 3.1
Suppose weÊve just started work and weÊve identified three use cases:
Admission · Handles the prisoner being transferred from the police or
courts to the prison, and being admitted.
Transfer · Handles transferring a prisoner to a half-way house.
Release · Handles the way in which a prisoner is released back into the
community.
In parallel with identifying and writing use cases, we are also working on the
conceptual class model. Quickly we realise that Prisoner is a key conceptual class,
so we start to draw its state diagram.
We have boxes with rounded corners to denote each state. Each state must be
given a meaningful name. Notice that the name of the last state ends in ÂedÊ ·
this is a very common ending for English state names.
What this diagram shows is that there are three states that a prisoner can be in.
Next we look at how our use case model supports these states. So what we do is
show the use cases on the state diagram. So our diagram is now this:
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:
This new version has a new state called Escaped (notice that it ends in ÂedÊ), and
weÊve identified two new use cases, namely Escape and Re-capture. This is the
crucial point of drawing state diagrams · they help us to quickly find missing
use cases.
Notice in this last diagram that we now recognize that some escaped prisoners
never get recaptured.
EXERCISE 3.2
For VictoriaÊs Videos, draw two separate state diagrams, one for Video
Tape, and one for Member.
ÂThatÊs fine, but prisoners can also escape from being in the half-way
house. Of course if we capture them, then they go back into custody.Ê
You will notice that there are two transitions, or use cases, called Escape. Now
since these refer to the same use case, we can simplify the diagram by introducing
the concept of a super state.
In the next version you can see that there is a super state called Admitted. So
what we are now saying is that if a prisoner is In Custody or In half-way house,
and they Escape, then they will be in the state Escaped. Once they are in the state
Escaped, if they are re-captured, they go to the state In Custody.
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
In addition to the notation in the reading, there is also the concept of a multi
object. This is also known as a collection object (such as a list). So a message
which is shown as being sent to a multi object, is really a message sent to the
collector of that object. The collector then finds the correct object.
EXERCISE 3.3
Your task is to translate this diagram into a dialogue between the various
components.
Object 1 Object 2
name name
Typically a sequence diagram shows one use case. However, to adequately show
how errors are handled, often extra diagrams are required.
READING 3.2
EXERCISE 3.4
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 its types of ÂdoingÊ responsibilities that must be
defined appropriately for classes in a system.
A classÊs responsibilities might be: knowing about its own data, knowing about a
related object or knowing about things it can figure out.
Where to begin? We start with the GUI telling the Register its ready to create a
new sale. This is a simple create operation on the class Sale. Next the GUI sends
the Register the id or barcode of the item and the quantity. Next we need to find
out what the item is, as per our robustness diagram. LetÊs just check that this is
correct. So look at the conceptual class model on page below:
(Source: Larman(2002))
What do you notice about the itemId? Is this attribute on the Item class? No, itÊs
not · itÊs on ProductSpecification. But how do we get to ProductSpecification?
From the domain model, we know that it is from the ProductCatalog. We are
trying to get a whole ProductSpecification object back, so note the syntax of
message 5 from Figure 3.10. Next the ProductCatalog object sends a message to
the ProductSpecification collection object, denoted with the special notation. This
collection object finds the correct ProductSpecification and sends it back.
(Note: At this point we have assumed that all these objects are sitting around just
waiting for us to talk to them. In reality of course they would be in a database,
and we would have to do some work to get them out. Getting data in and out of
databases is not covered in this module.)
Lastly, the payment is made (assume itÊs cash only, and that correct money is
given) and the Payment object is created.
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
EXERCISE 3.6
Draw a collaboration diagram and a sequence diagram for the use case
Borrow Videos in the VictoriaÊs Video case.
The ways a system behaves in response to certain events or actions are the
dynamic characteristics of a system.
Thus, the designer must iterate between the two kinds of models, driving
them to converge on an acceptable solution.
X INTRODUCTION
The previous topics have dealt on how to create models of object-oriented
systems. In particular, you have learned on how to perform systems modelling
using UML. You have learned that UML can be used to perform static and
dynamic modelling for object-oriented systems. Model is just a model in the
sense that it cannot be executed. Model gives us a solid understanding about the
nature and behaviour of the system. Model acts as a blueprint in order to
implement the system. Object-oriented programming language such as Java is the
popular language used to implement UML models. This topic and onwards will
focus on Java programming language.
What is so special in Java that computer industries and businesses can accept it
within a very short period of time compared to other new technologies in the
computer history? The answer to this question is provided in the next subtopic ă
4.2 Characteristics of Java. The next section will give overview of Java.
Figure 4.2 illustrates the Java programming environment. The output of Java
program compilation is in the form of bytecode. Java bytecode is a set of
instructions that is quite similar to the machine code instructions or native code
for a machine. The difference is that the bytecode is not specific to any processor.
The result of compilation can be implemented by a Java Virtual Machine (JVM),
any machine that will interpret the bytecode.
Java Interpreter
(Pentium)
Java Interpreter
Java Program Java Compiler Java Bytecode (Power PC)
Java Interpreter
(SPARC)
Java Interpreter
(Pentium)
Java Interpreter
Java Program Java Compiler Java Bytecode
(Power PC)
Java Interpreter
(SPARC)
Simple
Java has functionality needed to implement its rich feature set. It does not add
lots of syntactic structure or unnecessary features.
Object-Oriented
Almost everything in Java is either a class, an interface, a method or an
object.
Platform Independent
Java programs are compiled to a byte code format that can be read and run
by interpreters on many platforms including Windows 95, Windows NT,
and Solaris 2.3 and later.
Safe
Java code can be executed in an environment that prohibits it from
introducing viruses, deleting or modifying files, or otherwise performing
data destroying and computer crashing operations.
High Performance
Java can be compiled on the fly with a Just-In-Time compiler (JIT) to code that
rivals C++ in speed.
Multi-Threaded
Java is inherently multi-threaded. A single Java program can have many different
things processing independently and continuously.
drop, and other graphic elements. The aim is to make the software development
process fast, efficient, and easy to debug.
Part of IDE uses the Rapid Application Development (RAD) approach. RAD
accelerates the software development process by using tools such as the interface
designer. Many of the Java IDE available in the market uses the graphic interface
builder to support RAD.
The following are some Java IDE software with their URLs:
WinEdit (http://www.winedit.com/)
Jcreator (http://www.jcreator.com)
Java WebIDE (http://www.chami.com/webide)
Symantec Café/Visual Café (http://www.symantec.com/)
Forte for Java (http://www.sun.com/forte/ffj/)
Microsoft Visual J++ (http://www.microsoft.com/java/sdk)
Visual Age (http://www-4.ibm.com/software/ad/vajava/)
ACTIVITY 4.1
Exercise 8.1 JDK can be downloaded free from the website
http://java.sun.com/j2se.
Apart from application, another type of Java program is Applet. Applet is a web-
enabled program. The examples of test-based application will be illustrated in
the next section. Applet and Frame are not covered in the syllabus. Applet are
covered in another course, CDOP3203 ă Java Programming. We will skip any
elaboration about Frame and Applet in this module.
Java Program
Application Applet
Text-based Frame
application
Frame is non-Web stand alone GUI program
Program 4.1 shows an example of non-GUI stand alone application written using
structured approach.
In structured approach, all the statements and instructions are dump into main
method. Sometime, extra methods could be added to perform specific tasks. No
objects are required to be created when writing Java programs using structured
approach. The Program 4.1 above is described below.
Line 1
Line 1 in the program is comments written by the programmer. It helps others to
understand the nature of the program. Thus, the program becomes more
readable.
Line 2
Line 2 declares the name of the class as Hello.
Line 3
Line 3 is where the program starts to execute. In this class, a method called
main() contains the statements to display the „Hello world!‰ string. The main()
method must be present in all Java applications because it is the first method
that will be executed when an application runs (i.e. It is the where the program
starts to execute). The Java technology interpreter must find this defined exactly
as given or it refuses to run the program. The following describes each element of
line 3:
public: The method main() can be accessed by anything, including the Java
interpreter.
static: This keyword tells the compiler that the main() method is usable in
the context of the class Hello. No object is needed to execute static
methods.
void: This keyword indicates that the method main() does not return any
values (i.e.: There is no return keyword in the main() method).
String[ ] args: This method declares the single parameter to the main()
method. The name of the parameter is args with the type of String array.
Line 4
The statement System.out.println(„Hello world!‰) in Line 4 in the body of the
method will instruct the computer to display the message „Hello world‰ upon
execution.
Line 5, 6
Line 5 and 6 contain two braces to close the method main() and class Hello
respectively.
The following activity will guide you to compile and execute Program 4.1:
The purpose of this exercise is to you to compile and execute Program 4.1.
It is compulsory for you to follow all the steps to ensure that you can learn
how to compile and execute Java program using JDK.
STEP 1
By using notepad in Windows, type Program 4.1. Then save it in a file with
the name Hello.java in the correct directory (For JDK, the program is to be
saved in jdk1.x.x/bin directory unless you have given a new name to this
directory).
Note: x.x in jdk1.x.x refers to the jdk version installed in your computer.
Latest jdk use abbreviation j2sdk1.x.x
STEP 2
Now enter the DOS window (also known as Command Prompt or C
Then, you need to enter to the directory that stores the program that you
have typed in step 1.Use the DOS command cd to enter the correct directory
namely jdk1.x.x/bin
STEP 3
Compile the Java program using the instruction javac Hello.java in the DOS
environment. Example is shown below:
C:\jdk1.x.x\bin>javac Hello.java
STEP 4
Go back to notepad and open the file that you have typed in Step 1 (and at
the same time do not close DOS window). Do the necessary correction in
your program. Make sure you save your file after the corrections. Now go
back DOS window and repeat Step 3.
STEP 5
If there is no error, the compiler will generate the bytecode file ă that is
Hello.class. Now you are ready to execute your program. In order to do
this, type the command java Hello in DOS Window as shown below:
C:\jdk1.x.x\bin>java Hello
Take note that this instruction consists of two parts. The first part (java)
refers to the Java runtime interpreter. The second part (Hello) refers to the
class name which has the main() method that is to be executed by the
interpreter.
• In addition, the types of Java program also have been discussed in this topic.
• It important for the students to understand the types of Java program and be
able to compile and execute those programs.
LEARNING OUTCOMES
When you have completed this topic you will be able to:
1. Describe the importance of data type and variable in Java;
2. List the primitive data type in Java;
3. List the rules of naming a variable in Java;
4. Describe about assignment;
5. Describe about boolean operators and relational operators; and
6. Explain about operator precedence.
X INTRODUCTION
What is a computer program? A program is a sequence of instructions that a
computer can execute to perform some task. There are two basic blocks of
programming: data and instructions and to work with data, you need to
understand variables and data types; to work with instructions, you need to
understand control structures and subroutines (methods). This topic will focus
on how variables and data types and its related concepts can be implemented in
Java.
Java is a kind of language that places importance on the types. This means each
variable should consist of the approved types. There are eight types of primitive
data in Java. Six of these are the numerical types, while the others are the char
data that is used for characters in the Unicode coding and the other type of data
is Boolean for the true values (true or false). All types of data in Java have the
same cell sizes in any environment. All the variables in Java must have a type.
(Variables will be elaborated in section 5.2.)
5.1.1 Integer
The integer type of data is used for numbers that do not have decimals. The
negative values are also allowed. Java prepares four types of integer data,
namely int, short, long and byte. The storage size and the value range
for each of this data type is shown in Table 5.1 below:
In many cases, the int type data is the most practical. If the integer value used
is too large, for example, in representing the income of PETRONAS, the most
appropriate data is long. The byte and short data type are for the use of
specific application such as keeping files at a lower level or a larger array if the
storage space is insufficient.
In the Java language, the range for the integer data type does not depend on the
machine where the Java code is executed. Unlike Java, in C or C++ language, the
int data type is different according to the machine. For the 16 bytes processor
such as the 8086, the int cell size is 2 bytes while for the 32 bytes processor such
as the Sun SPARC, the cell size is 4 bytes. For the Intel Pentium processor, the
integer data type depends on the operation system: for DOS and Windows 3.1,
the integer cell size is 2 bytes and when using the 32 bytes processor on
Windows 95 or Windows NT, the cell size is 4 bytes.
Copyright © Open University Malaysia (OUM)
TOPIC 5 BASIC CONSTRUCTS OF JAVA W 103
As the range for all types of Java data is fixed, the Java program will produce the
same results if run on any machine. This makes it easier for the programmers
who wish to transfer their codes from one machine to another or between the
operational systems on the same platform.
The long type of numerical integer has the L suffix (for example
2412345600L). The hexadecimal numbers have the initial 0x (for example
0xA9B9). Take note that Java does not have the type of data with unsigned
descriptor as in C.
5.1.2 Real
The real data type or floating point represents numbers that have the decimal
parts. There are two types of real data types, which are float and double.
The storage size and value range for each of these data is shown in Table 5.2
below.
The name double is used because the number from this type has two times the
precision of the float type numbers. Sometimes it is called the variable with
double precision. In many applications, the double type is picked to represent
real numbers. This is because the float data type can only represent 7
meaningful digits (decimals). The precision of limited float data is insufficient
in most cases. One of the reasons for using it is when there is a need for quick
processing or when the real number count that needs to be stored is large.
The real number from the float type has the F suffix, for example 75.43F.
The floating point number without the suffix F such as 75.43 would be
considered double. This is because the double data type is the default data
that represents real numbers in Java. This is different from C language that uses
the float as its default data type.
We could also add the D suffix to represent the double type numbers. All the
floating point data types follow the IEEE 754 specifications. An overflow occurs
when the range error takes place and an underflow when the zero division
operation takes place.
Copyright © Open University Malaysia (OUM)
104 X TOPIC 5 BASIC CONSTRUCTS OF JAVA
5.1.3 Characters
The character data type is represented by char. The single open inverted sign (Â)
is used to show character constant.
The char data type follows the Unicode coding scheme. Unicode was created to
facilitate the programmer to deal with the non-Roman characters. As the
Unicode was invented to handle all characters existent in all the written
languages in the world, the cell size is 2 bytes. This size allows character
representation of up to 65 536 compared to the ASCII / ANSI code, which is the
1 byte code and only allows 255 character representation. Until recently, only 35
000 character codes were used.
ACTIVITY 5.1
Java has also allowed us to use the escape sequence for special characters as
shown in Table 5.3 below.
Although Java allows any Unicode character in the Applet or Java applications,
the question whether that character can be displayed on the Applet or console
depends on the support provided. For example, we cannot display the Kanji
character (a type of Japanese writing) on the machine that operates using the
Windows 95 of US version.
5.1.4 Boolean
Boolean types have two values: true and false. These literals are typed without
quotes, but they represent values, not variables. Boolean-valued expressions are
used extensively in control structures and to to test the mantic expressions.
Boolean values can also be assigned to variables of type boolean.
Boolean data type does not exist in C language. However, the non-zero value is
used to represent true and zero for false. In C++, a data type called bool is used.
It, too, can take either the true or false value. As C++ has a history that relates
closely to C, therefore the exchange between the Boolean value and integer is
allowed. This means that the integer value can still be used to test a signal. But
in Java, the exchange of the boolean value and integer is not allowed, even
though by using the casting operation. The following is an example of the use of
the Boolean data type to represent the status of a room.
class test1 {
public static void main (String args[]){
boolean dark;
dark = true;
while (dark) {
System.out.println(“Switch on lights”);
dark = false;
}//while
}//main
}//class
ACTIVITY 5.2
EXERCISE 5.1
At the end of this section, you should be able to list the types of data that could
be used in developing a Java program and differentiate the four data types that
have been discussed. In the subsequent section, we will learn how to name and
declare a variable with the appropriate data type.
Figure 2.1: Memory Location showing the Name and Value of Variable Age
Figure 2.2: Memory Location showing the Name and Value of Variables age and name
A variable in Java is designed to hold only one particular type of data; it can
legally hold that type of data and no other. The compiler will consider it to be a
syntax error if you try to violate this rule. In the previous section, you have
learned data types that could be used in a Java program. This section will
describe how to name variables to be used according to the Java specification.
Remember: Declaring a variable will involve data type and the variable name.
You must focus on the content of this section because when you fail to declare
the right variable, it will cause the Java program that has been developed unable
to be compiled and excuted if a variable is not properly declared.
The definition of letter and digit in Java encompasses a wider meaning than other
programming languages. The letter is defined as characters ÂAÊ ă ÂZÊ, ÂaÊ ă ÂzÊ, Â_Ê, Â$Ê
or any Unicode characters that symbolizes a letter in a particular language. For
example, French users can use the character ‘Ç’ in a name variable; while Greeks can
use the ‘µ’ character. The same goes for digits. Digits are from Â0Ê ă Â9Ê and any
Unicode characters that symbolizes a digit in a particular language. Symbols such as
Â+Ê or Â©Ê and also empty spaces cannot be used in the name of a variable.
Java is sensitive towards cases. This means the capital letters and the small letters
are considered different characters. There is no limit to the length of the name of
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 above does not allow empty space characters
to be used to separate words. The most popular among the programming
community is by starting the first word with a small letter and the capital letter
to start each of the next words. Character Â_Ê is not selected event though it does
not break the above rules. Below is an example of the name of a variable.
studentName, totalMarks, pricePerunit
ACTIVITY 5.3
You intend to develop a program on workers salary system. Try list down the
variables that represent the information that is going to be used.
data_type name_variable;
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
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 test8 {
public static void main (String args[]){
Answer the following questions to test your knowledge of what you have
learned in this topic.
ACTIVITY 5.4
You have known the type of comments that can be used logically. Do you
know the importance of comments in a program?
EXERCISE 5.2
State whether the variables below is valid or otherwise. For the variables
that are invalid, please state the following reasons:
(a) nameLength
(b) Name_length
(c) Import
(d) 43650BBB
(e) BBB43650
(f) touch&go
(g) touch-and-go
(h) 2nd
(i) break
(j) OUM
After reading through this section, you should be able to declare a variable with
the appropriate data type. You should also enable to differentiate the three types
of comment and how to use it.
In Java, the only way to get data into a variable is with an assignment statement.
An assignment statement in Java has the following form:
variable = expression;
Copyright © Open University Malaysia (OUM)
TOPIC 5 BASIC CONSTRUCTS OF JAVA W 113
where expression refers to data or its computation whereas variable is any name
of variable that has been declared. The expression can consist of any variable,
constant, expression or a combination of the three that is linked by the operator
such as +, -, /, * and others that can produce a value.
discount = 100;
The variable in this assignment statement is discount, and the expression is the
number 100. The computer executes this assignment statement by putting the
number 100 in the variable discount, replacing whatever was there before. Now,
consider the following assignment statement, which might come later in the same
program:
newPrice=oldPrice-discount;
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.
• If one is of the double type operant, the other operant would be changed to
double.
• On the other hand, if one of it is a float type operant, the other operant
would be changed to float.
• On the other hand, if one of it is a long type operant, the other operant
would be changed to long.
The same principle applies to integer types: int, short, and byte.
The value assigned to the ringgit is 100. Changing the floating point value to int
would cut off the decimal portion of the float point value. If we wish to round up
a floating point number to the nearest integer, use the Math.round method:
double grandTotal = 100.89;
int ringgit = (int) Math.round(grandTotal);
The sum assigned to the ringgit is 101. Note that the use of the casting
operation (int) is still needed. This is because the value returned by the round
method is a long type, and a long value can only be changed to int value
with the casting operator.
The Java compiler will not give any warning if we try to change a certain number
from one type to another, which is outside the target type range. Therefore, a
good programming practice is by testing whether the intended value to be
changed is within the target type range before change can be made.
Java allows the change in value of a particular variable from one type to another
without the casting operation following the sequence below:
byte short int long float double
and
char int
A value of a type that occurs earlier in this list can be converted automatically to
a value that occurs later. For example (Source: David J. Eck, 2006):
int A;
double X;
short B;
A = 17;
X = A; // Acceptable; A is converted to a double
B = A; // illegal; no automatic conversion
// from int to short
In some cases, you might want to force a conversion that wouldn't be done
automatically. For this, you can use casting. For example (Source: David J. Eck,
2006),
int A;
short B;
A = 17;
B = (short)A; // Acceptable; A is explicitly type cast
// to a value of type short
You can do casting from any numeric type to any other numeric type. However,
you should note that you might change the numeric value of a number by type-
casting it. You can also type-cast between the type char and the numeric types.
The numeric value of a char is its Unicode code number. For example, (char)97 is
'a', and (int)'+' is 43 (Source: David J. Eck, 2006).
EXERCISE 5.3
The following Java program has few mistakes. Rewrite the program by
correcting the mistakes.
class Error {
public static void main (String[ ] args){
width = 15
area = length * width;
System.out.println(„Area is „ + area);
}
}
After knowing of how to give initial value to the variable and performing binary
operations to numerics with different data types without data lost, you will learn
in detail on operators and operatorÊs operation that involve numeric values in the
next section.
5.4 OPERATOR
5.4.1 Arithmetic
Table 1.5 below shows the operator and operation that is used in Java. The
operation for this operator is the same as in C language.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Residue(modulo)
The / operator refers to the integer division if both operands are integers. This
means that the results obtained are integers. If otherwise, the division is division
of real numbers. The % operator meanwhile refers to the integer residue. Look at
several examples that are shown in Table 5.6 below.
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 below:
class test11 {
public static void main (String args[]){
int i = 1;
int j = 1;
int x = 7-++i;//the value of x is 5, and i becomes 2
int y = 7–j++;//the value of y is 6, and j becomes 2
}//main
}//class
Note that the values of x and y are different even though the original value of i
and j are the same. This is because the third statement, the value of i is added by 1
first before subtracting from 7 while in the last statement, the original value of j is
subtracted from 7 and then only added by 1. The use of the addition and
reduction operator in the statement can cause confusion which is difficult to
trace. Therefore, the use of this operator is not encouraged in statements such as
the examples shown above. However, it can be used in cases such as follows:
int n = 0;
n++; //alternative to n = n+ 1;
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 could not be used to compare values of
type String.
Please remember that Java uses different symbols for assignments and
equivalence tests. Assignments use symbol Â=Ê while equivalence tests use symbol
Â==Ê. For example, the value
(9 = = 6)
is false. Java avoids the possibility of the occurrence of errors arising from the use
of the symbol Â=Ê at places where the symbol Â==Ê is used.
If you use several operators in one expression, and if you don't use parentheses
to explicitly indicate the order of evaluation, then you have to worry about the
precedence rules that determine the order of evaluation.
Table 5.10 below shows the priority level of the numeric operator including
relations.
Operators on the same line have the same precedence. When they occur together,
unary operators and assignment operators are evaluated right-to-left, and the
remaining operators are evaluated left-to-right.
For example, A*B/C means (A*B)/C, while A=B=C means A=(B=C). Let us see
more examples below.
2 + 2 = 4
(Note: 4/2 will be evaluated first as the operator / has higher priority than
operator +)
6 /2 = 3
(Note: Those operands and operator in the parentheses will be evaluated first as
parentheses have the highest priority. Thus 2 + 4 in the parentheses will be
evaluated first and the result will be divided with 2).
In Java, the boolean operator "and" is represented by &&. The && operator is
used to combine two boolean values. The result is also a boolean value. The
result is true if both of the combined values are true, and the result is false if
either of the combined values is false. For example, "(x == 0) && (y == 0)" is true
if and only if both x is equal to 0 and y is equal to 0.
The boolean operator "or" is represented by ||. The expression "A || B" is true if
either A is true or B is true, or if both are true. "A || B" is false only if both A and
B are false.
Copyright © Open University Malaysia (OUM)
122 X TOPIC 5 BASIC CONSTRUCTS OF JAVA
The && and II operators are evaluated using a short cut method. This means in
evaluating the following statement:
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.
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
(h) 5.0 / 2 * 3 % 2
2. What are the values of j and k after the statement below has been
executed? Assume that value j is 5 and value k is 7 before the
statement is accomplished.
(a) k + = j;
(b) k - = j++;
(c) k * =++ j*2;
(d) k / = 25 * j --;
(e) k % = j ă 3;
In conclusion, you should have recognized the operators that could be suitably
used with arithmetic operations that will be used in a particular Java program.
• 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
the students to enable them to write a complete Java program and is free
form errors.
Boolean Expression
Boolean Operator Relational Operator
Data Types Variable
X INTRODUCTION
As highlighted in Topic 5, there are two basic aspects of programming: data and
instructions. To work with data, you need to understand variables and data
types; to work with instructions, you need to understand control structures and
methods. This Topic will focus on control structures and methods. Variables and
types have been elaborated in Topic 5.
located in the next line. This scenario is known as transfer of program control.
Bohm and Jacopini have conducted research in the 1960s and have concluded
that all programs can be written in a structured way by only using three control
structures, that is shown in Table 6.1.
Table 6.1: Three Control Stuctures
The above three structures that are capable to change the flow of control in a
program can be implemented in the Java language. The following sections with
touch on this.
What is algorithm?
A step-by-step problem-solving procedure written in natural language
such English.
In Java, the expression value is from the boolean type, that is, the
expression has true/false values. Therefore, the expression value besides
the true or false is invalid to be used in the expression.
(b) Bi-selection
Bi-selection provides other alternatives if the requisite is not fulfilled. The
following is an example of an algorithm condition, where one of the choices
is accomplished.
If your age is less than 55
Print “Still Eligible for Employment”
If_ not
Print “Compulsory retirement”
Age < 55
False True
Compulsory Retirement
else
System.out.println(“Compulsory retirement”);
if(expression)
statement 1;
else
statement 2;
Generally, the syntax in the Figure 6.2 as follows represents the if-else
statement.
Expression
False True
Statement 2
In the case of single selection, if the expression has false value, no action
will be taken. This is different with the case of bi-selection, where we are
given another alternative, that is if the expression has false value,
statement 2 will be accomplished. With reference to the above example,
if the age is or more than 55, the words ‘compulsory retirement” will
be printed.
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, i.e. System.out.println
(“Chinese”); is abandoned. The next expression is tested and found that
the value to be true, then the expression
System.out.println(“Indian”); will be accomplished and the
“Indian” string will be printed as shown in Figure 6.3 below.
False True
raceCode=M
True
raceCode=C
False
True
raceCode=I
False
Java also supports the use of the ? operator, which is sometimes very useful. The
expression
requisite ? statement1 : statement2
will accomplish statement 1 value if the requisite value is true. On the other
hand, if the requisite value is false, the expression will accomplish
statement2 value.
EXERCISE 6.1
What is the output that will be displayed by the following program segment:
r = 2;
if (r > 1)
System.out.println (“AAA”);
else System.out.println (“BBB”);
if (r < 1)
System.out.println (“AAA”);
else System.out.println (“BBB”);
if (r != 1)
System.out.println (“AAA”);
else System.out.println(“BBB”);
case constant-2:
statements-2
break;
.
. // (more cases)
.
case constant-N:
statements-N
break;
default: // optional default case
statements-(N+1)
} // end of switch statement
A switch statement allows you to test the value of an expression and, depending on
that value, to jump to some location within the switch statement. The expression
must be either integer-valued or character-valued. It cannot be a String or a real
number. The positions that you can jump to are marked with "case labels" that take
the form: "case constant:". This marks the position the computer jumps to when the
expression evaluates to the given constant. The default statement is optional to the
programmers. It provides a default jump point that is used when the value of the
expression is not listed in any case label. Following is the program segment for
testing the choice made by the menu system:
int choice = 1;
switch (choice) {
case 1: … // choose menu 1
break;
case 2: … // choose menu 2
break;
case 3: … // choose menu 3
break;
case 4: … // choose menu 4
break;
default: … // wrong input
break;
}
The break statement can also be used to force program control exit any loop
blocks.
Figure 6.4: Selection Structure in Multi Selection using switch and break
The example below shows of the use of switch statement from the previous
example of if-else if structure:
switch (raceCode){
case ‘M’: System.out.println (“Malay”); break;
case ‘C’: System.out.println (“Chinese”); break;
case‘I’ : System.out.printn (“Indian”); break;
default : System.out.println (“Others”);
}
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.
The while loop will not be accomplished at all if the expression value is
false the first time it is tested. Notice the example below to find the addition
integer from 1 to 100.
/*Find the addition of the integers 1+2+3+99+…+100*/
sum = 0;
i = 1;
while (i <= 100) {
sum += i;
i++;
}
The while loop in the above example will stop when the value i exceeds 100.
When the i value exceeds 100, the requisite (expression) will become false.
For the repetitive structure while, there are four basic components that need to be
fulfilled.
1. Initial statement.
This statement will assign initial value for the variable that will be used in
the loop. In our example, the i = 1 statement is the initial statement.
2. Stop requisite.
This requisite will be tested to determine whether the next iteration needs to
be accomplished. In the above example, i < = 100 is the stop requisite.
4. Updated Statement
Normally, this statement is placed at the end of the loop. In our example,
the control variable, which is i will be updated i++.
In contrast, the do-while loop is a variation of the while loop. Its syntax is as
below:
do {
Statement1
Statement2
……
……
StatementN
} while (condition)
For the do-while loop, the loop body will be executed first, Then condition is
evaluated. If the condition is true, the loop body will be executed. Otherwise
the loop will be terminated. The difference between while loop and do-while
loop is the order in which the condition is evaluated and the loop body
executed.
for(initial_value;requisite;update){
block_statement
}
Unlike while and do-while statements, for loop is used for the
number of loop repetitions that already known in advance.
We can give initial value to several variables that usually act as the calculator in
the first slot. Unlike C, Java allows int type variable to be declared and given its
initial value at this slot. However, it is only valid in the body or for loop block
where it is declared.
The second slot requisite is used to test the requisite that determines whether the
body of a for loop will be accomplished or not. The third slot explains is
updates that describes how to update to change the initial_value
Copyright © Open University Malaysia (OUM)
TOPIC 6 CONTROL STRUCTURE & METHOD W 137
HI
HI
HI
HI
HI
break;
In the above program, the program will exit the loop when the value of line
becomes 3 event though the requisite for the loop line <=5. The result that
will be displayed is:
HI
HI
HI
break and continue can be used in while loops and do..while loops. They
can also be used in for loops and switch statement. Note that when a break
occurs inside an if statement, it breaks out of the loop or switch statement that
contains the if statement. If the if statement is not contained inside a loop or
switch, then the if statement cannot legally contain a break statement. A
similar consideration applies to continue statements.
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?
SELF-CHECK 6.1
When using if/else, for while loops, there is one important concept that you
should know that is Compound Statement. What is Compound Statement?
We will start with two examples in order to explain the concept of compound
statements. Consider the following two examples:
Example 1:
1 int x=2;
2 if (x==2)
3 System.out.println(“Hi”);
4 System.out.println(“Hello”);
5 System.out.println(“Bye”);
Example 2:
1 int x=2;
2 if (x==3)
3 {
4 System.out.println(“Hi”);
5 System.out.println(“Hello”);
6 }
7 System.out.println(“Bye”);
Copyright © Open University Malaysia (OUM)
140 X TOPIC 6 CONTROL STRUCTURE & METHOD
Do you know why there is a difference between the output for the Example 1 and
Example2?
In Example 1, there is no braces { } for the if statement in line 2. Thus, only one
statement that follows the if statement (that is Line 3) is subjected to the
condition of line 2 (i.e. If line 2 returns a true boolean value then line 3 will be
executed where as line 3 will not be executed if line 2 returns a false value). Line
4 and 5 will be executed irrespective whether line 2 returns true or false value.
In Example 2, there is braces { } for the if statement in line 3 and line 6. All the
statements inside the braces (line 4-line 5) are subjected to the condition of line 2
(i.e. Line 4-line 5 will be executed if line 2 returns a true value whereas Line 4-
Line 5 will not be executed if line 2 returns a false value). Line 7 will be executed
irrespective whether line 2 returns true or false value because it is not inside the
braces.
Example 3:
int x=2;
int y=3;
if (x==2)
{
if (y==1)
System.out.println(“Hi”);
System.out.println(“Hello”);
}
System.out.println(“Bye”);
Example 4:
for (int a=1; a<=3; a++){
System.out.println(“Hi”);
System.out.println(“Hello”); Compound Statement
}
System.out.println(“**************”);
for (int b=1; b<=3; b++) Notice that there is no braces in
System.out.println(“Hi”); this line
System.out.println(“Hello”);
EXERCISE 6.2
What is the output that is displayed from the following program segment:
6.4 METHOD
Methods allow the programmer to modularize a program - each method will
perform a single specialized task.
Query method is used to access only the objectÊs state and this operation does not
change the state of a object. Example of this method are:
• getName()
• getPay()
• RetrieveID()
• checkPassword()
Copyright © Open University Malaysia (OUM)
TOPIC 6 CONTROL STRUCTURE & METHOD W 143
Finally, task methods is used to perform some specific task. This method may
change the state of the object. Example of this method are:
• calculateAge()
• convertToCelcius()
Line 3-5 is the declaration of a method. A Java method is a set of Java statements
which can be included inside a Java programs. Java methods are similar to
functions or procedures in other programming languages. Methods in Java could
be divided into two, namely:
• Library methods such as main(), max (x,y), sqrt(x), etc
• User defined methods written by the programmer such as method display()
shown above in Program 1.2.
Example:
int max;
if (no1>no2)
max= no1;
else Method body
max= no2;
return max;
}
Return value
The <return_type> indicates the type of value returned by the method. If the
method does not return any value, then it should be declared as void as shown
below:
public void calculateAverage(){
…..
…..
}
If the method returns a value such an int value, then the method should be
declared as int as shown in the example below:
If the method returns a value a String value, then the method should be declared
as String as shown in the example below:
The same goes for other methods that returns other data types such float, double,
char, boolean, etc. Use return statement within the method to pass back value if
the method return a value as shown in the next example:
Note that the return statement should not be included within the method if it is
void method.
Example 1:
Public int getPowerOfTwo(int no1){
int answer; /* any variable declared in a method are
local variable */
answer = no1*no1;
return answer;
}
Example 2:
/* Note that this program does not have return statement
within the method as it is a void method. */
public void calculateAverage(int no1, int no2) {
int average = no1/no2;
}
Example 3:
Public int getId(){
int id = 4567
return id;
}
Example 4:
public void displayName (String name){
System.out.println(“Your name is” + name);
}
Arguments
If a method does not return any value (i.e. it is a void method), then method must
be 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 compatible as defined in the method signature.
Example 5 below shows a complete program which has method declaration and
method invocation
Example 5:
class obj {
public static void main (String[ ] args ){
int a=67;
pass the
int b=80; value
int max=getMax(a,b);
System.out.println(„Maximum is „ + max);
}
public static int getMax(int no1, int no2){
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.
In line 5 of the above program, it will invoke the first method that will determine
the maximum value between two integer numbers. In line 6, it will invoke the
second method that will determine the maximum value between two float
numbers.
As you can see in the above program, two methods with the same name have
been declared. This approach of declaring more than one method with the same
name but with different parameter list is known as method overloading. You
cannot overload methods based on different modifiers or return types.
• Bohm and Jacopini have conducted research in the 1960s and have concluded
that all programs can be written in a structured way by only using three
control structures, namely: sequential structure, selection structure and
repetitive structure
• Sequential structure in Java could be implements using if, if-else, if-else if and
switch statements
break method
case nested loops
continue Repetitive Structure
do-while Selestion Structure
for Sequential Structure
if switch
if-else while
X INTRODUCTION
A program is a sequence of instructions that a computer can execute to perform
some tasks. There are two basic blocks of programming: data and instructions.
To work with data, you need to understand variables and data types; to work
with instructions, you need to understand control structures and methods. All
these have been elaborated in Topic 5 and Topic 6.
Like other programming languages, there are also THREE other important
constructs in Java as listed as follow:
• Array
• String
• Input Reading
• Process the marks of 100 students and determine the highest and lowest
marks
• Determine number of characters in a String
• Enable an user to key in data during program run-time
7.1 ARRAY
Array is a group of memory locations that are connected and has the same
name and data type.
„You have been required to write a program that will accept and store the
marks for 5 students‰
For the above problem, you are just required to declare five variables type of
integer as shown below to store the studentsÊ marks:
int student1, student2, student3, student4, student5;
„You have been required to write a program that will accept and store the
marks for 500 students‰
For the above problem, are you going to declare 500 variables as shown below:
It is very obvious that the above approach to write 500 variables is „tiring‰
and it is not a good approach. The solution is to use array:
int[] student = new int [500];
Do not worry if you donÊt understand the above declaration because we are
going to discuss it in a short while.
We need to state the name of the array and the location in order to refer a
particular memory location in the array. Figure 7.1 shows a visual representation
of an array.
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:
int[] number = { 3, 5, 4, 0};
char[] letter = {‘A’, ‘B’, ‘Z’, ‘E’};
Number[0] 3
Number[1] 5
Number[2] 4
Number[3] 0
letter[0] A
letter[1] B
Letter[2] Z
letter[3] E
Notice that in the two examples above, the new operator is not used. We can also
give an initial value to an array that has no name definition as shown below:
This statement will allocate a new array and add the value in parenthesis { }. The
sum of initial value will be calculated and the array size is determined according
to that sum. This type of syntax is used if we wish to send an array as a
parameter to a particular method without creating a localized variable for it. For
example:
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;
length is an attribute for the array that stores information on the size of the
array. For example:
int[] evenNum = { 2, 4, 6, 8, 10};
for (i = 0; i < evenNum.length;i++)
System.out.println(evenNum[i]);
Here evenNum.length is the size for the array evenNum. By referring to the
evenNum array above, this means that the value for evenNum.length is 5.
Therefore, the for loop above will be executed five times and will print the
contents of the evenNum array beginning from the index 0 to evenNum.length-
1, that is 4.
The following is an example of the program segment that shows how three out of
five values copied from the evenNum array to the newNum array.
arraycopy() method was used to copy the evenNum array element starting
from index 1 position. The number of elements copied is three, therefore the
elements that are copied are 4, 6, 8. These elements that are copied are then
stored in the evenNum array starting from the index 2 position. Therefore, the
newNum[2] element, newNum[3] and newNum[4] each would be replaced by
the values 4, 6 and 8. The figure below shows the memory space for both arrays
after the above program segment is executed:
The effect obtained is both arrays refer to a set of the same data. Changes in
one of the arrays will affect both arrays. The visual below will help you to
understand this explanation:
array1
Index Value
0 12
1 33
2 45
array2
Observe that array1 and array2 are pointing to the same memory location.
EXERCISE 7.1
1. Each declaration in the table as follows contains error. Give reason for
the error.
(a) int intA[ ] = new double[10];
(b) int intA[ ] = new int[1.5];
(c) double doubleA = newdouble [-10];
(d) int intMatrik[ ][ ] = new int[10];
2. Assume that the declaration below was made and state whether It is
valid or otherwise and give the reasons
int j[ ] = new int [10];
char k [] = new char[6];
int x = 7, y = 2;
double m = 0.0;
(a) j[0]
(b) k[0]
(c) c[1.0]
(d) k[‘j’]
(e) k[j]
(f) j[x + y]
(g) j[x % y]
(h) j[10]
(i) c[-1]
(j) j[j [4] ]
3. The following program will create an array and then values will be
assigned to this array. These values will be displayed. Observe the
usage of the for command in the program. In your opinion, what will
be the output? Compare your answer with the computerÊs output.
arraycopy class {
public static void main (String[ ] args){
//assign values for each element and display the content for
(int i=0; i< 10; i++){
anArray[i]=i*2;
System.out.println( anArray[i] + „ „);
} //for
}//main
} //class
7.2 STRING
The character string, which is a combination of individual characters, is
implemented as a string class. We no longer need to declare a variable that stores
character string values as char type array. String constant consists of character
strings that are in between two inverted signs „ „. This includes the empty space
character that separates the words. Words, digits and special characters such as +,
-, *, /, $, etc could be assigned to String variable in Java.
SELF-CHECK 7.1
You have already learned about arrays. Do you know the difference between
array and String?
Like Array, String is implemented as an object. Thus, we only need to know how
to use it without having to know how it is implemented.
In the above example, the use of the Â+Ê operator will produce myName
character string with the value ”FirdausMohd”. Note that there is no
empty space in this string. The Â+Ê operator only acts to combine two strings
according to the sequence that is stated.
The call for substring() method in the above example pass two
parameters, that is 0 and 10. The second parameter is the first position in
the IPTS string that we do not intend to copy. In this case, what we intend
to accomplish is to copy the character from position 0 to 9. Therefore, the
substring() method will calculate from position 0 (included) to
position 10 (excluded).
d) String Comparison
To test whether two strings have the same value, we can use equals()
method. The expression
s.equals(r)
returns the true value if s and r strings are the same and false if
otherwise. s and r can be either constant or string variable.
“Greetings”.equals(IPTS)
Never use Â==Ê operator to compare two strings. This operation will only
check whether both strings are stored in the same location. Definitely the
string stored at the same location will have the same value. But we can also
store many strings that have the same value at different locations.
ACTIVITY 7.1
EXERCISE 7.2
Seeing that it is difficult for a new programmer learning the Java language to
write Java program that using InputStream class to capture input, we have
prepared a simple class to read input integer, character, real numbers, character
or strings. This class is named Pembaca class.
All the Java applications that involve input reading in this module will use Pembaca
class. You can download this Pembaca class from myLMS in order to use it in your
program. Make sure you copy this class to the directory jdk1.x.x/bin in your PC. The
program will not function properly if Pembaca class is not copied to this directory.
We will look at the details of the Pembaca Class. This class has methods
(that are defined in this class) which are allocated to read certain types of data.
These methods are called member methods.
• bacaFloat() method
• bacaFloat () method
• bacaDouble()method
• bacaLong()method
• bacaShort() method
• bacaChar() method
• bacaString() method
The following is an example of a program that uses Pembaca Class to read input:
Now the memory space size for Pembaca Class is assigned and the variable
read is now referred or shows to that memory space. To use the methods defined
in that class, we can call the method in Table 7.1 by the following syntax:
read.method_name;
For example, to call bacaInt() method, the call has to be in the form
read.bacaInt();. As this method returns the value int that is input by the
user, thus the call should be in the form assignment as shown in line 14 that is
integerValue = read.bacaInt();. Next, we can manipulate the value
input whether to print or to use in arithmetic operations.
EXERCISE 7.3
Write a Java program that will accept three integer numbers from an user
and display the maximun number among these three inputs.
We can use the command from the library class DecimalFormat to format the
numbers.
As a example, the statement as follows will display the first three digits after the
decimal point.
The statement below will display three digits of a number as an output. If the
number is less than three digits, then 0 will be appended at the front. If the digits
of a number is greater than three, then all the digits in the number will be
displayed.
System.out.println(num.format(papar));
System.out.println(num.format(18));
System.out.println(num.format(124));
System.out.println(num.format(23455));
}
}
Now, replace the following statements to the statements that have been bolded in
the above program.
Can you see any difference in the output upon executing the program?
• To work with data, you need to understand variables and data types.
• This topic has focuses on array, String and how to capture input from user
during program runtime.
• Array is a group of memory locations that are connected and has the same
name and data type.
• An interesting thing in writing the Java program is that the reading input
process from the keyboard is not as simple as expected.
• Thus, we have prepared class Pembaca for you so that that it could be used
to develop interactive programs.
Array String
Pembaca Class
Answers
Suggested Answers to Exercises for Topic 2
Exercise 2.1
(a) functional
(b) non-functional
(c) functional
(d) non-functional
(e) could be regarded as either
Exercise 2.2
Functional requirements:
Ć register members
Ć track overdue videos
Ć produce a daily upload file for the general ledger
Ć print letters for members on their birthdays.
Non-functional requirements:
Ć speed of the system should allow a video borrowing transaction to be
completed within one minute
Ć the barcode reader should be at least 99.5% accurate
Ć a front desk clerk should be able to become familiar with all the functions of
the system within one week.
Exercise 2.3
Front desk clerk · primary · This actor deals with the members · joining,
borrowing videos, asking questions.
Back office clerk · primary · This actor deals with all the back office functions,
such as sending data to the general ledger system. (Will probably find later that
this ÂactorÊ is actually several actors.)
Management · secondary, as their reporting needs are met from the data
warehouse. Need sufficient information to run the business.
Security manager · primary · maintains the user names to control access to the
system.
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
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?
Ć How are the members going to identify themselves?
Ć Tell me about stocktakes. What are the issues? What are you trying to
achieve?
Ć Who will support and maintain the system?
Ć Have you thought about transferring the data from the old system to the new
system?
Ć Is any auditing required?
Exercise 2.11
Later in the unit we show you a way for dealing with large systems with
hundreds of use cases.
Exercise 2.12
Exercise 2.14
Perhaps you can already envisage the answer, but letÊs work through it slowly.
We need a use case to sell old videos. So hereÊs our first version.
What do you notice about the last line? ItÊs 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
And 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 (e.g. total number
borrowed, total number of overdues, current
number borrowed, current number overdues)
Optionally, the user can Store the changes
modify the personal details
of the member
Optionally, the user can Check that the borrower has nothing borrowed
delete the member Delete the member
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
Exercise 2.17
Exercise 2.18
Exercise 2.19
Exercise 2.20
Exercise 3.1
The most obvious entity that we wish to track is each Video Tape.
The other entity for which a state diagram could be useful is the class Member.
The problem discussion did not mention that if a member has too many
overdues, then she is not allowed to borrow, but this is the sort of fact that should
be verified with individual users if a state diagram is used.
As we stated, it is not wrong to draw state diagrams for other classes, it is simply
that they will be very simple and you will not learn from them. But of course the
best way to find this out is to draw them.
Exercise 3.2
The first version for the state diagram for Video Tape might look like this:
Borrow Videos
On-Shelf Borrowed
Return Videos
Then you could think about how a video tape comes into existence. Clearly we
are missing a use case here · letÊs call it Get New Video Tapes.
And what about the final state? An initial answer could be to create another new
use case, this time called Retire Video Tapes. Clearly we have uncovered new
functionality and would need to go back to the users to discuss this. For example,
perhaps they try to sell some old video tapes.
Lastly, letÊs think about lost or missing video tapes. Once again, we would need
to discuss this with Victoria, and the answer could be the following.
Record Stocktake
Findings Write-off
Video Tape
Exercise 3.3
Exercise 3.4
Exercise 3.5
Exercise 3.6
Exercise 5.2
(a) valid
(b) valid
(c) not valid
reserve word
(d) not valid
it starts with digit
(e) valid
(f) not valid
it has Â&Ê character
(g) not valid
it has Â-Â character
(h) not valid
it starts with digit
(i) not valid
reserve word
(j) valid
Exercise 5.3
class hasErrors {
public static void main (String[ ] args){
int width=15; //any values is acceptable
int length=20; //any values is acceptable
int area=length +width;
System.out.println("Area is " + area);
}
}
Exercise 5.4
1. (a) 34.0
(b) 54
(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
Output:
AAA
BBB
AAA
Exercise 6.2
a. 0
6
12
18
24
30
36
b. 1
8
15
22
29
36
43
1. (a) intA is declared as integer array but was assigned with double array.
(b) The array size must be an integer value
(c) doubleA is declared as double but was assigned with double array.
Also, the size of the array cannot be negative.
(d) intMatriks is declared as two dimensional array but was assigned with
one dimensional array
2. (a) valid
(b) valid
(c) not valid
(d) valid
(e) not valid
(f) valid
(g) valid
(h) not valid
(i) not valid
(j) valid based on the syntax
3. Output:
0
2
4
6
8
10
12
14
16
18
Exercise 7.2
1. (a) 32
(b) e
2. Output:
s1: hello there
Length of s1: 11
The string reversed is: e r e h t o l l e h
The character array is: hello
Exercise 7.3
import java.io.*;
class Maks {
public static void main( String args[ ] ) throws IOException
{
int temp, maks;
Pembaca read = new Pembaca();
System.out.println("Enter first number:");
int no1=read.bacaInt();
if (no1>no2)
temp=no1;
else
temp=no2;
if (temp>no3)
maks=temp;
else
maks=no3;
}//main
}//class
References
Addison-Wesley. (This is a great reference for UML, providing more detail than
you will ever need.)
Eriksson, H.-E. and Penkus, M. (2000) Business Modelling with UML · Business
Patterns at Work, Wiley.
Fowler, M. and Scott, K. (2000). UML Distilled, 2nd edn, Addison-Wesley. (This is
a short and practical overview to using UML in actual practice.)
Scott, K. (2001). UML Explained, Addison-Wesley. (This book presents the basics
of UML.).
OR
Thank you.