CBLM - Perform Java OOP
CBLM - Perform Java OOP
CO
ES PO
ACES
L L E GE
Page i
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page ii
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
HOW TO USE THIS COMPETENCY-BASED LEARNING
MATERIAL
Welcome!
This unit of competency, Perform object-oriented analysis and
design in Java technology, is one of the competencies of PROGRAMMING
(JAVA) NC III, a course which comprises the knowledge, skills and attitudes
required for a TVET trainee to possess.
The module, Performing Object-Oriented Analysis and Design in
Java Technology, contains training materials and activities related to apply
basics of Java language, work with methods and encapsulation, work with
inheritance and handling exceptions, examine object-oriented concepts and
terminology, explain modeling and software development process, create use
case diagrams and use case scenarios, transition analysis to design using
interaction diagrams, and introduce architectural concepts and architecture
tiers diagrams for you to complete.
In this module, you are required to go through a series of learning
activities in order to complete each learning outcome. In each learning
outcome are Information Sheets, Self-Checks, Task Sheets and Job Sheets.
Follow and perform the activities on your own. If you have questions, do not
hesitate to ask for assistance from your trainer.
Remember to:
Read information sheets and complete self-checks. Suggested
references are included to supplement the materials provided in this
module.
Perform the Task Sheets and Job Sheets until you are confident that
your outputs conform to the Performance Criteria Checklist that
follows the sheets.
Submit outputs of the Task Sheets and Job Sheets to your trainer for
evaluation and recording in the Accomplishment Chart. Outputs
shall serve as your portfolio during the Institutional Competency
Evaluation. When you feel confident that you have had sufficient
practice, ask your trainer to evaluate you. The results of your
assessment will be recorded in your Progress Chart and Achievement
Chart.
You must pass the Institutional Competency Evaluation for this
competency for issuance of Certificate of Achievement to be awarded to
you after passing the evaluation.
CO
ES PO
ACES
L L E GE
Page iii
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
PROGRAMMING (JAVA) NC III
Competency-Based Learning Materials
List of Competencies
Performing object-
Perform object-oriented
oriented analysis and
1. analysis and design in ICT313359
design in Java
Java technology
technology
CO
ES PO
ACES
L L E GE
Page iv
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
TABLE OF CONTENTS
CO
ES PO
ACES
L L E GE
Page v
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
INFORMATION SHEET 1.4-1 OBJECT-ORIENTED PROGRAMMING CONCEPTS ........ 113
SELF-CHECK 1.4-1 ..................................................................................................................................... 116
ANSWER KEY 1.4-1 ..................................................................................................................................... 117
LEARNING OUTCOME NO. 5 EXPLAIN MODELING AND SOFTWARE DEVELOPMENT
PROCESS ................................................................................................................ 118
INFORMATION SHEET 1.5-1 SOFTWARE DEVELOPMENT LIFE CYCLE (SDLC) ........ 119
SELF-CHECK 1.5-1 ..................................................................................................................................... 123
ANSWER KEY 1.5-1 ..................................................................................................................................... 124
INFORMATION SHEET 1.5-2 SDLC MODELS ........................................................... 125
SELF-CHECK 1.5-2 ..................................................................................................................................... 145
ANSWER KEY 1.5-2 ..................................................................................................................................... 146
LEARNING OUTCOME NO. 6 CREATE USE CASE DIAGRAMS AND USE CASE
SCENARIOS............................................................................................................. 147
INFORMATION SHEET 1.6-1 USE CASE DIAGRAM AND SCENARIOS ....................... 148
SELF-CHECK 1.6-1 ..................................................................................................................................... 154
ANSWER KEY 1.6-1 ..................................................................................................................................... 155
LEARNING OUTCOME NO. 7 TRANSITION ANALYSIS TO DESIGN USING INTERACTION
DIAGRAMS .............................................................................................................. 156
INFORMATION SHEET 1.7-1 UNIFIED MODELING LANGUAGE (UML) OVERVIEW AND
BASIC NOTATION .................................................................................................... 157
SELF-CHECK 1.7-1 ..................................................................................................................................... 172
ANSWER KEY 1.7-1 ..................................................................................................................................... 173
INFORMATION SHEET 1.7-2 UML DIAGRAMS ......................................................... 174
SELF-CHECK 1.7-2 ..................................................................................................................................... 202
ANSWER KEY 1.7-2 ..................................................................................................................................... 203
LEARNING OUTCOME NO. 8 INTRODUCE ARCHITECTURAL CONCEPTS AND
ARCHITECTURE TIERS DIAGRAMS ......................................................................... 204
INFORMATION SHEET 1.8-1 JAVA ENTERPRISE SYSTEM SOLUTION ARCHITECTURES
............................................................................................................................... 205
SELF-CHECK 1.8-1 ..................................................................................................................................... 220
ANSWER KEY 1.6-1 ..................................................................................................................................... 221
BIBLIOGRAPHY ....................................................... ERROR! BOOKMARK NOT DEFINED.
CO
ES PO
ACES
L L E GE
Page vi
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
PROGRAMMING (JAVA) NC III
Sector : ICT
CO
ES PO
ACES
L L E GE
Page i
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
MODULE CONTENT
CO
ES PO
ACES
L L E GE
Page 2
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
ASSESSMENT CRITERIA:
Executable Java applications are created in accordance with Java
framework
Java packages are imported to make them accessible in the code
Working with Java Data types is demonstrated in accordance with
Java framework
Using Operators and Decision Constructs is demonstrated in
accordance with Java framework
Creating and Using Arrays is demonstrated in accordance with Java
framework
Using Loop Constructs is demonstrated in accordance with Java
framework
Methods with arguments and return values are created in
accordance with Java framework
Static keywords are applied to methods and fields in accordance with
Java framework
Overloaded method is created in accordance with Java framework
Access modifiers are applied in accordance with Java framework
Encapsulation principled are applied to a class in accordance with
Java framework
Inheritance is implemented in accordance with Java framework
Code that demonstrates the use of polymorphism is developed in
accordance with Java framework
Super and this syntax are used to access objects and constructors
in accordance with Java framework
Abstract classes and interfaces are used in accordance with Java
framework
How exceptions alter normal program flow are determined by
creating a try-catch block.
CO
ES PO
ACES
L L E GE
Page 3
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
LEARNING OUTCOME NO. 1 Apply basics of Java
language
Contents:
1. Basics of a Java program
History
Creating Java program
Data types
Operators
2. Selection control structure
3. Repetition control structure
4. Arrays
Assessment Criteria:
1. Executable Java applications are created in accordance with Java
framework
2. Java packages are imported to make them accessible in the code
3. Working with Java Data types is demonstrated in accordance with
Java framework
4. Using Operators and Decision Constructs is demonstrated in
accordance with Java framework
5. Creating and Using Arrays is demonstrated in accordance with
Java framework
6. Using Loop Constructs is demonstrated in accordance with Java
framework
Conditions:
PC or workstation
Programming tools
Reference Book s
Handouts/Modules/Printed Materials
Assessment Method:
Oral recitation
Written examinations
Case Study (Defense)
CO
ES PO
ACES
L L E GE
Page 4
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.1-1 Introduction to Java and Basics of
a Java Program
Learning Objectives:
After reading this information sheet, you must be able to:
1. Review types of software
2. Define what is programming language
3. Familiarize steps in creating Java program
4. Create a simple Java program
5. Identify errors in Java program
6. Enumerate data types in Java
7. Enumerate and apply arithmetic operators in mathematical
expressions
Software are created to perform specific task. In your previous lessons,
you learned that there are three categories of software:
(1) application software;
(2) system software; and
(3) programming languages.
System software are those that are used to manage computers and
allow communication among the hardware components of the computer
system as it operates. Examples of system software include:
(1) operating systems
(a) Windows XP,
(b) Windows 7,
(c) Windows 8,
(d) Ubuntu Linux, and
(e) MAC OS
(2) Utilities like antivirus software that is responsible for mantaining
the security of your computer system and optimizing system
performance.
CO
ES PO
ACES
L L E GE
Page 5
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
JAVA HISTORY
In this section, the plan is to lead you into the world of Java programming by
taking you through the basic steps required to get a simple program running.
The Java system is a collection of applications, not unlike many of the other
applications that you are accustomed to using (such as your word processor,
email program, and internet browser). As with any application, you need to
be sure that Java is properly installed on your computer. It comes preloaded
on many computers, or you can download it easily. You also need a text editor
and a terminal application. Your first task is to find the instructions for
installing such a Java programming environment on your computer by
installing Kava Development Kit which is downloadable at .
PROGRAMMING IN JAVA
To introduce you to developing Java programs, we break the process
down into three steps. To program in Java, you need to:
1. Create a program by typing it into a file named, say, MyCode.java.
2. Compile it by typing javac MyCode.java in a terminal window.
3. Run (or execute) it by typing java MyCode in the terminal window.
In the first step, you start with a blank screen and end with a sequence
of typed characters on the screen, just as when you write an email message
or a paper. Programmers use the term code to refer to program text and the
term coding to refer to the act of creating and editing the code. In the second
step, you use a system application that compiles your program (translates it
into a form more suitable for the computer) and puts the result in a file named
MyCode.class. In the third step, you transfer control of the computer from the
system to your program (which returns control back to the system when
finished). Many systems have several different ways to create, compile, and
execute programs. We choose the sequence described here because it is the
simplest to describe and use for simple programs.
CO
ES PO
ACES
L L E GE
Page 6
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Creating a program. A Java program is nothing more than a sequence of
characters, like a paragraph or a poem, stored in a file with a .java extension.
To create one, therefore, you need only define that sequence of characters, in
the same way as you do for email or any other computer application. You can
use any text editor for this task, or you can use one of the more sophisticated
program development environments described on the booksite. Such
environments are overkill for the sorts of programs we consider in this book,
but they are not difficult to use, have many useful features, and are widely
used by professionals.
Executing a program. Once you compile the program, you can run it. This
is the exciting part, where your program takes control of your computer
(within the constraints of what the Java system allows). It is perhaps more
accurate to say that your computer follows your instructions. It is even more
accurate to say that a part of the Java system known as the Java Virtual
Machine (the JVM, for short) directs your computer to follow your
instructions. To use the JVM to execute your program, type the java command
followed by the program name in a terminal window.
CO
ES PO
ACES
L L E GE
Page 7
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Program 1. Hello World
CO
ES PO
ACES
L L E GE
Page 8
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
statements. The first statement calls on System.out.print() to print in the
terminal window the message
between the quotation marks,
and the second statement calls
on System.out.println() to
terminate the line. Since the
1970s, it has been a tradition
that a beginning programmers
first program should print "Hello,
World". So, you should type the
code in PROGRAM 1 into a file,
compile it, and execute it. By
doing so, you will be following in
the footsteps of countless others who have learned how to program. Also, you
will be checking that you have a usable editor and terminal application. At
first, accomplishing the task of printing something out in a terminal window
might not seem very interesting; upon reflection, however, you will see that
one of the most basic functions that we need from a program is its ability to
tell us what it is doing. For the time being, all our program code will be just
like PROGRAM 1, except with a different sequence of statements in main().
Thus, you do not need to start with a blank page to write a program. Instead,
you can
Copy HelloWorld.java into a new file having a new program name of
your choice, followed by .java.
Replace HelloWorld on the first line with the new program name.
Replace the System.out.print() and System.out. println() statements
with a different sequence of statements (each ending with a semicolon).
Your program is characterized by its sequence of statements and its
name. Each Java program must reside in a file whose name matches the one
after the word class on the first line, and it also must have a .java extension.
Errors. It is easy to blur the distinction among editing, compiling, and
executing programs. You should keep them separate in your mind when you
are learning to program, to better understand the effects of the errors that
inevitably arise. You can find several examples of errors in the Q&A at the end
of this section. You can fix or avoid most errors by carefully examining the
program as you create it, the same way you fix spelling and grammatical
errors when you compose an email message. Some errors, known as compile-
time errors, are caught when you compile the program, because they prevent
the compiler from doing the translation. Other errors, known as run-time
errors, do not show up until you execute the program. In general, errors in
programs, also commonly known as bugs, are the bane of a programmers
existence: the error messages can be confusing or misleading, and the source
of the error can be very hard to find. One of the first skills that you will learn
CO
ES PO
ACES
L L E GE
Page 9
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
is to identify errors; you will also learn to be sufficiently careful when coding,
to avoid making many of them in the first place.
CO
ES PO
ACES
L L E GE
Page 10
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Definitions To talk about data types, we need to introduce some terminology.
To do so, we start with the following code fragment:
int a, b, c;
a = 1234;
b = 99;
c = a + b;
The first line is a declaration that declares the names of three variables to be
the identifiers a, b, and c and their type to be int. The next three lines are
assignment statements that change the values of the variables, using the
literals 1234 and 99, and the expression a + b, with the end result that c has
the value 1333. Identifiers. We use identifiers to name variables (and many
other things) in Java. An identifier is a sequence of letters, digits, _, and $,
the first of which is not a digit. The sequences of characters abc, Ab$, abc123,
and a_b are all legal Java identifiers, but Ab*, 1abc, and a+b are not.
Identifiers are case-sensitive, so Ab, ab, and AB are all different names. You
cannot use certain reserved wordssuch as public, static, int, double, and so
forthto name variables.
Literals. A literal is a source-code representation of a data-type value. We
use strings of digits like 1234 or 99 to define int literal values, and add a
decimal point as in 3.14159 or 2.71828 to define double literal values. To
specify a boolean value, we use the keywords true or false, and to specify a
String, we use a sequence of characters enclosed in quotes, such as "Hello,
World". We will consider other kinds of literals as we consider each data type
in more detail. Variables. A variable is a name that we use to refer to a data-
type value. We use variables to keep track of changing values as a
computation unfolds. For example, we use the variable n in many programs
to count things. We create a variable in a declaration that specifies its type
and gives it a name. We compute with it by using the name in an expression
that uses operations defined for its type. Each variable always stores one of
the permissible data-type values.
Declaration statements. A declaration statement associates a variable name
with a type at compile time. Java requires us to use declarations to specify
the names and types of variables. By doing so, we are being explicit about any
computation that we are specifying. Java is said to be a strongly-typed
language, because the Java compiler can check for consistency at compile
time (for example, it does not permit us to add a String to a double). This
situation is precisely analogous to making sure that quantities have the
proper units in a scientific application (for example, it does not make sense to
add a quantity measured in inches to another measured in pounds).
Declarations can appear anywhere before a variable is first usedmost often,
we put them at the point of first use.
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 11
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Assignment statements. An assignment statement associates a data-type
value with a variable. When we write c = a + b in Java, we are not expressing
mathematical equality, but are
instead expressing an action: set
the value of the variable c to be
the value of a plus the value of b.
It is true that c is mathematically
equal to a + b immediately after
the assignment statement has
been executed, but the point of the
statement is to change the value
of c (if necessary). The left-hand
side of an assignment statement
must be a single variable; the
right-hand side can be an
arbitrary expression that
produces values of the type. For example, we can say discriminant = b*b -
4*a*c in Java, but we cannot say a + b = b + a or 1 = a. In short, the meaning
of = is decidedly not the same as in mathematical equations. For example, a
= b is certainly not the same as b = a, and while the value of c is the value of
a plus the value of b after c = a + b has been executed, that may cease to be
the case if subsequent statements change the values of any of the variables.
Initialization. In a simple declaration, the initial value of the variable is
undefined. For economy, we can combine a declaration with an assignment
statement to provide an initial value for the variable.
Tracing changes in variable values. As a final check on your
understanding of the purpose of assignment statements, convince yourself
that the following code exchanges the values of a and b (assume that a and b
are int variables):
int t = a;
a = b;
b = t;
To do so, use a time-honored method of
examining program behavior: study a table
of the variable values after each statement
(such a table is known as a trace).
Expressions. An expression is a literal, a
variable, or a sequence of operations on
literals and/or variables that produces a value. For primitive types,
expressions look just like mathematical formulas, which are based on familiar
symbols or operators that specify data-type operations to be performed on one
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 12
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
or more operands. Each operand can be any
expression. Most of the operators that we use are
binary operators that take exactly two operands,
such as x + 1 or y / 2. An expression that is
enclosed in parentheses is another expression with
the same value. For example, we can write 4 * (x -
3) or 4*x - 12 on the right-hand side of an
assignment statement and the compiler will
understand what we mean.
CO
ES PO
ACES
L L E GE
Page 13
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
are both the same: they assign to c the value "123499". We use this automatic
conversion liberally to form String values for System.out.print() and System.
out.println() for output. For example, we can write statements like this one:
CO
ES PO
ACES
L L E GE
Page 14
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
function that describes the relative lengths of the marks on a ruler. One
noteworthy feature of this computation is that it illustrates how easy is is to
craft short programs that produce huge amountsof output. If you extend this
program in the obvious way to print five lines, six lines, seven lines, and so
forth, you will see that each time you add just two statements to this program,
you increase the size of its output by precisely one more than a factor of two.
Specifically, if the program prints n lines, the nth line contains 2n!1 numbers.
For example, if you were to add statements in this way so that the program
prints 30 lines, it would attempt to print more than 1 billion numbers.
CO
ES PO
ACES
L L E GE
Page 15
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
beginning (that, when interpreted as decimal numbers, fall within the defined
range), are integer literal values. We use ints frequently because they
naturally arise when implementing programs. Standard arithmetic operators
for addition/ subtraction (+ and -), multiplication (*), division (/), and
remainder (%) for the int data type are built in to Java. These operators take
two int operands and produce an int result, with one significant exception
division or remainder by zero is not allowed. These operations are defined just
as in grade school (keeping in mind that all results must be integers): given
two int values a and b, the value of a / b is the number of times b goes into a
with the fractional part discarded, and the value of a % b is the remainder
that you get when you divide a by b. For example, the value of 17 / 3 is 5,
and the value of 17 % 3 is 2. The int results that we get from arithmetic
operations are just what we expect, except that if the result is too large to fit
into ints 32-bit representation, then it will be truncated in a well-defined
manner. This situation is known as overflow. In
CO
ES PO
ACES
L L E GE
Page 16
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
PROGRAM 3 illustrates basic operations for manipulating integers,
such as the use of expressions involving arithmetic operators. It also
demonstrates the use of Integer.parseInt() to convert String values on the
command line to int values, as well as the use of automatic type conversion
to convert int values to String values for output.
Three other built-in types are different representations of integers in
Java. The long, short, and byte types are the same as int except that they use
64, 16, and 8 bits respectively, so the range of allowed values is accordingly
different. Programmers use long when working with huge integers, and the
other types to save space.
Floating-point numbers
The double type is for representing floating-point numbers, for use in
scientific and commercial applications. The internal representation is like
scientific notation, so that we can compute with numbers in a huge range. We
use floating-point numbers to
represent real numbers, but they are
decidedly not the same as real
numbers! There are infinitely many
real numbers, but we can only
represent a finite number of floating-
points in any digital computer
representation. Floating-point
numbers do approximate real
numbers sufficiently well that we can
use them in applications, but we often
need to cope with the fact that we
cannot always do exact computations.
We can use a sequence of digits with a decimal point to type floating-
point numbers. For example, 3.14159 represents a six-digit approximation to
#. Alternatively, we can use a notation like scientific notation: the literal
6.022e23 represents the number 6.022 $ 1023. As with integers, you can use
these conventions to write floating-point literals in your programs or to
provide floating-point numbers as string parameters on the command line.
The arithmetic operators +, -, *, and / are defined for double. Beyond
the built-in operators, the Java Math library defines the square root,
trigonometric
CO
ES PO
ACES
L L E GE
Page 17
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
functions, logarithm/exponential functions, and other common functions for
floating-point numbers. To use one of these values in an expression, we write
the name of the function followed by its argument in parentheses. For
example, you can use the code Math.sqrt(2.0) when you want to use the
square root of 2 in an expression.
When working with floating point numbers, one of the first things that
you will encounter is the issue of precision: 5.0/2.0 is 2.5 but 5.0/3.0 is
1.6666666666666667. In SECTION 1.5, you will learn Javas mechanism for
controlling the number of significant digits that you see in output. Until then,
we will work with the Java default output format.
The result of a calculation can be one of the special values Infinity (if
the number is too large to be represented) or NaN (if the result of the
calculation is undefined). Though there are myriad details to consider when
calculations involve these values, you can use double in a natural way and
begin to write Java programs instead of using a calculator for all kinds of
calculations.
For example, PROGRAM 1.2.3 shows the use of double values in
computing the roots of a quadratic equation using the quadratic formula.
Several of the exercises at the end of this section further illustrate this point.
As with long, short, and byte for integers, there is another representation for
real numbers called float. Programmers sometimes use float to save space
when precision is a secondary consideration. The double type is useful for
about 15 significant digits; the float type is good for only about 7 digits. We
do not use float in this module.
Booleans
The boolean type has just two values: true and false. These are the two
possible boolean literals. Every boolean variable
has one of these two values, and every boolean
operation has operands and a result that takes
on just one of these two values. This simplicity
is deceiving boolean values lie at the
foundation of computer science.
The most important operations defined
for booleans are and (&&), or (||), and not (!),
which have familiar definitions:
a && b is true if both operands are true, and false if either is false.
a || b is false if both operands are false, and true if either is true.
!a is true if a is false, and false if a is true.
CO
ES PO
ACES
L L E GE
Page 18
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Despite the intuitive nature of these definitions, it is worthwhile to fully
specify each possibility for each operation in tables known as truth tables.
The not function
has only one operand: its value for each of the two possible values of the
operand is specified in the second column. The and and or functions each
have two operands: there are four different possibilities for operand input
values, and the values of the functions for each possibility are specified in the
right two columns. We can use these operators with parentheses to develop
arbitrarily complex expressions, each of which specifies a well-defined boolean
function. Often the same function appears in different guises. For example,
the expressions (a && b) and !(!a || !b) are equivalent.
The study of manipulating expressions of this kind is known as
Boolean logic. This field of mathematics is fundamental to computing: it plays
an essential role in the design and operation of computer hardware itself, and
it is also a starting point for the theoretical foundations of computation. In
the present context, we are interested in boolean expressions because we use
them to control the behavior of our programs. Typically, a particular condition
of interest is specified as a boolean expression and a piece of program code is
written to execute one set of statements if the expression is true and a
different set of statements if the expression is false.
Type conversion
One of the primary rules of modern programming is that you should always
be aware of the type of data that your program is processing. Only by knowing
the type can you know precisely which set of values each variable can have,
which literals you can use, and which operations you can perform. Typical
programming tasks involve processing multiple types of data, so we often need
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 19
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
to convert data from one type to another. There are several ways to do so in
Java.
Explicit type conversion. You can use a method that takes an argument of
one type (the value to be converted) and produces a result of another type. We
have already used the Integer.parseInt() and Double.parseDouble() library
methods to convert String values to int and double values, respectively. Many
other methods are available for conversion among other types. For example,
the library method Math.round() takes a double argument and returns a long
result: the nearest integer to the argument. Thus, for example,
Math.round(3.14159) and Math.round(2.71828) are both of type long and
have the same value (3).
Explicit cast. Java has some built-in type conversion conventions for
primitive types that you can take advantage of when you are aware that you
might lose information. You have to make your intention to do so explicit by
using a device called a cast. You cast an expression from one primitive type
to another by prepending the desired type name within parentheses. For
example, the expression (int) 2.71828 is a cast from double to int that
produces an int with value 2. The conversion methods defined for casts throw
away information in a reasonable way. For example, casting a floating-point
number to an integer discards the fractional part by rounding towards zero.
If you want a different result, such as rounding to the nearest integer, you
must use the explicit conversion method Math.round(), as just discussed (but
you then need to use an explicit cast to int, since that method returns a long).
RandomInt (PROGRAM 4) is an example that uses a cast for a practical
computation.
CO
ES PO
ACES
L L E GE
Page 20
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
OPERATORS
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Show Examples
CO
ES PO
ACES
L L E GE
Page 21
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The Relational Operators:
Show Examples
Java defines several bitwise operators, which can be applied to the integer
types, long, int, short, char, and byte.
a = 0011 1100
b = 0000 1101
-----------------
CO
ES PO
ACES
L L E GE
Page 22
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
a|b = 0011 1101
~a = 1100 0011
Show Examples
CO
ES PO
ACES
L L E GE
Page 23
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The Logical Operators:
Assume Boolean variables A holds true and variable B holds false, then:
Show Examples
Show Examples
CO
ES PO
ACES
L L E GE
Page 24
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Modulus AND assignment operator, It takes C %= A is
%= modulus using two operands and assign the result equivalent to C
to left operand =C%A
C <<= 2 is
<<= Left shift AND assignment operator same as C = C
<< 2
C >>= 2 is
>>= Right shift AND assignment operator same as C = C
>> 2
C &= 2 is same
&= Bitwise AND assignment operator
as C = C & 2
C ^= 2 is same
^= bitwise exclusive OR and assignment operator
as C = C ^ 2
C |= 2 is same
|= bitwise inclusive OR and assignment operator
as C = C | 2
Misc Operators
Conditional Operator ( ? : ):
CO
ES PO
ACES
L L E GE
Page 25
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
This would produce the following result:
Value of b is : 30
Value of b is : 20
instanceof Operator:
This operator is used only for object reference variables. The operator checks
whether the object is of a particular type(class type or interface type).
instanceof operator is wriiten as:
If the object referred by the variable on the left side of the operator passes the
IS-A check for the class/interface type on the right side, then the result will
be true. Following is the example:
true
This operator will still return true if the object being compared is the
assignment compatible with the type on the right. Following is one more
example:
class Vehicle {}
CO
ES PO
ACES
L L E GE
Page 26
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
true
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.
CO
ES PO
ACES
L L E GE
Page 27
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.1-1
Identification. Identify what is described in each statement.
1. A standardized technique to express instruction to computers.
2. A data type that can hold integral or whole number values.
3. A type of error that is encountred during compiling of programs due
to wrong syntax or grammar.
4. An imaginary machine that interprets or executes the Java bytecode.
5. A data type that holds collective characters like values for names,
addressess, etc.
Coding. Write the code of the following values stored in a variable. Apply
correct data type
1. 23.1
2. Panabo City
3. Cyril Dela Cruz
4. 89
5. Y
CO
ES PO
ACES
L L E GE
Page 28
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.1-1
1. programming language
2. int
3. compile time error
4. Java Virtual Machine (JVM)
5. String
Coding.
1. double var = 23.1;
2. String city = Panabo City;
3. String fulname = Cyril Dela Cruz;
4. int var2 = 89;
5. char mi = Y;
CO
ES PO
ACES
L L E GE
Page 29
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.1-2 Selection Control Structure
Learning Objectives:
After reading this information sheet, you must be able to:
1. Enumerate selection control structures in Java
IF STATEMENTS
Most computations require different actions for different inputs. One way to
express these differences in Java is the if statement:
if (<boolean expression>) { <statements> }
This description introduces a formal notation known as a template that we
will use to specify the format of Java constructs. We put within angle brackets
(< >) a construct that we have already defined, to indicate that we can use any
instance of that construct where specified. In this case, <boolean expression>
represents an expression that has a boolean value, such as one involving a
comparison operation, and <statements> represents a statement block (a
sequence of Java statements, each terminated by a semicolon). This latter
construct is familiar to you: the body of main() is such a sequence. If the
sequence is a single statement, the curly braces are optional. It is possible to
make formal definitions of <boolean expression> and <statements>, but we
refrain from going into that level of detail. The meaning of an if statement is
self-explanatory: the statement(s) in the sequence are to be executed if and
only if the expression is true.
CO
ES PO
ACES
L L E GE
Page 30
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
As a simple example, suppose that you want to compute the absolute value
of an int value x. This statement does the job:
if (x < 0) x = -x;
As a second simple example, consider the following
statement:
if (x > y){
int t = x;
x = y;
y = t;
}
This code puts x and y in ascending order by exchanging them if
necessary. Another example is a code snippet below:
int grade = 68;
if( grade > 60 ) System.out.println("Congratulations!");
or
int grade = 68;
if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println("You passed!");
}
Coding Guidelines:
1. The boolean_expression part of a statement should evaluate to
a boolean value. That means that the execution of the condition should
either result to a value of true or a false.
2. Indent the statements inside the if-block.For example,
if( boolean_expression ){
//statement1;
//statement2;
}
IF-ELSE STATEMENTS
You can also add an else clause to an if statement, to express the
concept of executing either one statement (or sequence of statements) or
another, depending on whether the boolean expression is true or false, as in
the following template:
if (<boolean expression>) <statements T>
CO
ES PO
ACES
L L E GE
Page 31
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
else <statements F>
or can also be written as,
if( boolean_expression ){
statement1;
statement2;
...
}
else{
statement1;
statement2;
...
}
As a simple example of the need for an else clause, consider the
following code, which assigns the maximum of two int values to the variable
max:
if (x > y) max = x;
else max = y;
One way to understand control flow is to visualize it with a diagram
called a flowchart.
Paths through the flowchart correspond to flow-of-control paths in the
program.
CO
ES PO
ACES
L L E GE
Page 32
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
else
System.out.println("Sorry you failed");
or
CO
ES PO
ACES
L L E GE
Page 33
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
similar to their meanings as natural-language phrases, you will quickly grow
used to them.
PROGRAM 5 is another example of the use of the if-else statement, in
this case for the task of simulating a coin flip. The body of the program is a
single statement, like the ones in the table above, but it is worth special
attention because it introduces an interesting philosophical issue that is
worth contemplating: can a computer program produce random values?
Certainly not, but a program can produce numbers that have many of the
properties of random numbers.
For example, given the code snippet,
int grade = 68;
if( grade > 60 ) System.out.println("Congratulations!");
or
int grade = 68;
if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println("You passed!");
}
CO
ES PO
ACES
L L E GE
Page 34
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
statement2;
else
statement3;
Take note that you can have many else-if blocks after an if-statement.
The else-block is optional and can be omitted. In the example shown above, if
boolean_expression1 is true, then the program executes statement1 and skips
the other statements. If boolean_expression2 is true, then the program
executes statement 2 and skips to the statements following statement3.
For example, given the code snippet,
int grade = 68;
if( grade > 90 ){
System.out.println("Very good!");
}
else if( grade > 60 ){
System.out.println("Very good!");
}
else{
System.out.println("Sorry you failed");
}
CO
ES PO
ACES
L L E GE
Page 35
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Program 6. Grade remarks
CO
ES PO
ACES
L L E GE
Page 36
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
SWITCH STATEMENTS
Another way to indicate a branch is through the switch keyword. The
switch construct allows branching on multiple outcomes. The switch
statement has the form,
switch( switch_expression ){
case case_selector1:
statement1; //
statement2; //block 1
. . . //
break;
case case_selector2:
statement1; //
statement2; //block 2
. . . //
break;
...
default:
statement1; //
statement2; //block n
. . . //
break;
}
where, switch_expression is an integer or character expression and,
case_selector1, case_selector2 and so on, are unique integer or character
constants. When a switch is encountered, Java first evaluates the
switch_expression, and jumps to the case whose selector matches the value
of the expression. The program executes the statements in order from that
point on until a break statement is encountered, skipping then to the first
statement after the end of the switch structure. If none of the cases are
satisfied, the default block is executed. Take note however, that the default
part is optional. A switch statement can have no default block.
NOTES:
Unlike with the if statement, the multiple statements are
executed in the switch
statement without needing the curly braces.
When a case in a switch statement has been matched, all the
statements associated
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 37
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
with that case are executed. Not only that, the statements
associated with the
succeeding cases are also executed.
To prevent the program from executing statements in the
subsequent cases, we use a
break statement as our last statement.
String class
This method compares this string to the specified object. The result is true if
and only if the argument is not null and is a String object that represents the
same sequence of characters as this object.
Syntax:
CO
ES PO
ACES
L L E GE
Page 38
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
public boolean equals(Object anObject)
Parameters:
Return Value :
This method returns true if the String are equal; false otherwise.
Example:
public class Test {
CO
ES PO
ACES
L L E GE
Page 39
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Task Sheet 1.1-2 Employee Weekly Salary
Title : Employee Weekly Salary
Performance Objective :
Create a Java program that will calculate and display the weekly
salary of an employee. An employee standard number of working hours is
40 hours. Any hour beyond that is considered over time for the employee.
Grosspay shall be computed as the number of hours worked by the
employee multiplied by the hourly wage. The netpay shall then be computed
as grosspay deducted by 12% of the grosspay which will be the employees
saving for the week. Overtime pay shall be computed as number of overtime
hours multiplied by 15% of the hourly rate. Note that when there is an
overtime pay, it will be included to the calculation of the grosspay. The
program will also display a message whether an employee had rendered
overtime or not.
Equipment : PC
Steps/Procedure:
1. Open text editor.
2. Write your program.
3. Run the program and debug errors.
4. Sample output of the program is the following:
Enter name: Joe
Enter number of hours worked: 41
Enter hourly wage: 50
-------------------------------------------
Name: Joe
Grosspay: 2007.50
You have rendered overtime!
Assessment Method:
Observation
CO
ES PO
ACES
L L E GE
Page 40
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Performance Criteria Checklist 1.1-2
CRITERIA Yes No
Does the user interface of the program meet the required
interface in the sample given?
Does your program following the correct structure of coding?
Does your program produce the expected required output?
CO
ES PO
ACES
L L E GE
Page 41
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.1-3 Repetition Control Structure
Learning Objectives:
After reading this information sheet, you must be able to:
1. Enumerate looping structures in Java and explain each of them
2. Explain what is infinite loop
CO
ES PO
ACES
L L E GE
Page 42
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
maximum before deciding to continue. TenHellos (PROGRAM 8) is a simple
example of this paradigm that uses a while statement. The key to the
computation is the statement i = i + 1; As a mathematical equation, this
statement is nonsense, but as a Java assignment statement it makes perfect
sense: it says to compute the value i + 1 and then assign the result to the
variable i. If the value of i was 4 before the statement, it becomes 5 afterwards;
if it was 5 it becomes 6; and so forth. With the initial condition in TenHellos
that the value of i starts at 4, the statement block is executed five times until
the sequence is broken, when the value of i becomes 11. Using the while loop
is barely worthwhile for this simple task, but you will soon be addressing
tasks where you will need to specify that statements be repeated far too many
times to contemplate doing it without loops. There is a profound difference
between programs with while statements and programs without them,
because while statements allow us to specify a potentially unlimited number
of statements to be executed in a
program. In particular, the while
statement allows us to specify lengthy
computations in short programs. This
ability opens the door to writing
programs for tasks that we could not
contemplate addressing without a
CO
ES PO
ACES
L L E GE
Page 43
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Program 8. Your first loop
computer. But there is also a price to pay: as your programs become more
sophisticated, they become more difficult to understand.
PowersOfTwo (PROGRAM 9) uses a while loop to print out a table of the
powers of 2. Beyond the loop control counter i, it maintains a variable v that
holds the powers of two as it computes them. The loop body contains three
statements: one to print the current power of 2, one to compute the next
(multiply the current one by 2), and one to increment the loop control counter.
There are many situations in computer science where it is useful to be
familiar with powers of 2. You should know at least the first 10 values in this
table and you should note that 210 is about 1 thousand, 220 is about 1
million, and 230 is about 1 billion. PowersOfTwo is the prototype for many
useful computations. It is worthwhile to carefully examine the behavior of
programs that use loops by studying a trace of the program. For example, a
trace of the operation of PowersOfTwo should show the value of each variable
before each iteration of the loop and the value of the conditional expression
that controls the loop. Tracing the operation of a loop can be very tedious, but
it is nearly always worthwhile to run a trace because it clearly exposes what
a program is doing. PowersOfTwo is nearly a self-tracing program, because it
prints the values of its variables each time through the loop. Clearly, you can
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 44
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
make any program produce a trace of itself by adding appropriate System.
out.println() statements. Modern programming environments provide
sophisticated tools for tracing, but
this tried-and-true method is simple and effective. You certainly should add
print statements to the first few loops that you write, to be sure that they are
doing precisely what you expect.
There is a hidden trap in PowersOfTwo, because the largest integer in Javas
int data type is 231 - 1 and the program does not test for that possibility. If
you invoke it with java PowersOfTwo 31, you may be surprised by the last line
of output:
...
1073741824
-2147483648
The variable v becomes too large and takes on a negative value because of the
way Java represents integers. The maximum value of an int is available for us
to use as Integer.MAX_VALUE. A better version of PROGRAM 1.3.3 would use
this value to test for overflow and print an error message if the user types too
large a value, though getting such a program to work properly for all inputs
is trickier than you might think. As a more complicated example, suppose
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 45
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
that we want to compute the largest power of two that is less than or equal to
a given positive integer N. If N is 13 we want the result 8; if N is 1000, we want
the result 512; if N is 64, we want the result 64; and so forth. This
computation is simple to perform with a while loop:
int v = 1;
while (v <= N/2)
v = 2*v;
It takes some thought to convince yourself that this simple piece of code
produces the desired result. You can do so by making these observations:
v is always a power of 2.
v is never greater than N.
v increases each time through the loop, so the loop
must terminate.
After the loop terminates, 2*v is greater than N.
Reasoning of this sort is often important in understanding how while loops
work. Even though many of the loops you will write are much simpler than
this one, you should be sure to convince yourself that each loop you write is
going to behave as you expect.
The logic behind such arguments is the same whether the loop iterates
just a few times, as in TenHellos, dozens of times, as in PowersOfTwo, or
millions of times, as in several examples that we will soon consider. That leap
from a few tiny cases to a huge computation is profound. When writing loops,
understanding how the values of the variables change each time through the
loop (and checking that understanding by adding statements to trace their
values and running for a small number of iterations) is essential. Having done
so, you can confidently remove those training wheels and truly unleash the
power of the computer.
DO-WHILE LOOPS
The do-while loop is similar to the while-loop. The statements inside a do-
while loop are executed several times as long as the condition is satisfied. The
main difference between a while and do-while loop is that, the statements
inside a do-while loop are executed at least once.
The do-while statement has the form,
do{
statement1;
statement2;
...
}while( boolean_expression );
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 46
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The statements inside the do-while loop are first executed, and then the
condition in the boolean_expression part is evaluated. If this evaluates to true,
the statements inside the do-while loop are executed again.
Here are a few examples that uses the do-while loop:
Example 1:
int x = 0;
do
{
System.out.println(x);
x++;
}while (x<10);
This example will output 0123456789 on the screen.
Example 2:
//infinite loop
do{
System.out.println(hello);
} while (true);
This example will result to an infinite loop, that prints hello on screen.
Example 3:
//one loop
// statement is executed once
do
System.out.println(hello);
while (false);
This example will output hello on the screen.
FOR LOOPS
As you will see, the while loop allows us to write programs for all manner of
applications. Before considering more examples, we will look at an alternate
Java construct that allows us even more flexibility when writing programs
with loops. This alternate notation is not fundamentally different from the
basic while loop, but it is widely used because it often allows us to write more
compact and more readable programs than if we used only while statements.
For notation. Many loops follow this scheme: initialize an index variable to
some value and then use a while loop to test a loop continuation condition
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 47
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
involving the index variable, where the last statement in the while loop
increments the index variable. You can express such loops directly with Javas
for notation:
for (<initialize>; <boolean expression>; <increment>)
{
<statements>
}
This code is, with only a few exceptions, equivalent to
<initialize>;
while (<boolean expression>)
{
<statements>
<increment>;
}
Your Java compiler might even produce identical results for the two
loops. In truth, <initialize> and <increment> can be any statements at all, but
we nearly always use for loops to support this typical initialize-and-increment
programming idiom. For example, the following two lines of code are
equivalent to the corresponding lines of code in TenHellos (PROGRAM 8):
for (int i = 4; i <= 10; i = i + 1)
System.out.println(i + "th Hello");
Typically, we work with a slightly more compact version of this code, using
the shorthand notation discussed next.
Compound assignment idioms. Modifying the value of a variable is
something that we do so often in programming that Java provides a variety of
different shorthand notations for the purpose. For example, the following four
statements all increment the value of i by 1 in Java:
i = i + 1; i++; ++i; i += 1;
You can also say i-- or --i or i -= 1 or i = i-1 to decrement that value of i by 1.
Most programmers use i++ or i-- in for loops, though any of the others would
do. The ++ and -- constructs are normally used for integers, but the compound
assignment constructs are useful operations for any arithmetic operator in
any primitive numeric type. For example, you can say v *= 2 or v += v instead
of v = 2*v. All of these idioms are for notational convenience, nothing more.
This combination of shortcuts came into widespread use with the C
programming language in the 1970s and have become standard. They have
survived the test of time because they lead to compact, elegant, and easily
understood programs. When you learn to write (and to read) programs that
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 48
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
use them, you will be able to transfer that skill to programming in numerous
modern languages, not just Java.
Scope. The scope of a variable is the part of the program where it is defined.
Generally the scope of a variable is comprised of the statements that follow
the declaration in the same block as the declaration. For this purpose, the
code in the for loop header is considered to be in the same block as the for
loop body. Therefore, the while and for formulations of loops are not quite
equivalent: in a typical for loop, the incrementing variable is not available for
use in later statements; in the corresponding while loop, it is. This distinction
is often a reason to use a while instead of a for loop.
Choosing among different formulations of the same computation is a
matter of each programmers taste, as when a writer picks from among
synonyms or chooses between using active and passive voice when composing
a sentence. You will not find good hard-and-fast rules on how to compose a
program any more than you will find such rules on how to compose a
paragraph. Your goal should be to find a style that suits you, gets the
computation done, and can be appreciated by others.
The accompanying table
includes several code fragments
with typical examples of loops
used in Java code. Some of these
relate to code that you have
already seen; others are new code
for straightforward
computations. To cement your
understanding of loops in Java,
put these code snippets into a
classs code that takes an integer
N from the command line (like PowersOfTwo) and compile and run them.
Then, write some loops of your own for similar computations of your own
invention, or do some of the early exercises at the end of this section. There
is no substitute for the experience gained by running code that you create
yourself, and it is imperative that you develop an understanding of how to
write Java code that uses loops.
CO
ES PO
ACES
L L E GE
Page 49
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
OTHER LOOP CONSTRUCTS
To more fully cover the Java language, we consider here 2 more control-flow
constructs. You need not think about using these constructs for every
program that you write, because you are likely to encounter them much less
frequently than the if, while, and for statements. You certainly do not need to
worry about using these constructs until you are comfortable using if, while,
and for. You might encounter one of them in a program in a book or on the
web, but many programmers do not use them at all and we do not use any of
them outside this section.
Break statement. In some situations, we want to immediately exit a loop
without letting it run to completion. Java provides the break statement for
this purpose. For example, the following code is an effective way to test
whether a given integer
N>1 is prime:
int i;
for (i = 2; i <= N/i; i++)
if (N % i == 0) break;
if (i > N/i) System.out.println(N + " is prime");
There are two different ways to leave this loop: either the break statement is
executed (because i divides N, so N is not prime) or the for loop condition is
not satisfied (because no i with i <= N/i was found that divides N, which
implies that N is prime). Note that we have to declare i outside the for loop
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 50
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
instead of in the initialization statement so that its scope extends beyond the
loop.
Continue statement. Java also provides a way to skip to the next iteration of
a loop: the continue statement. When a continue is executed within a loop
body, the flow of control transfers directly to the increment statement for the
next iteration of the loop.
INFINITE LOOPS
Before you write programs that use loops, you need to think about the
following issue: what if the loop-continuation condition in a while loop is
always satisfied? With the statements that you have learned so far, one of two
bad things could happen, both of which you need to learn to cope with. First,
suppose that such a loop calls System.out.println(). For example, if the
condition in TenHellos were (i > 3) instead of (i <= 10), it would always be true.
What happens? Nowadays, we use print as an abstraction to mean display in
a terminal window and the result of attempting to display an unlimited
number of lines in a terminal window is dependent on operating-system
conventions. If your system is set up to have print mean print characters on
a piece of paper, you might run out of paper or have to unplug the printer. In
a terminal window, you need a stop printing operation. Before running
programs with loops on your own, you make sure that you know what to do
to pull the plug on an infinite loop of System.out.println() calls and then test
out the strategy by making the change to TenHellos indicated above and trying
to stop it. On most systems, <ctrl-c> means stop the current program, and
should do the job.
Second, nothing might happen. If your program has an infinite loop that
does not produce any output, it will spin through the loop and you will see no
results at all. When you find yourself in such a situation, you can inspect the
loops to make sure that the loop exit condition always happens, but the
problem may not be easy to identify. One way to locate such a bug is to insert
calls to System.out.println() to produce a trace. If these calls fall within an
infinite loop, this strategy reduces the problem to the case discussed in the
previous paragraph, but the output might give you a clue about what to do.
You might not know (or it might not matter) whether a loop is infinite
or just very long. Even BadHellos eventually would terminate after printing
over a billion lines because of overflow. Why not have Java detect infinite loops
and warn us about them? You might be surprised to know that it is not
possible to do so, in general. This counterintuitive fact is one of the
fundamental results of theoretical computer science.
CO
ES PO
ACES
L L E GE
Page 51
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Task Sheet 1.1-3 Right triangle
Title : Right triangle
Performance Objective :
Create a Java program that will display a right triangle out of asterisks
depending on the size given by the user.
Equipment : PC
Steps/Procedure:
1. Open text editor.
2. Write your program.
3. Run the program and debug errors.
4. Sample output of the program is the following:
Enter size of square: 8
----------------------------
*
**
***
****
*****
******
*******
********
5. Evaluate your own output using the Performance Criteria Checklist 1.1-
2.
6. Present your work to your trainer
Assessment Method:
Observation
CO
ES PO
ACES
L L E GE
Page 52
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Performance Criteria Checklist 1.1-3
CRITERIA Yes No
Does the user interface of the program meet the required
interface in the sample given?
Does your program following the correct structure of coding?
Does your program produce the expected required output?
CO
ES PO
ACES
L L E GE
Page 53
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.1-4 Arrays
Learning Objectives:
After reading this information sheet, you must be able to:
1. Describe the process of visual program design and development.
2. Explain the term object-oriented programming.
3. Explain the concepts of classes, objects, properties, methods, and
events.
4. List and describe the tree steps for writing a Visual Basic project.
5. Describe the various files that make up a Visual Basic project.
Identify the elements in the Visual Studio environment.
CO
ES PO
ACES
L L E GE
Page 54
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
ARRAYS IN JAVA
Making an array in a Java program involves three distinct steps:
o Declare the array name and type.
o Create the array.
o Initialize the array values.
To declare the array, you need to specify a name and the type of data it
will contain. To create it, you need to specify its size (the number of values).
For example, the following code makes an array of N numbers of type double,
all initialized to 0.0:
double[] a;
a = new double[N];
for (int i = 0; i < N; i++)
a[i] = 0.0;
The first statement is the array declaration. It is just like a declaration
of a variable of the corresponding primitive type except for the square brackets
following the type name, which specify that we are declaring an array. The
second statement creates the array. This action is unnecessary for variables
of a primitive type (so we have not seen a similar action before), but it is
needed for all other types of data in Java. In the code in this module, we
normally keep the array length in an integer variable N, but any integer-valued
expression will do. The for statement initializes the N array values. We refer
to each value by putting its index in brackets after the array name. This code
sets all of the array entries to the value 0.0.
When you begin to write code that uses an array, you must be sure that
your code declares, creates, and initializes it. Omitting one of these steps is a
common programming mistake. For economy in code, we often take advantage
of Javas default array initialization convention and combine all three steps
into a single statement. For example, the following statement is equivalent to
the code above:
double[] a = new double[N];
The code to the left of the equal sign constitutes the declaration; the code to
the right constitutes the creation. The for loop is unnecessary in this case
because the default initial value of variables of type double in a Java array is
0.0, but it would be required if a nonzero value were desired. The default initial
value is zero for all numbers and false for type boolean. For String and other
non-primitive types, the default is the value null. After declaring and creating
an array, you can refer to any individual value anywhere you would use a
variable name in a program by enclosing an integer index in braces after the
array name. We refer to the ith item with the code a[i]. The explicit
initialization code shown earlier is an example of such a use. The obvious
CO
ES PO
ACES
L L E GE
Page 55
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
advantage of using arrays is to avoid explicitly naming each variable
individually.
Using an array index is virtually the same as appending the index to
the array name: for example, if we wanted to process eight variables of type
double, we could declare each of them individually with the declaration
double a0, a1, a2, a3, a4, a5, a6, a7;
and then refer to them as a0, a1 and so forth instead of declaring them with
double[] a = new double[8]
and referring to them as a[0], a[1], and so forth. But naming dozens of
individual variables in this way would be cumbersome and naming millions
is untenable.
The dot product represented as one-dimensional arrays x[] and y[] that
are each of length 3 is the expression x[0]*y[0] + x[1]*y[1] + x[2]*y[2]. If we
represent the two vectors as one-dimensional arrays x[] and y[] that are each
of length N and of type double, the dot product is easy to compute:
double sum = 0.0;
for (int i = 0; i < N; i++)
sum += x[i]*y[i];
The simplicity of coding such computations makes the use of arrays the
natural choice for all kinds of applications. (Note that when we use the
notation x[], we are referring to the whole array, as opposed to x[i], which is a
reference to the ith entry.)
The accompanying table has many examples of array-processing code, and
we will consider even more examples later in the book, because arrays play a
central role in processing data in many applications. Before considering more
sophisticated examples, we describe a number of important characteristics of
programming with arrays.
CO
ES PO
ACES
L L E GE
Page 56
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Zero-based indexing. We always refer to the first element of an array as a[0],
the second as a[1], and so forth. It might seem more natural to you to refer to
the first element as a[1], the second value as a[2], and so forth, but starting
the indexing with 0 has some advantages and has emerged as the convention
used in most modern programming languages. Misunderstanding this
convention often leads to off-by one-errors that are notoriously difficult to
avoid and debug, so be careful!
Array length. Once we create an array, its size is fixed. The reason that we
need to explicitly create arrays at runtime is that the Java compiler cannot
know how much space to reserve for the array at compile time (as it can for
primitive-type values). Our convention is to keep the size of the array in a
variable N whose value can be set at runtime (usually it is the value of a
command-line argument). Javas standard mechanism is to allow a program
to refer to the length of an array a[] with the code a.length; we normally use
N to create the array, or set the value of N to a.length. Note that the last
element of an array is always a[a.length-1]. PROGRAM 10 is an example of
program that will use .length to get the value of the array.
CO
ES PO
ACES
L L E GE
Page 57
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Program 10. Array length display
CO
ES PO
ACES
L L E GE
Page 58
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
process is required for all variables that you use in a program. We call
attention to it now because it is your responsibility to use new to allocate
memory for an array before accessing any of its elements. If you fail to adhere
to this rule, you will get a compile-time uninitialized variable error. Java
automatically initializes all of the values in an array when it is created. You
should remember that the time required to create an array is proportional to
its length.
CO
ES PO
ACES
L L E GE
Page 59
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Whenever the values of all array entries are known at compile time (and the
size of the array is not too large) it makes sense to use this method of
initializing the arrayjust put all the values in braces on the right hand side
of an assignment in the array declaration. Doing so implies array creation, so
the new keyword is not needed.
Setting array values at runtime. A more typical situation is when we wish
to compute the values to be stored in an array. In this case, we can use array
names with indices in the same way we use variable names on the left side of
assignment statements. For example, we might use the following code to
initialize an array of size 52 that represents a deck of playing cards, using the
two arrays just defined:
String[] deck = new String[suit.length * rank.length];
for (int i = 0; i < suit.length; i++)
for (int j = 0; j < rank.length; j++)
deck[rank.length*i + j] = rank[i] + " of " + suit[j];
After this code has been executed, if you were to print out the contents of deck
in order from deck[0] through deck[51] using System.out.println(), you would
get the sequence
2 of Clubs
2 of Diamonds
2 of Hearts
2 of Spades
3 of Clubs
3 of Diamonds
...
Ace of Hearts
Ace of Spades
CO
ES PO
ACES
L L E GE
Page 60
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
and j are equal, the array is unchanged. When i and j are not equal, the values
a[i] and a[j] are found in different places in the array. For example, if we were
to use this code with i equal to 1 and j equal to 4 in the deck array of the
previous example, it would leave 3 of Clubs in deck[1] and 2 of Diamonds in
deck[4].
Shuffle. The following code shuffles our deck of cards:
int N = deck.length;
for (int i = 0; i < N; i++)
{
int r = i + (int) (Math.random() * (N-i));
String t = deck[i];
deck[i] = deck[r];
deck[r] = t;
}
Proceeding from left to right, we pick a random card from deck[i] through
deck[N-1] (each card equally likely) and exchange it with deck[i]. This code is
more sophisticated than it might seem: First, we ensure that the cards in the
deck after the shuffle are the same as the cards in the deck before the shuffle
by using the exchange idiom. Second, we ensure that the shuffle is random
by choosing uniformly from the cards not yet chosen.
Simplifying repetitive code. As an example of another simple application of
arrays, consider the following code fragment, which prints out the name of a
month given its number (1 for January, 2 for February, and so forth):
if (m == 1) System.out.println("Jan");
else if (m == 2) System.out.println("Feb");
else if (m == 3) System.out.println("Mar");
else if (m == 4) System.out.println("Apr");
else if (m == 5) System.out.println("May");
else if (m == 6) System.out.println("Jun");
else if (m == 7) System.out.println("Jul");
else if (m == 8) System.out.println("Aug");
else if (m == 9) System.out.println("Sep");
else if (m == 10) System.out.println("Oct");
else if (m == 11) System.out.println("Nov");
else if (m == 12) System.out.println("Dec");
CO
ES PO
ACES
L L E GE
Page 61
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
We could also use a switch statement, but a much more compact alternative
is to use a String array consisting of the names of each month:
String[] months =
{
"", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
System.out.println(months[m]);
This technique would be especially useful if you needed to access the name of
a month by its number in several different places in your program. Note that
we intentionally waste one slot in the array (element 0) to make months[1]
correspond to January, as required.
Assignments and equality tests. Suppose that you have created the two
arrays a[] and b[]. What does it mean to assign one to the other with the code
a = b; ? Similarly, what does it mean to test whether the two arrays are equal
with the code (a == b)? The answers to these questions may not be what you
first assume, but if you think about the array memory representation, you
will see that Javas interpretation of these operations makes sense: An
assignment makes the names a and b refer to the same array. The alternative
would be to have an implied loop that assigns each value in b to the
corresponding value in a. Similarly, an equality test checks whether the two
names refer to the same array. The alternative would be to have an implied
loop that tests whether each value in one array is equal to the corresponding
value in the other array. In both cases, the implementation in Java is very
simple: it just performs the standard operation as if the array name were a
variable whose value is the memory address of the array. Note that there are
many other operations that you might want to perform on arrays: for example,
it would be nice in some applications to say a = a + b and have it mean add
the corresponding element in b[] to each element in a[], but that statement is
not legal in Java. Instead, we write an explicit loop to perform all the additions.
In typical applications, we use this mechanism, so we rarely need to use
Javas assignments and equality tests with arrays.
With these basic definitions and examples out of the way, we can now
consider two applications that both address interesting classical problems
and illustrate the fundamental importance of arrays in efficient computation.
In both cases, the idea of using data to index into an array plays a central role
and enables a computation that would not otherwise be feasible.
TWO-DIMENSIONAL ARRAYS
In many applications, a convenient way to store information is to use a
table of numbers organized in a rectangular table and refer to rows and
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 62
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
columns in the table. For example, a teacher might need to maintain a table
with a row corresponding to each student and a column corresponding to
each assignment, a scientist might need to maintain a table of experimental
data with rows corresponding to experiments and columns corresponding to
various outcomes, or a programmer might want to prepare an image for
display by setting a table of pixels to various grayscale values or colors.
The mathematical abstraction corresponding to such tables is a matrix;
the corresponding Java construct is a twodimensional array. You are likely to
have already encountered many applications of matrices and two-dimensional
arrays, and you will certainly encounter many others in science, in
engineering, and in computing applications, as we will demonstrate with
examples throughout this module.
Extending Java array constructs to handle two-dimensional arrays is
straightforward. To refer to the element in row i and column j of a two-
dimensional array a[][], we use the notation a[i][j]; to declare a two-
dimensional array, we add another pair of brackets; and to create the array,
we specify the number of rows followed by the number of columns after the
type name (both within brackets), as follows:
double[][] a = new double[M][N];
We refer to such an array as an M-by-N array. By convention, the first
dimension is the number of rows and the second is the number of columns.
As with onedimensional arrays, Java initializes all entries in arrays of
numbers to zero and in arrays of boolean values to false.
Initialization. Default initialization of two-dimensional arrays is useful
because it masks more code than for one-dimensional arrays. The following
code is equivalent to the single-line create-and-initialize idiom that we just
considered:
double[][] a;
a = new double[M][N];
for (int i = 0; i < M; i++)
{ // Initialize the ith row.
for (int j = 0; j < N; j++)
a[i][j] = 0.0;
}
This code is superfluous when initializing to zero, but the nested for loops are
needed to initialize to some other value(s). As you will see, this code is a model
for the code that we use to access or modify each element of a two-dimensional
array.
CO
ES PO
ACES
L L E GE
Page 63
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Output. We use nested for loops for many array-processing operations. For
example, to print an M-by-N array in the familiar tabular format, we would
use the following code
for (int i = 0; i < M; i++)
{ // Print the ith row.
for (int j = 0; j < N; j++)
System.out.print(a[i][j] + " ");
System.out.println();
}
regardless of the array elements type. If desired, we could add code to
embellish the output with row and column numbers, but Java programmers
typically tabulate arrays with row numbers
running top to bottom from 0 and column
number running left to right from 0.
Generally, we also do so and do not bother to
use labels.
Memory representation. Java represents a
two-dimensional array as an array of arrays.
A matrix with M rows and N columns is
actually an array of length M, each entry of
which is an array of length N. In a two-
dimensional Java array a[][], we can use the
code a[i] to refer to the ith row (which is a one-
dimensional array), but we have no
corresponding way to refer to a column.
CO
ES PO
ACES
L L E GE
Page 64
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Setting values at compile time. The Java method for initializing an array of
values at compile time follows immediately from the representation. A two-
dimensional array is an array of rows, each row initialized as a one-
dimensional array. To initialize a two-dimensional array, we enclose in braces
a list of terms to initialize the rows, separated by
commas. Each term in the list is itself a list: the values
for the array elements in the row, enclosed in braces
and separated by commas.
CO
ES PO
ACES
L L E GE
Page 65
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
entries is known as row-major order. Similarly, to compute the average test
grade (average values for each column), sum the entries for each column and
divide by M. The column-by-column order in which this code processes the
matrix entries is known as column-major order.
Matrix operations. Typical applications in science and engineering involve
representing matrices as two-dimensional arrays and
then implementing various mathematical operations
with matrix operands. Again, even though such
processing is often done within specialized
applications, it is worthwhile for you to understand the
underlying computation. For example, we can add two
N-by-N matrices as follows:
double[][] c = new double[N][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
c[i][j] = a[i][j] + b[i][j];
Similarly, we can multiply two
matrices. You may have
learned matrix multiplication, but if you do not recall
or are not familiar with it, the Java code below for
square matrices is essentially the same as the
mathematical definition. Each entry c[i][j] in the
product of a[] and b[] is computed by taking the dot
product of row i of a[] with column j of b[].
double[][] c = new double[N][N];
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
// Compute dot product of row i and column j.
for (int k = 0; k < N; k++)
c[i][j] += a[i][k]*b[k][j];
}
CO
ES PO
ACES
L L E GE
Page 66
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
}
Multidimensional arrays. The same notation extends to allow us to write
code using arrays that have any number of dimensions. For instance, we can
declare and initialize a three-dimensional array with the code
double[][][] a = new double[N][N][N];
and then refer to an entry with code like a[i][j][k], and so forth.
CO
ES PO
ACES
L L E GE
Page 67
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Task Sheet 1.1-4 Address Book
Title : Address Book
Performance Objective :
Create a Java program address book that will contain 100 entries which
include name, address, telephone number and email address.
Equipment : PC
Steps/Procedure:
1. Open text editor.
2. Write your program.
3. Run the program and debug errors.
4. Evaluate your own output using the Performance Criteria Checklist 1.1-
2.
5. Present your work to your trainer
Assessment Method:
Observation
CO
ES PO
ACES
L L E GE
Page 68
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Performance Criteria Checklist 1.1-4
CRITERIA Yes No
Does the source code of the program meet the required program
specifications?
Does your program following the correct structure of coding?
Does your program produce the expected required output?
CO
ES PO
ACES
L L E GE
Page 69
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
LEARNING OUTCOME NO. 2 Works with Methods and
Encapsulation
Contents:
2. Methods
3. Encapsulation
Assessment Criteria:
1. Methods with arguments and return values are created in
accordance with Java framework
2. Static keywords are applied to methods and fields in accordance
with Java framework
3. Overloaded method is created in accordance with Java framework
4. Access modifiers are applied in accordance with Java framework
5. Encapsulation principled are applied to a class in accordance with
Java framework
Conditions:
PC or workstation
Programming tools
Reference Book s
Handouts/Modules/Printed Materials
Assessment Method:
Oral recitation
Written examinations
Case Study (Defense)
CO
ES PO
ACES
L L E GE
Page 70
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.2-1 Methods in Java
Learning Objectives:
After reading this information sheet, you must be able to:
1. Write syntax to create a method
2. Execute calling of method that are created
3. Learn how to pass variables and values to a method
4. Enumerate access modifiers in Java
In the examples we discussed before, we only have one method, and
that is the main() method. In Java, we can define many methods which we
can call from different methods. A method is a separate piece of code that can
be called by a main program or any other method to perform some specific
function.
The following are characteristics of methods:
It can return one or no values
It may accept as many parameters it needs or no parameter at all.
Parameters are
also called function arguments.
After the method has finished execution, it goes back to the method
that called it.
Now, why do we need to create methods? Why don't we just place all the code
inside one big method? The heart of effective problem solving is in problem
decomposition. We can do this in Java by creating methods to solve a specific
part of the problem. Taking a problem and breaking it into small, manageable
pieces is critical to writing large programs.
CREATING METHOD
Considering the following example to explain the syntax of a method:
public static int funcName(int a, int b) {
// body
}
Here,
CO
ES PO
ACES
L L E GE
Page 71
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
int a, int b: list of parameters
return min;
}
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 72
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
METHOD CALLING
For using a method, it should be called. There are two ways in which a method
is called i.e. method returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method,
the program control gets transferred to the called method. This called method
then returns control to the caller in two conditions, when:
return statement is executed.
reaches the method ending closing brace.
The methods returning void is considered as call to a statement. Lets consider
an example:
System.out.println("This is tutorialspoint.com!");
The method returning value can be understood by the following example:
int result = sum(6, 9);
Example:
Following is the example to demonstrate how to define a method and how to
call it:
public class ExampleMinNumber{ if (n1 > n2)
public static void main(String[] min = n2;
args) { else
int a = 11; min = n1;
int b = 6;
int c = minFunction(a, b); return min;
System.out.println("Minimum }
Value = " + c); }
}
/** returns the minimum of two This would produce the following
numbers */ result:
public static int minFunction(int
n1, int n2) { Minimum value = 6
int min;
CO
ES PO
ACES
L L E GE
Page 73
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Example:
public class ExampleVoid {
public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
System.out.println("Rank:A1");
}
else if (points >= 122.4) {
System.out.println("Rank:A2");
}
else {
System.out.println("Rank:A3");
}
}
}
Pass-by-value
CO
ES PO
ACES
L L E GE
Page 74
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
When a pass-by-value occurs, the method makes a copy of the value of the
variable passed to the method. The method cannot accidentally modify the
original argument even if it modifies the parameters during calculations.
For example,
public class TestPassByValue
{
public static void main( String[] args ){
int i = 10;
//print the value of i
System.out.println( i );
//call method test
//and pass i to method test
test( i );
//print the value of i. i not changed
System.out.println( i );
}
public static void test( int j ){
//change value of parameter j
j = 33;
}
}
In the given example, we called the method test and passed the value of i as
parameter. The value of i is copied to the variable of the method j. Since j is
the variable changed in the test method, it will not affect the variable value if
i in main since it is a different copy of the variable.
By default, all primitive data types when passed to a method are pass-by-
value.
Pass-by-reference
When a pass-by-reference occurs, the reference to an object is passed to the
calling method. This means that, the method makes a copy of the reference of
the variable passed to the method. However, unlike in pass-by-value, the
method can modify the actual object that the reference is pointing to, since,
although different references are used in the methods, the location of the data
they are pointing to is the same.
For example,
CO
ES PO
ACES
L L E GE
Page 75
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
class TestPassByReference
{
public static void main( String[] args ){
//create an array of integers
int []ages = {10, 11, 12};
//print array values
for( int i=0; i<ages.length; i++ ){
System.out.println( ages[i] );
}
//call test and pass reference to array
test( ages );
//print array values again
for( int i=0; i<ages.length; i++ ){
System.out.println( ages[i] );
}
}
public static void test( int[] arr ){
//change values of array
for( int i=0; i<arr.length; i++ ){
arr[i] = i + 50;
}
}
}
ACCESS MODIFIERS
There are four different types of member access modifiers in Java: public,
private, protected and default. The first three access modifiers are explicitly
written in the code to indicate the access type, for the fourth one which is
default, no keyword is used.
Default Access (Also Called Package Accessibility)
This specifies that only classes in the same package can have access to
the class' variables and methods. There are no actual keyword for the default
modifier; it is applied in the absence of an access modifier.
For example,
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 76
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
public class StudentRecord
{
//default access to instance variable
int name;
//default access to method
String getName(){
return name;
}
}
In this example, the instance variable name and the method getName() can
be accessed from other objects, as long as the object belongs to the same
package where the class StudentRecord belongs to.
Public Access
This specifies that class members are accessible to anyone, both inside and
outside the class. Any object that interacts with the class can have access to
the public members of the class.
For example,
public class StudentRecord
{
//default access to instance variable
public int name;
//default access to method
public String getName(){
return name;
}
}
In this example, the instance variable name and the method getName() can
be accessed from other objects.
Protected Access
This specifies that the class members are accessible only to methods in that
class and the subclasses of the class.
For example,
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 77
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
public class StudentRecord
{
//default access to instance variable
protected int name;
//default access to method
protected String getName(){
return name;
}
}
In this example, the instance variable name and the method getName() can
be accessed only from methods inside the class and from subclasses of
StudentRecord.
Private Access
This specifies that the class members are only accessible by the class they are
defined in.
For example,
public class StudentRecord
{
//default access to instance variable
private int name;
//default access to method
private String getName(){
return name;
}
}
In this example, the instance variable name and the method getName() can
be accessed only from methods inside the class. Furthermore, method
overloading will be discussed on the next information sheet.
CO
ES PO
ACES
L L E GE
Page 78
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.2-1
Answer each item and write it on your paper.
1. How many access modifiers are there in Java?
2. What type of passing variable to a method when method makes a
copy of the value of the variable that is passed?
3. What keyword allows us to create methods which do not return a
value?
CO
ES PO
ACES
L L E GE
Page 79
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.2-1
1. 4
2. pass-by-value
3. void
CO
ES PO
ACES
L L E GE
Page 80
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.2-2 Encapsulation
Learning Objectives:
After reading this information sheet, you must be able to:
1. Define encapsulation
2. Define mutator methods
3. Describe accessor method
4. Explain what is method overloading
ENCAPSULATION AND INFORMATION HIDING
Encapsulation is one of the four fundamental OOP concepts. The other
three are inheritance, polymorphism, and abstraction.
Encapsulation is the technique of making the fields in a class private
and providing access to the fields via public methods. If a field is declared
private, it cannot be accessed by anyone outside the class, thereby hiding the
fields within the class. For this reason, encapsulation is also referred to as
data hiding.
Encapsulation can be described as a protective barrier that prevents
the code and data being randomly accessed by other code defined outside the
class. Access to the data and code is tightly controlled by an interface.
The main benefit of encapsulation is the ability to modify our
implemented code without breaking the code of others who use our code. With
this feature Encapsulation gives maintainability, flexibility and extensibility
to our code.
Information hiding is the principle of concealing the internal data and
procedures of an object and providing an interface to each object in such a
way as to reveal as little as possible about its inner workings. As in
conventional programming, some languages permit arbitrary access to objects
and allow methods to be defined outside of a class. For example, Simula
provides no protection, or information hiding, for objects, meaning that an
object's data, or instance variables, may be accessed wherever visible.
However, most object-oriented languages provide a well-defined interface to
their objects through classes. For example, jAVA has a very general
encapsulation protection mechanism with public, private, and protected
members. Public members (member data and member functions) may be
accessed from anywhere. For instance, the compute Payroll method of an
employee object will be public. Private members are accessible only from
within a class. An object data representation, such as a list or an array,
usually will be private. Protected members can be accessed only from
subclasses. An important factor in achieving encapsulation is the design of
different classes of objects that operate using a common protocol, or object's
user interface. This means that many objects will respond to the same
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 81
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
message, but each will perform the message using operations tailored to its
class. In this way, a program can send a generic message and leave the
implementation up to the receiving object, which reduces interdependencies
and increases the amount of interchangeable and reusable code.
A car engine is an example of encapsulation. Although engines may
differ in implementation, the interface between the driver and the car is
through a common protocol: Step on the gas to increase power and let up on
the gas to decrease power. Since all drivers know this protocol, all drivers can
use this method in all cars, no matter what engine is in the car. That detail is
insulated from the rest of the car and from thedriver. This simplifies the
manipulation of car objects and the maintenance of code.
Data abstraction is a benefit of the object-oriented concept that
incorporates encapsulation and polymorphism. Data are abstracted when
they are shielded by a full set of methods and only those methods can access
the data portion of an object.
Example:
CO
ES PO
ACES
L L E GE
Page 82
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
}
The public methods are the access points to this class' fields from the
outside java world. Normally, these methods are referred as getters (accessor
method) and setters (mutator method). Therefore any class that wants to
access the variables should access them through these getters and setters.
The variables of the EncapTest class can be access as below::
Mutator Methods
Now, what if we want other objects to alter our data? What we do is we provide
methods that can write or change values of our class variables
(instance/static). We call these methods, mutator methods. A mutator method
is usuallyu written as
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 83
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
set<NameOfInstanceVariable>.
Now let's take a look at one implementation of a mutator method,
public class StudentRecord
{
private String name;
::
public void setName( String temp ){
name = temp;
}
}
where,
public - means that the method can be called from objects outside the class
void - imeans that the method does not return any value
setName - the name of the method
(String temp) - parameter that will be used inside our method
The statement,
name = temp;
assigns the value of temp to name and thus changes the data inside the
instance
variable name.
Take note that mutator methods don't return values. However, it contains
some program
argument or arguments that will be used inside the method.
Accessor methods
In order to implement encapsulation, that is, we don't want any objects to just
access our data anytime, we declare the fields or attributes of our classes as
private. However, there are times wherein we want other objects to access
private data. In order to do this, we create accessor methods.
Accessor methods are used to read values from class variables
(instance/static). An accessor method usually starts with a
get<NameOfInstanceVariable>. It also returns a value.
For our example, we want an accessor method that can read the name,
address, english grade, math grade and science grade of the student.
Now let's take a look at one implementation of an accessor method,
CO
ES PO
ACES
L L E GE
Page 84
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
public class StudentRecord
{
private String name;
::
public String getName(){
return name;
}
}
where,
public - means that the method can be called from objects outside the class
String - is the return type of the method. This means that the method should
return a value of type String
getName - the name of the method
() - this means that our method does not have any parameters
The statement,
return name;
in our program signifies that it will return the value of the instance variable
name to the calling method. Take note that the return type of the method
should have the same data type as the data in the return statement. You
usually encounter the following error if the two does not have the same data
type,
StudentRecord.java:14: incompatible types
found : int
required: java.lang.String return age;
^
1 error
Another example of an accessor method is the getAverage method,
public class StudentRecord
{
private String name;
::
public double getAverage(){
double result = 0;
CO
ES PO
ACES
L L E GE
Page 85
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
result = ( mathGrade+englishGrade+scienceGrade )/3;
return result;
}
}
The getAverage method computes the average of the 3 grades and returns the
result.
Another example of class that depicts encapsulation.
public class StudentRecord
{
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
private static int studentCount;
/**
* Returns the name of the student
*/
public String getName(){
return name;
}
/**
* Changes the name of the student
*/
public void setName( String temp ){
name = temp;
}
// other code here ....
/**
* Computes the average of the english, math and science
CO
ES PO
ACES
L L E GE
Page 86
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
* grades
*/
public double getAverage(){
double result = 0;
result = ( mathGrade+englishGrade+scienceGrade )/3;
return result;
}
/**
* returns the number of instances of StudentRecords
*/
public static int getStudentCount(){
return studentCount;
}
}
Now, here's a sample code of a class that uses our StudentRecord class.
CO
ES PO
ACES
L L E GE
Page 87
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
System.out.println("Count="+StudentRecord.getStudentCou
nt());
}
}
The output of this program is,
Anna
Student Count = 0
The this reference
The this reference is used to access the instance variables shadowed by the
parameters. To understand this better, let's take for example the setAge
method. Suppose we have the following declaration for setAge.
public void setAge( int age ){
age = age; //WRONG!!!
}
The parameter name in this declaration is age, which has the same name as
the instance variable age. Since the parameter age is the closest declaration
to the method, the value of the parameter age will be used. So in the
statement,
age = age;
we are just assigning the value of the parameter age to itself! This is not what
we want to happen in our code. In order to correct this mistake, we use the
this reference. To use the this reference, we type,
this.<nameOfTheInstanceVariable>
This method will then assign the value of the parameter age to the
instance variable of the object StudentRecord.
NOTE: You can only use the this reference for instance variables and NOT
static or class variables.
Overloading Methods
In our classes, we want to sometimes create methods that has the same
names but function differently depending on the parameters that are passed
CO
ES PO
ACES
L L E GE
Page 88
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
to them. This capability is possible in Java, and it is called Method
Overloading.
Method overloading allows a method with the same name but different
parameters, to have different implementations and return values of different
types. Rather than invent new names all the time, method overloading can be
used when the same operation has different implementations.
For example, in our StudentRecord class we want to have a method that
prints information about the student. However, we want the print method to
print things differently depending on the parameters we pass to it. For
example, when we pass a String, we want the print method to print out the
name, address and age of the student.
When we pass 3 double values, we want the method to print the
student's name and grades.
We have the following overloaded methods inside our StudentRecord class,
public void print( String temp ){
System.out.println("Name:" + name);
System.out.println("Address:" + address);
System.out.println("Age:" + age);
}
public void print(double eGrade, double mGrade, double sGrade)
System.out.println("Name:" + name);
System.out.println("Math Grade:" + mGrade);
System.out.println("English Grade:" + eGrade);
System.out.println("Science Grade:" + sGrade);
}
When we try to call this in the following main method,
public static void main( String[] args )
{
StudentRecord annaRecord = new StudentRecord();
annaRecord.setName("Anna");
annaRecord.setAddress("Philippines");
annaRecord.setAge(15);
annaRecord.setMathGrade(80);
annaRecord.setEnglishGrade(95.5);
annaRecord.setScienceGrade(100);
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 89
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
//overloaded methods
annaRecord.print( annaRecord.getName() );
annaRecord.print( annaRecord.getEnglishGrade(),
annaRecord.getMathGrade(),
annaRecord.getScienceGrade());
}
we will have the output for the first call to print,
Name:Anna
Address:Philippines
Age:15
we will have the output for the second call to print,
Name:Anna
Math Grade:80.0
English Grade:95.5
Science Grade:100.0
CO
ES PO
ACES
L L E GE
Page 90
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.2-2
Answer each item and write it on your paper.
1. What do you call the technique of making the fields in a class private
and providing access to the fields via public methods?
2. What type of method is used to read values from class variables?
3. What do you call the allowing of method to have the same name but
different parameters, to have different implementations and return
values of different types?
CO
ES PO
ACES
L L E GE
Page 91
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.2-2
1. encapsulation
2. accessor methods
3. method overloading
CO
ES PO
ACES
L L E GE
Page 92
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
LEARNING OUTCOME NO. 3 Work with Inheritance and
Handling Exceptions
Contents:
1. Inheritance
2. Polymorphism
3. Abstract Classes, Java Interface and Exception Handling
Assessment Criteria:
1. Inheritance is implemented in accordance with Java framework
2. Code that demonstrates the use of polymorphism is developed in
accordance with Java framework
3. Super and this syntax are used to access objects and constructors in
accordance with Java framework
4. Abstract classes and interfaces are used in accordance with Java
framework
5. How exceptions alter normal program flow are determined by creating
a try-catch block.
Conditions:
PC or workstation
Programming tools
Reference Book s
Handouts/Modules/Printed Materials
Assessment Method:
Oral recitation
Written examinations
Case Study (Defense)
CO
ES PO
ACES
L L E GE
Page 93
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.3-1 Inheritance
Learning Objectives:
After reading this information sheet, you must be able to:
1. Define subclasses and superclasses
In Java, all classes, including the classes that make up the Java API,
are subclassed from the Object superclass. A sample class hierarchy is shown
below. Any class above a specific class in the class hierarchy is known as a
superclass. While any class below a specific class in the class hierarchy is
known as a subclass of that class.
Inheritance is a major advantage in object-oriented programming since
once a behavior (method) is defined in a superclass, that behavior is
automatically inherited by all subclasses. Thus, you can encode a method
only once and they can be used by all subclasses. A subclass only need to
implement the differences between itself and the parent.
CO
ES PO
ACES
L L E GE
Page 94
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
*/
public String getName(){
return name;
}
public String getAddress(){
return address;
}
public void setName( String name ){
this.name = name;
}
public void setAddress( String add ){
this.address = add;
}
}
Notice that, the attributes name and address are declared as protected.
The reason we did this is that, we want these attributes to be accessible by
the subclasses of the superclass. If we declare this as private, the subclasses
won't be able to use them. Take note that all the properties of a superclass
that are declared as public, protected and default can be accessed by its
subclasses.
Now, we want to create another class named Student. Since a student
is also a person, we decide to just extend the class Person, so that we can
inherit all the properties and methods of the existing class Person. To do this,
we write,
Inside Person:Constructor
Inside Student:Constructor
CO
ES PO
ACES
L L E GE
Page 95
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The super keyword
public Student(){
super( "SomeName", "SomeAddress" );
System.out.println("Inside Student:Constructor");
}
This code calls the second constructor of its immediate superclass (which is
Person) and executes it. Another sample code shown below,
public Student(){
super();
System.out.println("Inside Student:Constructor");
}
This code calls the default constructor of its immediate superclass (which is
Person) and
executes it.
There are a few things to remember when using the super constructor call:
1. The super() call MUST OCCUR THE FIRST STATEMENT IN A
CONSTRUCTOR.
2. The super() call can only be used in a constructor definition.
3. This implies that the this() construct and the super() calls CANNOT BOTH
OCCUR IN
THE SAME CONSTRUCTOR.
Another use of super is to refer to members of the superclass (just like the
this
reference ). For example,
public Student()
{
super.name = somename;
super.address = some address;
}
CO
ES PO
ACES
L L E GE
Page 96
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.3-1
Answer each item and write it on your paper.
1. Enumerate the 3 things to remember when using super constructor
call?
CO
ES PO
ACES
L L E GE
Page 97
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.3-1
1. The 3 things to remember when using super constructor call are:
1. The super() call must occur the first statement in A constructor.
2. The super() call can only be used in a constructor definition.
3. This implies that the this() construct and the super() calls cannot
both occur in the same constructor.
CO
ES PO
ACES
L L E GE
Page 98
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.3-2 Polymorphism
Learning Objectives:
After reading this information sheet, you must be able to:
1. Define polymorphism
Example:
CO
ES PO
ACES
L L E GE
Page 99
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
All the reference variables d,a,v,o refer to the same Deer object in the
heap.
Now, given the parent class Person and the subclass Student of our
previous example, we add another subclass of Person which is Employee.
In Java, we can create a reference that is of type superclass to an object
of its subclass.
For example,
public static main( String[] args )
{
Person ref;
Student studentObject = new Student();
Employee employeeObject = new Employee();
ref = studentObject; //Person ref points to a
// Student object
//some code here
}
Now suppose we have a getName method in our superclass Person, and
we override this
method in both the subclasses Student and Employee,
public class Person
{
public String getName(){
System.out.println(Person Name: + name);
return name;
}
}
public class Student extends Person
{
public String getName(){
System.out.println(Student Name: + name);
return name;
}
}
public class Employee extends Person
{
public String getName(){
System.out.println(Employee Name: + name);
return name;
}
}
Going back to our main method, when we try to call the getName method of
the reference Person ref, the getName method of the Student object will be
called. Now, if we assign ref to an Employee object, the getName method of
Employee will be called.
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 100
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
public static main( String[] args )
{
Person ref;
Student studentObject = new Student();
Employee employeeObject = new Employee();
ref = studentObject; //Person reference points to a
// Student object
String temp = ref.getName(); //getName of Student
//class is called
System.out.println( temp );
ref = employeeObject; //Person reference points to an
// Employee object
String temp = ref.getName(); //getName of Employee
//class is called
System.out.println( temp );
}
This ability of our reference to change behavior according to what object
it is holding is called polymorphism. Polymorphism allows multiple objects of
different subclasses to be treated as objects of a single superclass, while
automatically selecting the proper methods to apply to a particular object
based on the subclass it belongs to.
Another example that exhibits the property of polymorphism is when
we try to pass a reference to methods. Suppose we have a static method
printInformation that takes in a Person object as reference, we can actually
pass a reference of type Employee and type Student to this method as long as
it is a subclass of the class Person.
public static main( String[] args )
{
Student studentObject = new Student();
Employee employeeObject = new Employee();
printInformation( studentObject );
printInformation( employeeObject );
}
public static printInformation( Person p ){
....
}
CO
ES PO
ACES
L L E GE
Page 101
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.3-2
Answer each item and write it on your paper.
1. In Java, all Java objects are ___________ since any object will pass the
IS-A test for their own type and for the class Object.
2. The only possible way to access an object is through what?
3. What do you call the ability of an object to take on many forms in
Java?
CO
ES PO
ACES
L L E GE
Page 102
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.3-2
1. Polymorphic
2. reference variable
3. polymorphism
CO
ES PO
ACES
L L E GE
Page 103
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.3-3 Abstract Classes, Java Interfaces
and Exception Handling
Learning Objectives:
After reading this information sheet, you must be able to:
1. Describe abstract classes
2. Define interfaces
3. Explain what is exception
Abstract Classes
Now suppose we want to create a superclass wherein it has certain
methods in it that contains some implementation, and some methods wherein
we just want to be overridden by its subclasses.
For example, we want to create a superclass named LivingThing. This
class has certain methods like breath, eat, sleep and walk. However, there are
some methods in this superclass wherein we cannot generalize the behavior.
Take for example, the walk method. Not all living things walk the same way.
Take the humans for instance, we humans walk on two legs, hile other living
things like dogs walk on four legs. However, there are many haracteristics
that living things have in common, that is why we want to create a general
superclass for this.
In order to do this, we can create a superclass that has some methods
with implementations and others which do not. This kind of class is called an
abstract class.
An abstract class is a class that cannot be instantiated. It often appears
at the top of an object-oriented programming class hierarchy, defining the
broad types of actions possible with objects of all subclasses of the class.
Those methods in the abstract classes that do not have implementation
are called abstract methods. To create an abstract method, just write the
method declaration without the body and use the abstract keyword. For
example,
public abstract void someMethod();
CO
ES PO
ACES
L L E GE
Page 104
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
* abstract method walk
* We want this method to be overridden by subclasses of
* LivingThing
*/
public abstract void walk();
}
When a class extends the LivingThing abstract class, it is required to
override the abstract method walk(), or else, that subclass will also become
an abstract class, and therefore cannot be instantiated. For example,
public class Human extends LivingThing
{
public void walk(){
System.out.println("Human walks...");
}
}
If the class Human does not override the walk method, we would encounter
the following error message,
Human.java:1: Human is not abstract and does not override
abstract method walk() in LivingThing
public class Human extends LivingThing
^
1 error
Interfaces
CO
ES PO
ACES
L L E GE
Page 105
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
methods with similar signatures, we can use an interface for this. We can
create an interface class, let's say interface Relation which has some
comparison method declarations. Our interface Relation can be declared as,
public interface Relation
{
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}
Another reason for using an object's programming interface is to reveal
an object's programming interface without revealing its class. As we can see
later on the section
Interface vs. Classes, we can actually use an interface as data type.
Finally, we need to use interfaces to model multiple inheritance which
allows a class to have more than one superclass. Multiple inheritance is not
present in Java, but present in other object-oriented languages like C++.
Creating Interfaces
CO
ES PO
ACES
L L E GE
Page 106
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
public Line(double x1, double x2, double y1, double y2){
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
public double getLength(){
double length = Math.sqrt((x2-x1)*(x2-x1) +
(y2-y1)* (y2-y1));
return length;
}
public boolean isGreater( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen > bLen);
}
public boolean isLess( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen < bLen);
}
public boolean isEqual( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen == bLen);
}
}
When your class tries to implement an interface, always make sure that you
implement all the methods of that interface, or else, you would encounter this
error,
Line.java:4: Line is not abstract and does not override
abstract method isGreater(java.lang.Object,java.lang.Object) in
Relation
public class Line implements Relation
^
1 error
The following are the main differences between an interface and an abstract
class: interface methods have no body, an interface can only define
constants and an interface have no direct inherited relationship with any
particular class, they are defined independently.
CO
ES PO
ACES
L L E GE
Page 107
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Interface vs. Class
One common characteristic of an interface and class is that they are both
types. This means that an interface can be used in places where a class can
be used. For example, given a class Person and an interface PersonInterface,
the following declarations are valid:
PersonInterface pi = new Person();
Person pc = new Person();
However, you cannot create an instance from an interface. An example of
this is:
PersonInterface pi = new PersonInterface(); //COMPILE
//ERROR!!!
Another common characteristic is that both interface and class can define
methods. However, an interface does not have an implementation code while
the class have one.
Handling Exceptions
CO
ES PO
ACES
L L E GE
Page 108
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
//exception of a certain type occurs
}
finally{
//add more cleanup code here
}
Exceptions thrown during execution of the try block can be caught and
handled in a catch block. The code in the finally block is always executed. The
following are the key aspects about the syntax of the try-catch-finally
construct:
The block notation is mandatory.
For each try block, there can be one or more catch blocks, but only one
finally block.
The catch blocks and finally blocks must always appear in conjunction
with the try block, and in the above order.
A try block must be followed by at least one catch block OR one finally
block, or both.
Each catch block defines an exception handle. The header of the catch
block takes exactly one argument, which is the exception its block is
willing to handle. The exception must be of the Throwable class or one
of its subclasses.
Let's take for example a code that prints the second argument when we
try to run the code using command-line arguments. Suppose, there is no
checking inside your code for the number of arguments and we just access
the second argument args[1] right away, we'll get the following exception.
CO
ES PO
ACES
L L E GE
Page 109
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.3-3
Answer each item and write it on your paper.
1. Enumerate the key aspects about the syntax of the try-catch-finally
construct.
2. What do you call the special kind of block containing method
signatures (and possibly constants) only. It also defines the
signatures of a set of methods without the body?
3. What do you call the class that has a superclass that has some
methods with implementations and others which do not?
CO
ES PO
ACES
L L E GE
Page 110
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.3-3
1. The key aspects about the syntax of the try-catch-finally construct are:
The block notation is mandatory.
For each try block, there can be one or more catch blocks, but only one
finally block.
The catch blocks and finally blocks must always appear in conjunction
with the try block, and in the above order.
A try block must be followed by at least one catch block OR one finally
block, or both.
Each catch block defines an exception handle. The header of the catch
block takes exactly one argument, which is the exception its block is
willing to handle. The exception must be of the Throwable class or one
of its subclasses.
2. interface
3. abstract class
CO
ES PO
ACES
L L E GE
Page 111
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
LEARNING OUTCOME NO. 4 Examine Object-Oriented
Concepts and Terminology
Contents:
1. Object-oriented Programming Concepts
Assessment Criteria:
1. Important object-oriented (OO) concepts are described in accordance
with Java framework
2. Fundamental OO terminology are defined in accordance with Java
framework
Conditions:
PC or workstation
Programming tools
Reference Book s
Handouts/Modules/Printed Materials
Assessment Method:
Oral recitation
Written examinations
Case Study (Defense)
CO
ES PO
ACES
L L E GE
Page 112
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.4-1 Object-Oriented Programming
Concepts
Learning Objectives:
After reading this information sheet, you must be able to:
1. Describe the process of visual program design and development.
2. Explain the term object-oriented programming.
3. Explain the concepts of classes, objects, properties, methods, and
events.
4. List and describe the tree steps for writing a Visual Basic project.
5. Describe the various files that make up a Visual Basic project.
Identify the elements in the Visual Studio environment.
In this section, we will introduce some basic concepts of object-
oriented programming. Later on, we will discuss the concept of classes and
objects, and how to use these classes and their members. Comparison,
conversion and casting of objects will also be covered. We will focus on using
classes that are already defined in the Java class library.
What Is an Object?
CO
ES PO
ACES
L L E GE
Page 113
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
What Is a Class?
A class is a blueprint or prototype from which objects are created. This section
defines a class that models the state and behavior of a real-world object. It
intentionally focuses on the basics, showing how even a simple class can
cleanly model state and behavior.
What Is a Package?
CO
ES PO
ACES
L L E GE
Page 114
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Class Instantiation
The new operator allocates a memory for that object and returns a
reference of that memory location to you. When you create an object, you
actually invoke the class' constructor. The constructor is a method where you
place all the initializations, it has the same name as the class.
CO
ES PO
ACES
L L E GE
Page 115
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.4-1
Answer each item and write it on your paper.
1. It is a namespace for organizing classes and interfaces in a logical
manner.
2. It is a blueprint or prototype from which objects are created.
3. A software bundle of related state and behavior. which are often used
to model the real-world objects that you find in everyday life.
4. Keyword used in creating or instantiating a class.
CO
ES PO
ACES
L L E GE
Page 116
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.4-1
1. package
2. class
3. object
4. new
CO
ES PO
ACES
L L E GE
Page 117
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
LEARNING OUTCOME NO. 5 Explain Modeling and
Software Development Process
Contents:
1. Software Development Life Cycle (SDLC)
2. SDLC Models
Assessment Criteria:
1. Object-Oriented Software Development (OOSD) process is explained in
accordance with Java framework
2. Benefits of modeling software are explained in accordance with Java
framework
3. Purpose, activities, and artifacts of the following OOSD workflows
(disciplines) are explained
Conditions:
PC or workstation
Programming tools
Reference Book s
Handouts/Modules/Printed Materials
Assessment Method:
Oral recitation
Written examinations
Case Study (Defense)
CO
ES PO
ACES
L L E GE
Page 118
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.5-1 Software Development Life Cycle
(SDLC)
Learning Objectives:
After reading this information sheet, you must be able to:
1. Define what is SDLC
2. Enumerate stages of SDLC
3. Identify different SDLC Models
SDLC, Software Development Life Cycle is a process used by software
industry to design, develop and test high quality softwares. The SDLC aims to
produce a high quality software that meets or exceeds customer expectations,
reaches completion within times and cost estimates.
SDLC is the acronym of Software Development Life Cycle.
It is also called as Software development process.
The software development life cycle (SDLC) is a framework
defining tasks performed at each step in the software
development process.
ISO/IEC 12207 is an international standard for software life-
cycle processes. It aims to be the standard that defines all the
tasks required for developing and maintaining software.
What is SDLC?
SDLC is a process followed for a software project, within a software
organization. It consists of a detailed plan describing how to develop,
maintain, replace and alter or enhance specific software. The life cycle defines
a methodology for improving the quality of software and the overall
development process.
The following figure is a graphical representation of the various stages
of a typical SDLC.
CO
ES PO
ACES
L L E GE
Page 119
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
A typical Software Development life cycle consists of the following stages:
Once the requirement analysis is done the next step is to clearly define
and document the product requirements and get them approved from the
customer or the market analysts. This is done through .SRS. . Software
Requirement Specification document which consists of all the product
requirements to be designed and developed during the project life cycle.
Stage 3: Designing the product architecture
SRS is the reference for product architects to come out with the best
architecture for the product to be developed. Based on the requirements
specified in SRS, usually more than one design approach for the product
architecture is proposed and documented in a DDS - Design Document
Specification.
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 120
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
This DDS is reviewed by all the important stakeholders and based on
various parameters as risk assessment, product robustness, design
modularity , budget and time constraints , the best design approach is
selected for the product.
In this stage of SDLC the actual development starts and the product is
built. The programming code is generated as per DDS during this stage. If the
design is performed in a detailed and organized manner, code generation can
be accomplished without much hassle.
This stage is usually a subset of all the stages as in the modern SDLC
models, the testing activities are mostly involved in all the stages of SDLC.
However this stage refers to the testing only stage of the product where
products defects are reported, tracked, fixed and retested, until the product
reaches the quality standards defined in the SRS.
CO
ES PO
ACES
L L E GE
Page 121
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
SDLC Models
There are various software development life cycle models defined and
designed which are followed during software development process. These
models are also referred as "Software Development Process Models". Each
process model follows a Series of steps unique to its type, in order to ensure
success in process of software development.
Following are the most important and popular SDLC models followed in
the industry:
Waterfall Model
Iterative Model
Spiral Model
V-Model
The other related methodologies are Agile Model, RAD Model, Rapid
Application Development and Prototyping Models.
CO
ES PO
ACES
L L E GE
Page 122
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.5-1
Answer each item and write it on your paper.
1. What do you call the process followed for a software project, within a
software organization that consists of a detailed plan describing how to
develop, maintain, replace and alter or enhance specific software, and
defines a methodology for improving the quality of software and the
overall development process?
2. Stage of SDLC that is usually a subset of all the stages as in the modern
SDLC models.
3. Enumerate at least 3 types of SDLC Models
CO
ES PO
ACES
L L E GE
Page 123
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.5-1
1. Software Development Life Cycle or SDLC
2. Testing the product
3. Waterfall model, iterative model, spiral model
CO
ES PO
ACES
L L E GE
Page 124
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.5-2 SDLC Models
Learning Objectives:
After reading this information sheet, you must be able to:
1. Define and explain Waterfall, Iterative, Spiral, Agile, RAD and
Software prototype model
2. State advantages and disadvantages of various SDLC Models
WATERFALL MODEL
Waterfall model is the earliest SDLC approach that was used for
software development .
CO
ES PO
ACES
L L E GE
Page 125
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The sequential phases in Waterfall model are:
System Design
The requirement specifications from first phase are studied in this
phase and system design is prepared. System Design helps in specifying
hardware and system requirements and also helps in defining overall system
architecture.
Implementation
With inputs from system design, the system is first developed in small
programs called units, which are integrated in the next phase. Each unit is
developed and tested for its functionality which is referred to as Unit Testing.
Deployment of system
Once the functional and non functional testing is done, the product is
deployed in the customer environment or released into the market.
Maintenance
There are some issues which come up in the client environment. To fix
those issues patches are released. Also to enhance the product some better
CO
ES PO
ACES
L L E GE
Page 126
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
versions are released. Maintenance is done to deliver these changes in the
customer environment.
All these phases are cascaded to each other in which progress is seen
as flowing steadily downwards (like a waterfall) through the phases. The next
phase is started only after the defined set of goals are achieved for previous
phase and it is signed off, so the name "Waterfall Model". In this model phases
do not overlap.
Advantage
Disadvantage
CO
ES PO
ACES
L L E GE
Page 127
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The disadvantage of waterfall development is that it does not allow for
much reflection or revision. Once an application is in the testing stage, it is
very difficult to go back and change something that was not well-documented
or thought upon in the concept stage.
The following table lists out the pros and cons of Waterfall model:
ITERATIVE MODEL
CO
ES PO
ACES
L L E GE
Page 128
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
An iterative life cycle model does not attempt to start with a full
specification of requirements. Instead, development begins by specifying and
implementing just part of the software, which is then reviewed in order to
identify further requirements. This process is then repeated, producing a new
version of the software at the end of each iteration of the model.
Iterative process starts with a simple implementation of a subset of the
software requirements and iteratively enhances the evolving versions until the
full system is implemented. At each iteration, design modifications are made
and new functional capabilities are added. The basic idea behind this method
is to develop a system through repeated cycles (iterative) and in smaller
portions at a time (incremental).
Following is the pictorial representation of Iterative and Incremental
model:
CO
ES PO
ACES
L L E GE
Page 129
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Like other SDLC models, Iterative and incremental development has
some specific applications in the software industry. This model is most often
used in the following scenarios:
Resources with needed skill set are not available and are planned to be
used on contract basis for specific iterations.
There are some high risk features and goals which may change in the
future.
The following table lists out the pros and cons of Iterative and Incremental
SDLC Model:
CO
ES PO
ACES
L L E GE
Page 130
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
SPIRAL MODEL
The spiral model combines the idea of iterative development with the
systematic, controlled aspects of the waterfall model.
Spiral model is a combination of iterative development process model
and sequential linear development model i.e. waterfall model with very high
emphasis on risk analysis.
It allows for incremental releases of the product, or incremental
refinement through each iteration around the spiral.
CO
ES PO
ACES
L L E GE
Page 131
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Spiral Model design
The spiral model has four phases. A software project repeatedly passes
through these phases in iterations called Spirals.
Identification
Design
Design phase starts with the conceptual design in the baseline spiral
and involves architectural design, logical design of modules, physical product
design and final design in the subsequent spirals.
Construct or Build
CO
ES PO
ACES
L L E GE
Page 132
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Following is a diagrammatic representation of spiral model listing the
activities in each phase:
CO
ES PO
ACES
L L E GE
Page 133
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Long-term project commitment because of potential changes to
economic priorities as the requirements change with time.
The advantage of spiral lifecycle model is that it allows for elements of the
product to be added in when they become available or known. This assures
that there is no conflict with previous requirements and design.
This method is consistent with approaches that have multiple software builds
and releases and allows for making an orderly transition to a maintenance
activity. Another positive aspect is that the spiral model forces early user
involvement in the system development effort.
On the other side, it takes very strict management to complete such products
and there is a risk of running the spiral in indefinite loop. So the discipline of
change and the extent of taking change requests is very important to develop
and deploy the product successfully.
The following table lists out the pros and cons of Spiral SDLC Model:
CO
ES PO
ACES
L L E GE
Page 134
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
AGILE MODEL
Agile Methods break the product into small incremental builds. These
builds are provided in iterations. Each iteration typically lasts from about one
to three weeks. Every iteration involves cross functional teams working
simultaneously on various areas like planning, requirements analysis, design,
coding, unit testing, and acceptance testing.
What is Agile?
CO
ES PO
ACES
L L E GE
Page 135
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Agile thought process had started early in the software development
and started becoming popular with time due to its flexibility and adaptability.
The most popular agile methods include Rational Unified Process
(1994), Scrum (1995), Crystal Clear, Extreme Programming (1996), Adaptive
Software Development, Feature Driven Development, and Dynamic Systems
Development Method (DSDM) (1995). These are now collectively referred to as
agile methodologies, after the Agile Manifesto was published in 2001.
CO
ES PO
ACES
L L E GE
Page 136
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Customer interaction is the backbone of Agile methodology, and open
communication with minimum documentation are the typical features of Agile
development environment. The agile teams work in close collaboration with
each other and are most often located in the same geographical location.
Following table lists out the pros and cons of Agile Model:
RAD MODEL
CO
ES PO
ACES
L L E GE
Page 137
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Rapid Application development focuses on gathering customer
requirements through workshops or focus groups, early testing of the
prototypes by the customer using iterative concept, reuse of the existing
prototypes (components), continuous integration and rapid delivery.
What is RAD?
RAD model distributes the analysis, design, build, and test phases into
a series of short, iterative development cycles. Following are the phases of
RAD Model:
Business Modeling
The business model for the product under development is designed in
terms of flow of information and the distribution of information between
various business channels. A complete business analysis is performed to find
the vital information for business, how it can be obtained, how and when is
the information processed and what are the factors driving successful flow of
information.
Data Modeling
The information gathered in the Business Modeling phase is reviewed
and analyzed to form sets of data objects vital for the business. The attributes
of all data sets is identified and defined. The relation between these data
objects are established and defined in detail in relevance to the business
model.
Process Modeling
The data object sets defined in the Data Modeling phase are converted
to establish the business information flow needed to achieve specific business
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 138
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
objectives as per the business model. The process model for any changes or
enhancements to the data object sets is defined in this phase. Process
descriptions for adding , deleting, retrieving or modifying a data object are
given.
Application Generation
The actual system is built and coding is done by using automation tools
to convert process and data models into actual prototypes.
CO
ES PO
ACES
L L E GE
Page 139
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
RAD Model Vs Traditional SDLC
The traditional SDLC follows a rigid process models with high emphasis
on requirement analysis and gathering before the coding starts. It puts a
pressure on the customer to sign off the requirements before the project starts
and the customer doesn.t get the feel of the product as there is no working
build available for a long time.
The customer may need some changes after he actually gets to see the
software, however the change process is quite rigid and it may not be feasible
to incorporate major changes in the product in traditional SDLC.
RAD model focuses on iterative and incremental delivery of working
models to the customer. This results in rapid delivery to the customer and
customer involvement during the complete development cycle of product
reducing the risk of non conformance with the actual user requirements.
RAD SDLC model should be chosen only if domain experts are available
with relevant business knowledge.
CO
ES PO
ACES
L L E GE
Page 140
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Following table lists out the pros and cons of RAD Model:
The prototype does not always hold the exact logic used in the actual
software application and is an extra effort to be considered under effort
estimation.
CO
ES PO
ACES
L L E GE
Page 141
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Prototyping is used to allow the users evaluate developer proposals and
try them out before implementation.
It also helps understand the requirements which are user specific and
may not have been considered by the developer during product design.
CO
ES PO
ACES
L L E GE
Page 142
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
For example, database requirements, interaction and data processing loads
in a given sub system.
Software that involves too much of data processing and most of the
functionality is internal with very little user interface does not usually benefit
CO
ES PO
ACES
L L E GE
Page 143
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
from prototyping. Prototype development could be an extra overhead in such
projects and may need lot of extra efforts.
Software Prototyping Pros and Cons
Following table lists out the pros and cons of Software Prototype Model:
CO
ES PO
ACES
L L E GE
Page 144
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.5-2
Answer each item and write it on your paper.
1. The earliest SDLC approach that was used for software development
is?
2. It is a working model of software with some limited functionality.
3. An SDLC Model that should be used only when a system can be
modularized to be delivered in incremental manner.
CO
ES PO
ACES
L L E GE
Page 145
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.5-2
1. Waterfall model
2. Prototype
3. Rapid Application Development (RAD)
CO
ES PO
ACES
L L E GE
Page 146
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
LEARNING OUTCOME NO. 6 Create Use Case Diagrams
and Use Case Scenarios
Contents:
1. Use Case Diagram
Assessment Criteria:
1. The need for a Use Case Diagram is justified in accordance with Java
framework
2. Use Case Diagram for a software system is developed based on the goals
of the business owner
3. Use Case Diagrams is developed based on the goals of all the
stakeholders
4. Use Case form is created describing a summary of the scenarios in the
main and alternate flows
Conditions:
Assessment Method:
Oral recitation
Written examinations
Case Study (Defense)
CO
ES PO
ACES
L L E GE
Page 147
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.6-1 Use Case Diagram and Scenarios
Learning Objectives:
After reading this information sheet, you must be able to:
1. State the purpose of Use Case diagram
2. Determine when to use Use case diagram
3. Define what is a scenario
4. Enumerate criteria for a good scenario
These internal and external agents are known as actors. So use case
diagrams are consists of actors, use cases and their relationships. The
diagram is used to model the system/subsystem of an application. A single
use case diagram captures a particular functionality of a system.
So to model the entire system numbers of use case diagrams are used.
Purpose
CO
ES PO
ACES
L L E GE
Page 148
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Now when the initial task is complete use case diagrams are modelled to
present the outside view.
Use case diagrams are considered for high level requirement analysis of
a system. So when the requirements of a system are analyzed the
functionalities are captured in use cases.
So we can say that uses cases are nothing but the system
functionalities written in an organized manner. Now the second things which
are relevant to the use cases are the actors. Actors can be defined as
something that interacts with the system.
Actors
The name of a use case is very important. So the name should be chosen
in such a way so that it can identify the functionalities performed.
CO
ES PO
ACES
L L E GE
Page 149
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Do not try to include all types of relationships. Because the main
purpose of the diagram is to identify requirements.
The SpecialOrder and NormalOrder use cases are extended from Order use
case. So they have extends relationship. Another important point is to identify
the system boundary which is shown in the picture. The actor Customer lies
outside the system as it is an external user of the system.
Use Cases can also have relationships with other Use Cases. The three most
typical types of relationships between Use Cases are:
<<include>> which specifies that a Use Case takes place inside another
Use Case
CO
ES PO
ACES
L L E GE
Page 150
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Where to Use Case Diagrams?
Use case diagrams specify the events of a system and their flows. But
use case diagram never describes how they are implemented. Use case
diagram can be imagined as a black box where only the input, output and the
function of the black box is known.
These diagrams are used at a very high level of design. Then this high
level design is refined again and again to get a complete and practical picture
of the system. A well structured use case also describes the pre condition,
post condition, exceptions. And these extra elements are used to make test
cases when performing the testing.
Although the use cases are not a good candidate for forward and reverse
engineering but still they are used in a slight different way to make forward
and reverse engineering. And the same is true for reverse engineering. Still
use case diagram is used differently to make it a candidate for reverse
engineering.
In forward engineering use case diagrams are used to make test cases
and in reverse engineering use cases are used to prepare the requirement
details from the existing application.
So the following are the places where use case diagrams are used:
Reverse engineering.
Forward engineering.
CO
ES PO
ACES
L L E GE
Page 151
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
SCENARIOS
Similar to a use case, scenarios are a written story that explains how a
person will use a product, service, or system to achieve a goal.
Scenarios are different in that they include the context of use and can
include multiple use cases.
Good Scenario
Writing Scenarios
The following are the steps to be undertaken in writing scenarios.
Where will the people using your system be, physically, when they
encounter it?
What state is the actual product or service in when they first
acknowledge it?
CO
ES PO
ACES
L L E GE
Page 152
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
List the goals a user may have, as they pertain to your product or
service.
Stack rank the goals, putting them in order from most important to
achieve using this system or service to least important to achieve using this
system or service.
Craft Stories
Using the people, context and goals as a starting point, craft a narrative
that explains how a person will use your system to achieve their goals. Dont
try to achieve all goals in a single epic story; instead, create ultiple stories,
one for each goal. Keep the conversation at a high, behavioral level, rather
than a low user interface level:
Good:
Fred grabs his phone. He opens the beer-finding
app, and locates a beer nearby. He chooses to have
it delivered, enters his payment information, and
completes his order.
Bad:
Fred grabs his phone. He taps the beer finding app
icon. He taps the zip code input box, and the
onscreen keyboard appears. He taps the numbers
for his zip code, and then taps find beer. An
hourglass appears on his screen, and after several
seconds, search results begin to show up..
CO
ES PO
ACES
L L E GE
Page 153
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.6-1
Answer each item and write it on your paper.
1. Diagrams that are used to gather the requirements of a system
including internal and external influences.
2. Enumerate purposes of use case diagrams.
3. A type of use case which specifies that a Use Case takes place inside
another Use Case.
CO
ES PO
ACES
L L E GE
Page 154
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.6-1
1. Use case diagram
2. Purpose of a use case diagram are as follows:
Used to gather requirements of a system.
CO
ES PO
ACES
L L E GE
Page 155
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
LEARNING OUTCOME NO. 7 Transition Analysis to
Design using Interaction Diagrams
Contents:
1. Unified Modeling Language (UML) Overview and Basic Notation
2. UML Diagrams
Assessment Criteria:
1. Purpose and elements of the Design model are explained in accordance
with Java framework
2. Essential elements of a UML Communication diagram are identified in
accordance with Java framework
3. Communication diagram view of the Design model is created in
accordance with Java framework
4. Sequence diagram view of the Design model is created in accordance
with Java framework
Conditions:
The students/trainees must be provided with the following:
PC or workstation
Programming tools
Reference Book s
Handouts/Modules/Printed Materials
Assessment Method:
Oral recitation
Written examinations
Case Study (Defense)
CO
ES PO
ACES
L L E GE
Page 156
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.7-1 Unified Modeling Language (UML)
Overview and Basic Notation
Learning Objectives:
After reading this information sheet, you must be able to:
1. State the goal of UML
2. Describe conceptual model of UML
3. Draw and the graphical notations used in structural things in UML
UML was created by Object Management Group (OMG) and UML 1.0
specification draft was proposed to the OMG in January 1997.
UML is not a programming language but tools can be used to generate code
in Java language (as well as some other languages) using UML diagrams. UML
has a direct relation with object oriented analysis and design. After some
standardization UML is become an OMG (Object Management Group)
standard.
Goals of UML
CO
ES PO
ACES
L L E GE
Page 157
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
organize and consolidate the object oriented development. At that point of
time UML came into picture.
There are a number of goals for developing UML but the most important
is to define some general purpose modeling language which all modelers can
use and also it needs to be made simple to understand and use.
UML diagrams are not only made for developers but also for business
users, common people and anybody interested to understand the system. The
system can be a software or non software. So it must be clear that UML is not
a development method rather it accompanies with processes to make a
successful system.
At the conclusion the goal of UML can be defined as a simple modeling
mechanism to model all possible practical systems in today.s complex
environment.
CO
ES PO
ACES
L L E GE
Page 158
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The objects are the real world entities that exist around us and the basic
concepts like abstraction, encapsulation, inheritance, polymorphism all can
be represented using UML.
So UML is powerful enough to represent all the concepts exists in object
oriented analysis and design. UML diagrams are representation of object
oriented concepts only. So before learning UML, it becomes important to
understand OO concepts in details.
CO
ES PO
ACES
L L E GE
Page 159
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
There are three basic steps where the OO concepts are applied and
implemented. The steps can be defined as
The second phase is object oriented design. During this phase emphasis
is given upon the requirements and their fulfilment. In this stage the
objects are collaborated according to their intended association. After
the association is complete the design is also complete.
CO
ES PO
ACES
L L E GE
Page 160
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
UML notations are the most important elements in modeling. Efficient
and appropriate use of notations is very important for making a complete and
meaningful model. The model is useless unless its purpose is depicted
properly.
Structural Things
Graphical notations used in structural things are the most widely used in
UML. These are considered as the nouns of UML models. Following are the
list of structural things.
Classes
Interface
Collaboration
Use case
Active classes
Components
Nodes
Class Notation
CO
ES PO
ACES
L L E GE
Page 161
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Classes are used to represent objects. Objects can be anything having
properties and responsibility.
Object Notation
The object is represented in the same way as the class. The only difference is
the name which is underlined as shown below.
Interface Notation
CO
ES PO
ACES
L L E GE
Page 162
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Interface is used to describe functionality without implementation. Interface
is the just like a template where you define different functions not the
implementation. When a class implements the interface it also implements
the functionality as per the requirement.
Collaboration Notation:
Use case is represented as an eclipse with a name inside it. It may contain
additional responsibilities.
CO
ES PO
ACES
L L E GE
Page 163
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Use case is used to capture high level functionalities of a system.
Actor Notation:
Initial state is defined to show the start of a process. This notation is used in
almost all diagrams.
The usage of Initial State Notation is to show the starting point of a process.
CO
ES PO
ACES
L L E GE
Page 164
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Final State Notation:
Final state is used to show the end of a process. This notation is also used
in almost all diagrams to describe the end.
Active class looks similar to a class with a solid border. Active class is
generally used to describe concurrent behaviour of a system.
Component Notation:
CO
ES PO
ACES
L L E GE
Page 165
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Node Notation:
Node is used to represent physical part of a system like server, network etc.
BEHAVIOURAL THINGS:
Dynamic parts are one of the most important elements in UML. UML has a
set of powerful features to represent the dynamic part of software and non
software systems. These features include interactions and state machines.
Interaction Notation:
CO
ES PO
ACES
L L E GE
Page 166
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Interaction is used to represent communication among the components of a
system.
State machine describes the different states of a component in its life cycle.
The notations are described in the following diagram.
CO
ES PO
ACES
L L E GE
Page 167
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
State machine is used to describe different states of a system component.
The state can be active, idle or any other depending upon the situation.
Grouping Things:
Organizing the UML models are one of the most important aspects of the
design. In UML there is only one element available for grouping and that is
package.
Package Notation:
Package notation is shown below and this is used to wrap the components of
a system.
CO
ES PO
ACES
L L E GE
Page 168
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Annotational Things:
Note Notation:
This notation is shown below and they are used to provide necessary
information of a system.
Relationships
Dependency
Association
Generalization
Extensibility
Dependency Notation:
CO
ES PO
ACES
L L E GE
Page 169
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Dependency is used to represent dependency between two elements of a
system.
Association Notation:
Generalization Notation:
CO
ES PO
ACES
L L E GE
Page 170
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Extensibility Notation:
CO
ES PO
ACES
L L E GE
Page 171
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.7-1
Answer each item and write it on your paper.
1. A standard language for specifying, visualizing, constructing, and
documenting the artifacts of software systems that was created by
Object Management Group
2. Enumerate at least 6 notations used in UML.
3. A notation that is defined as some internal or external entity that
interacts with the system. Draw the notation that is being referred by
this.
CO
ES PO
ACES
L L E GE
Page 172
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.7-1
1. Unified Modeling Language (UML)
2. Notations used in UML are:
a. Class notation
b. Object notation
c. Interface notation
d. Class notation
e. Collaboration notation
f. Interaction notation
4. Actor notation
CO
ES PO
ACES
L L E GE
Page 173
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.7-2 UML Diagrams
Learning Objectives:
After reading this information sheet, you must be able to:
1. Define what is structural diagram
2. Enumerate four structural diagrams
3. Define what is behavioral diagram
4. Enumerate behavioral diagrams
We have discussed about the building blocks and other necessary elements
of UML. Now we need to understand where to use those elements.
The elements are like components which can be associated in different ways
to make a complete UML pictures which is known as diagram. So it is very
important to understand the different diagrams to implement the knowledge
in real life systems.
You can also create your own set of diagrams to meet your requirements.
Diagrams are generally made in an incremental and iterative way.
There are two broad caetgories of diagrams and then are again divided into
sub-categories:
Structural Diagrams
Behavioral Diagrams
Structural Diagrams
The structural diagrams represent the static aspect of the system. These static
aspects represent those parts of a diagram which forms the main structure
and therefore stable.
CO
ES PO
ACES
L L E GE
Page 174
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Class diagram
Object diagram
Component diagram
Deployment diagram
Class Diagram
Class diagrams are the most common diagrams used in UML. Class diagram
consists of classes, interfaces, associations and collaboration.
Class diagrams basically represent the object oriented view of a system which
is static in nature.
Object Diagram
Object diagrams are a set of objects and their relationships just like class
diagrams and also represent the static view of the system.
The usage of object diagrams is similar to class diagrams but they are used
to build prototype of a system from practical perspective.
Component Diagram
During design phase software artifacts (classes, interfaces etc) of a system are
arranged in different groups depending upon their relationship. Now these
groups are known as components.
CO
ES PO
ACES
L L E GE
Page 175
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Deployment Diagram
Deployment diagrams are a set of nodes and their relationships. These nodes
are physical entities where the components are deployed.
Note: If the above descriptions and usages are observed carefully then it is very
clear that all the diagrams are having some relationship with one another.
Component diagrams are dependent upon the classes, interfaces etc which are
part of class/object diagram. Again the deployment diagram is dependent upon
the components which are used to make a component diagrams.
Behavioral Diagrams
Any system can have two aspects, static and dynamic. So a model is
considered as complete when both the aspects are covered fully.
Sequence diagram
Collaboration diagram
Statechart diagram
Activity diagram
Sequence Diagram:
CO
ES PO
ACES
L L E GE
Page 176
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Collaboration Diagram:
Statechart Diagram:
Activity Diagram:
Activity diagrams are used to visualize the flow of controls in a system. This
is prepared to have an idea of how the system will work when executed.
CLASS DIAGRAMS
CO
ES PO
ACES
L L E GE
Page 177
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The class diagram describes the attributes and operations of a class and also
the constraints imposed on the system. The class diagrams are widely used
in the modelling of object oriented systems because they are the only UML
diagrams which can be mapped directly with object oriented languages.
Purpose:
The purpose of the class diagram is to model the static view of an application.
The class diagrams are the only diagrams which can be directly mapped with
object oriented languages and thus widely used at the time of construction.
The UML diagrams like activity diagram, sequence diagram can only give the
sequence flow of the application but class diagram is a bit different. So it is
the most popular UML diagram in the coder community.
Class diagrams are the most popular UML diagrams used for construction of
software applications. So it is very important to learn the drawing procedure
of class diagram.
Class diagrams have lot of properties to consider while drawing but here the
diagram will be considered from a top level view.
CO
ES PO
ACES
L L E GE
Page 178
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
For each class minimum number of properties should be specified.
Because unnecessary properties will make the diagram complicated.
Use notes when ever required to describe some aspect of the diagram.
Because at the end of the drawing it should be understandable to the
developer/coder.
Finally, before making the final version, the diagram should be drawn
on plain paper and rework as many times as possible to make it correct.
First of all Order and Customer are identified as the two elements of the
system and they have a one to many relationship because a customer
can have multiple orders.
We would keep Order class is an abstract class and it has two concrete
classes (inheritance relationship) SpecialOrder and NormalOrder.
The two inherited classes have all the properties as the Order class. In
addition they have additional functions like dispatch () and receive ().
So the following class diagram has been drawn considering all the points
mentioned above:
CO
ES PO
ACES
L L E GE
Page 179
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Where to use Class Diagrams?
Generally UML diagrams are not directly mapped with any object oriented
programming languages but the class diagram is an exception.
Class diagram clearly shows the mapping with object oriented languages like
Java, C++ etc. So from practical experience class diagram is generally used
for construction purpose.
OBJECT DIAGRAM
Object diagrams are derived from class diagrams so object diagrams are
dependent upon class diagrams.
Object diagrams are used to render a set of objects and their relationships as
an instance.
Purpose:
CO
ES PO
ACES
L L E GE
Page 180
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
It means the object diagram is more close to the actual system behaviour. The
purpose is to capture the static view of a system at a particular moment.
So both diagrams are made of same basic elements but in different form. In
class diagram elements are in abstract form to represent the blue print and
in object diagram the elements are in concrete form to represent the real world
object.
From the above discussion it is clear that a single object diagram cannot
capture all the necessary instances or rather cannot specify all objects of a
system. So the solution is:
First, analyze the system and decide which instances are having
important data and association.
Second, consider only those instances which will cover the
functionality.
Third, make some optimization as the numbers of instances are
unlimited.
CO
ES PO
ACES
L L E GE
Page 181
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Now after this the following things are to be decided before starting the
construction of the diagram:
Customer
Order
SpecialOrder
NormalOrder
Now the customer object (C) is associated with three order objects (O1, O2
and O3). These order objects are associated with special order and normal
order objects (S1, S2 and N1). The customer is having the following three
orders with different numbers (12, 32 and 40) for the particular time
considered.
Now the customer can increase number of orders in future and in that
scenario the object diagram will reflect that. If order, special order and normal
order objects are observed then we you will find that they are having some
values.
For orders the values are 12, 32, and 40 which implies that the objects are
having these values for the particular moment (here the particular time when
the purchase is made is considered as the moment) when the instance is
captured.
The same is for special order and normal order objects which are having
number of orders as 20, 30 and 60. If a different time of purchase is
considered then these values will change accordingly.
So the following object diagram has been drawn considering all the points
mentioned above:
CO
ES PO
ACES
L L E GE
Page 182
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Where to use Object Diagrams?
Now if you take a snap of the running train then you will find a static picture
of it having the following:
So here we can imagine the snap of the running train is an object having the
above values. And this is true for any real life simple or complex system. In a
brief, object diagrams are used for:
COMPONENT DIAGRAM
Now the question is what are these physical aspects? Physical aspects are the
elements like executables, libraries, files, documents etc which resides in a
node.
CO
ES PO
ACES
L L E GE
Page 183
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
So component diagrams are used to visualize the organization and
relationships among components in a system. These diagrams are also used
to make executable systems.
Purpose:
So from that point component diagrams are used to visualize the physical
components in a system. These components are libraries, packages, files etc.
Initially the system is designed using different UML diagrams and then when
the artifacts are ready component diagrams are used to get an idea of the
implementation.
CO
ES PO
ACES
L L E GE
Page 184
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Files used in the system.
Libraries and other artifacts relevant to the application.
Relationships among the artifacts.
Now after identifying the artifacts the following points needs to be followed:
Use a meaningful name to identify the component for which the diagram
is to be drawn.
Prepare a mental layout before producing using tools.
Use notes for clarifying important points.
The following is a component diagram for order management system. Here the
artifacts are files. So the diagram shows the files in the application and their
relationships. In actual the component diagram also contains dlls, libraries,
folders etc.
In the following diagram four files are identified and their relationships are
produced. Component diagram cannot be matched directly with other UML
diagrams discussed so far. Because it is drawn for completely different
purpose.
So the following component diagram has been drawn considering all the
points mentioned above:
CO
ES PO
ACES
L L E GE
Page 185
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Where to use Component Diagrams?
We have already described that component diagrams are used to visualize the
static implementation view of a system. Component diagrams are special type
of UML diagrams used for different purposes.
DEPLOYMENT DIAGRAM
Purpose:
The name Deployment itself describes the purpose of the diagram. Deployment
diagrams are used for describing the hardware components where software
components are deployed. Component diagrams and deployment diagrams
are closely related.
CO
ES PO
ACES
L L E GE
Page 186
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Component diagrams are used to describe the components and deployment
diagrams shows how they are deployed in hardware.
So most of the UML diagrams are used to handle logical components but
deployment diagrams are made to focus on hardware topology of a system.
Deployment diagrams are used by the system engineers.
Performance
Scalability
Maintainability
Portability
Nodes
Relationships among nodes
Monitor
Modem
Caching server
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 187
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Server
So the following deployment diagram has been drawn considering all the
points mentioned above:
INTERACTION DIAGRAM
From the name Interaction it is clear that the diagram is used to describe some
type of interactions among the different elements in the model. So this
interaction is a part of dynamic behaviour of the system.
Purpose:
CO
ES PO
ACES
L L E GE
Page 188
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
How to draw Interaction Diagram?
So the following things are to identified clearly before drawing the interaction
diagram:
The following diagram has shown the message sequence for SpecialOrder
object and the same can be used in case of NormalOrder object. Now it is
important to understand the time sequence of message flows. The message
flow is nothing but a method call of an object.
The first call is sendOrder () which is a method of Order object. The next call
is confirm () which is a method of SpecialOrder object and the last call is
Dispatch () which is a method of SpecialOrder object. So here the diagram is
mainly describing the method calls from one object to another and this is also
the actual scenario when the system is running.
CO
ES PO
ACES
L L E GE
Page 189
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The Collaboration Diagram:
The method calls are similar to that of a sequence diagram. But the difference
is that the sequence diagram does not describe the object organization where
as the collaboration diagram shows the object organization.
Now to choose between these two diagrams the main emphasis is given on the
type of requirement. If the time sequence is important then sequence diagram
is used and if organization is required then collaboration diagram is used.
CO
ES PO
ACES
L L E GE
Page 190
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Figure below presents a simplified collaboration diagram for displaying a
seminar details screen or page. The rectangles represent the various objects
involved that make up the application. The lines between the classes
represent the relationships (associations, composition, dependencies, or
inheritance) between them. The same notation for classes and objects used
on UML sequence diagrams are used on UML communication diagrams,
another example of the consistency of the UML. The details of your
associations, such as their multiplicities, are not modeled because this
information is contained on your UML class diagrams: remember, each UML
diagram has its own specific purpose and no single diagram is sufficient on
its own. Messages are depicted as a labeled arrow that indicates the direction
of the message, using a notation similar to that used on sequence diagrams.
CO
ES PO
ACES
L L E GE
Page 191
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The next figure summarizes the basic notation for modeling messages on
communication diagrams. Optionally, you may indicate the sequence number
in which the message is sent, indicate an optional return value, and indicate
the method name and the parameters (if any) passed to it. Sequence numbers
should be in the format A.B.C.D to indicate the order in which the messages
where sent. In Figure 1 message 1 is sent to the Seminar object which in turn
sends messages 1.1 and then 1.2 to the Course object. Message 5 is sent to
the Seminar object, which sends message 5.1 to enrollment, which in turn
sends message 5.1.1 to student, and it finally sends message 5.1.1.1 to itself.
Notice how a recursive connection, or a self connection, is required so that
student can do this.
CO
ES PO
ACES
L L E GE
Page 192
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
[sequenceNumber:] methodName(parameters) [: returnValue]
In you see the Seminar Details user interface object collaborates with the
seminar object to obtain the information needed to display its information. It
first invokes the getter method to obtain the name of the seminar. To fulfill
this responsibility, the seminar object then collaborates with the course object
that describes it to obtain the name of the course. In this example I showed
return values for some messages but not others to provide examples of how
to do it. I'll either indicate the type of the return value, for example string, or
the result, such as seminarName. Normally I wouldn't show return values on
this diagram because the messages are named well - my heuristic is to only
model return values when it isn't clear what the message returns. Better yet
I try to find a new name for the message (remember, messages map to
operations implemented by your classes).
You draw communication diagrams in the same way as you draw sequence
diagrams, the only real difference is that you lay out the notation in a different
manner. To tell you the truth I rarely find the need to create communication
diagrams although I have found them useful in situations where we didn't
have use cases as the primary requirements artifact. Sequence diagrams and
use cases seem to go hand in hand because of how easy it is to model the
sequential logic of a use case using a sequence diagram. Communication
diagrams seem to be preferred by people with a structure bent, people that
focus on UML class diagrams or class responsibility collaborator (CRC) cards,
because of the similarity of communication diagrams with those types of
artifacts. As always, follow the AM practice Apply the Right Artifact(s) and use
the most appropriate technique for your situation.
CO
ES PO
ACES
L L E GE
Page 193
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The main purposes of both the diagrams are similar as they are used to
capture the dynamic behaviour of a system. But the specific purposes are
more important to clarify and understood.
Sequence diagrams are used to capture the order of messages flowing from
one object to another. And the collaboration diagrams are used to describe
the structural organizations of the objects taking part in the interaction. A
single diagram is not sufficient to describe the dynamic aspect of an entire
system so a set of diagrams are used to capture is as a whole.
The interaction diagrams are used when we want to understand the message
flow and the structural organization. Now message flow means the sequence
of control flow from one object to another and structural organization means
the visual organization of the elements in a system.
CO
ES PO
ACES
L L E GE
Page 194
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Where to use Deployment Diagrams?
CO
ES PO
ACES
L L E GE
Page 195
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
To model the hardware topology of a system.
To model embedded system.
To model hardware details for a client/server system.
To model hardware details of a distributed application.
Forward and reverse engineering.
STATECHARTS DIAGRAM
The name of the diagram itself clarifies the purpose of the diagram and other
details. It describes different states of a component in a system. The states
are specific to a component/object of a system.
Purpose:
Statechart diagram is one of the five UML diagrams used to model dynamic
nature of a system. They define different states of an object during its lifetime.
And these states are changed by events. So Statechart diagrams are useful to
model reactive systems. Reactive systems can be defined as a system that
responds to external or internal events.
Statechart diagram describes the flow of control from one state to another
state. States are defined as a condition in which an object exists and it
changes when some event is triggered. So the most important purpose of
Statechart diagram is to model life time of an object from creation to
termination.
Statechart diagrams are also used for forward and reverse engineering of a
system. But the main purpose is to model reactive system.
CO
ES PO
ACES
L L E GE
Page 196
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
How to draw Statechart Diagram?
Statechart diagram is used to describe the states of different objects in its life
cycle. So the emphasis is given on the state changes upon some internal or
external events. These states of objects are important to analyze and
implement them accurately.
Statechart diagrams are very important for describing the states. States can
be identified as the condition of objects when a particular event occurs.
The first state is an idle state from where the process starts. The next states
are arrived for events like send request, confirm request, and dispatch order.
These events are responsible for state changes of order object.
During the life cycle of an object (here order object) it goes through the
following states and there may be some abnormal exists also. This abnormal
exit may occur due to some problem in the system. When the entire life cycle
is complete it is considered as the complete transaction as mentioned below.
CO
ES PO
ACES
L L E GE
Page 197
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Where to use Statechart Diagrams?
Statechart diagram defines the states of a component and these state changes
are dynamic in nature. So its specific purpose is to define state changes
triggered by events. Events are internal or external factors influencing the
system.
Statechart diagrams are used to model states and also events operating on
the system. When implementing a system it is very important to clarify
different states of an object during its life time and statechart diagrams are
used for this purpose. When these states and events are identified they are
used to model it and these models are used during implementation of the
system.
CO
ES PO
ACES
L L E GE
Page 198
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
To model reactive system. Reactive system consists of reactive objects.
To identify events responsible for state changes.
Forward and reverse engineering.
ACTIVITY DIAGRAM
Activity diagram is basically a flow chart to represent the flow form one activity
to another activity. The activity can be described as an operation of the
system.
So the control flow is drawn from one operation to another. This flow can be
sequential, branched or concurrent. Activity diagrams deals with all type of
flow control by using different elements like fork, join etc.
Purpose:
The basic purposes of activity diagrams are similar to other four diagrams. It
captures the dynamic behaviour of the system. Other four diagrams are used
to show the message flow from one object to another but activity diagram is
used to show message flow from one activity to another.
Activity is a particular operation of the system. Activity diagrams are not only
used for visualizing dynamic nature of a system but they are also used to
construct the executable system by using forward and reverse engineering
techniques. The only missing thing in activity diagram is the message part.
It does not show any message flow from one activity to another. Activity
diagram is some time considered as the flow chart. Although the diagrams
looks like a flow chart but it is not. It shows different flow like parallel,
branched, concurrent and single.
CO
ES PO
ACES
L L E GE
Page 199
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
they have some additional capabilities. These additional capabilities include
branching, parallel flow, swimlane etc.
Activities
Association
Conditions
Constraints
After receiving the order request condition checks are performed to check if it
is normal or special order. After the type of order is identified dispatch activity
is performed and that is marked as the termination of the process.
CO
ES PO
ACES
L L E GE
Page 200
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Where to use Activity Diagrams?
The basic usage of activity diagram is similar to other four UML diagrams.
The specific usage is to model the control flow from one activity to another.
This control flow does not include messages.
The activity diagram is suitable for modeling the activity flow of the system.
An application can have multiple systems. Activity diagram also captures
these systems and describes flow from one system to another. This specific
usage is not available in other diagrams. These systems can be database,
external queues or any other system.
Now we will look into the practical applications of the activity diagram. From
the above discussion it is clear that an activity diagram is drawn from a very
high level. So it gives high level view of a system. This high level view is mainly
for business users or any other person who is not a technical person.
This diagram is used to model the activities which are nothing but business
requirements. So the diagram has more impact on business understanding
rather implementation details.
CO
ES PO
ACES
L L E GE
Page 201
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.7-2
Answer each item and write it on your paper.
1. A UML diagram that is basically a flow chart to represent the flow
form one activity to another activity. The activity can be described as
an operation of the system.
2. A UML diagram that is used when we want to understand the
message flow and the structural organization.
3. A UML Diagram that represents the structural organization of a
system and the messages sent/received. Structural organization
consists of objects and links.
CO
ES PO
ACES
L L E GE
Page 202
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.7-2
1. Activity diagram
2. Sequence diagram
3. Collaboration/communication diagram
CO
ES PO
ACES
L L E GE
Page 203
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
LEARNING OUTCOME NO. 8 Introduce Architectural
Concepts and Architecture Tiers Diagrams
Contents:
1. Java Enterprise System Solution Architectures
Assessment Criteria:
1. Difference between architecture and design is distinguished in
accordance with Java framework
2. Tiers, layers, and systemic qualities are described in accordance with
Java framework
3. Architecture workflow is described in accordance with Java framework
4. Architecture Tiers are defined in accordance with Java framework
Conditions:
1. Reference Book
2. Handouts/Modules/Printed Materials
Assessment Method:
Oral recitation
Written examinations
Case Study (Defense)
CO
ES PO
ACES
L L E GE
Page 204
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Information Sheet 1.8-1 Java Enterprise System Solution
Architectures
Learning Objectives:
After reading this information sheet, you must be able to:
1. Enumerate architectural dimensions of Java Enterprise Systems
CO
ES PO
ACES
L L E GE
Page 205
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
components used to build such systems. In particular, the design of
distributed systems involves the following three architectural dimensions:
CO
ES PO
ACES
L L E GE
Page 206
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
implement secure access, and so forth. This section explains the key role
played by a number of Java ES components in providing these infrastructure
services.
CO
ES PO
ACES
L L E GE
Page 207
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The following paragraphs describe the different infrastructure service levels
and refer to Java programming language artifacts, where relevant. The service
levels are described from lowest to highest, as shown in Dimension 1:
CO
ES PO
ACES
L L E GE
Page 208
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
services are application-level business services, normally provided by
stand-alone servers (such as an email server or a calendar server).
Integration. Provides the services that aggregate existing business
services. Provides a common interface for accessing the services, as in
a portal, or by integrating the services through a process engine that
coordinates them within a production workflow. Integration can also
take place as business-to-business interactions between different
enterprises.
CO
ES PO
ACES
L L E GE
Page 209
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Java Enterprise System Infrastructure Service Dependencies
Table below shows the specific relationships between the Java ES system
service components, listed from top to bottom, as shown in Java ES System
Service Components.
Access Manager
Directory Server
If configured to use
corresponding
Channels:
CBLMs on Document No. APC-NCIV-04
Programming NC III Date Developed: Issued by:
ECHNIC
YT September 2013
(JAVA)
L
CO
ES PO
ACES
L L E GE
Page 210
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Calendar Server
Messaging Server
Instant Messaging
Messaging Directory Server Calendar Server (for email
Server notifications)
Access Manager (for
single sign-on) Portal Server (for messaging
channel)
Instant Directory Server Portal Server (for instant
Messaging messaging channel)
Access Manager (for
single sign-on)
Calendar Directory Server Portal Server (for calendar
Server channel)
Messaging Server (for
e-mail notification
service)
CO
ES PO
ACES
L L E GE
Page 211
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Messaging Server
Instant Messaging
Access Manager
Dimension 2: Logical Tiers
For the most part, logical tier architectures represent the distributed
enterprise application layer. The Java ES system service components
discussed in Infrastructure Service Levels provide support to application
components in all of the logical tiers shown in Dimension 2. However, logical
tier concepts also apply to system service components that provide
application-level services, such as Messaging Server and Calendar Server.
This section provides brief descriptions of the four logical tiers shown in
Dimension 2. The descriptions refer to application components implemented
using the Java 2 Platform, Enterprise Edition (J2EE platform) component
model. However, other distributed component models, such as CORBA, also
support this architecture.
CO
ES PO
ACES
L L E GE
Page 212
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Client tier. The client tier consists of application logic accessed
directly by an end user through a user interface. The logic in the client
tier could include browser-based clients, Java components running on
a desktop computer, or Java 2 Platform, Micro Edition (J2ME
platform) mobile clients running on a handheld device.
Presentation tier. The presentation tier consists of application logic
that prepares data for delivery to the client tier and processes requests
from the client tier for delivery to back-end business logic. The logic in
the presentation tier typically consists of J2EE components such as
Java Servlet components or JSP components that prepare data for
delivery in HTML or XML format or that receive requests for processing.
This tier might also include a portal service that can provide
personalized, secure, and customized access to business services in the
business service tier.
Business service tier. The business service tier consists of logic that
performs the main functions of the application: processing data,
implementing business rules, coordinating multiple users, and
managing external resources such as databases or legacy systems.
Typically, this tier consists of tightly coupled components that conform
to the J2EE distributed component model, such as Java objects, EJB
components, or message-driven beans. Individual J2EE components
can be assembled to deliver complex business services, such as an
inventory service or tax calculation service. Individual components and
service assemblies can be encapsulated as loosely coupled web services
within a service oriented architecture model and that conform to Simple
Object Access Protocol (SOAP) interface standards. Business services
can also be built as standalone servers, such as an enterprise calendar
server or messaging server.
Data tier. The data tier consists of services that provide persistent
data used by business logic. The data can be application data stored in
a database management system or it can be resource and directory
information stored in a Lightweight Directory Access Protocol (LDAP)
data store (resource tier). The data services can also include data feeds
from external sources or data accessible from legacy computing systems
(integration tier).
CO
ES PO
ACES
L L E GE
Page 213
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
in other tiers. You can change your implementation of business logic
without having to change or upgrade logic in the presentation tier or
client tier. This independence means, for example, that you can
introduce new types of client components without having to modify
business service components.
Physical independence. The four tiers also represent physical
independence: You can deploy the logic in different tiers on different
hardware platforms (that is, different processor configurations, chip
sets, and operating systems). This independence allows you to run
distributed application components on the computers best suited to
their individual computing requirements and best suited to maximizing
network bandwidth.
CO
ES PO
ACES
L L E GE
Page 214
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
The logical separation of Messaging Server functions into different tiers allows
the logically distinct configurations of Messaging Server to be deployed on
different computers in a physical environment. The physical separation allows
for flexibility in meeting quality of service requirement. For example it provides
for different availability solutions for the different instances, and different
security implementations for different Messaging Server functions.
Service Qualities
CO
ES PO
ACES
L L E GE
Page 215
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
quality-of-service requirements. These service qualities are summarized in the
following table.
CO
ES PO
ACES
L L E GE
Page 216
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Java Enterprise System Service Quality Components
The following table shows the most important Java ES service quality
components from an architectural perspective with the system qualities they
impact most.
Sun Cluster software provides high availability and scalability services for
Java ES components and for applications supported by Java ES
infrastructure.
CO
ES PO
ACES
L L E GE
Page 217
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
A cluster is a set of loosely coupled computers that collectively provides a
single client view of services, system resources, and data. Internally, the
cluster uses redundant computers, interconnects, data storage, and network
interfaces to provide high availability to cluster-based services and data.
Sun Cluster software continuously monitors the health of member nodes and
other cluster resources. In case of failure, Sun Cluster software intervenes to
initiate failover of the resources it monitors, thereby using the internal
redundancy to provide near-continuous access to these resources.
A two-node cluster to support data store services for Messaging Server and
Calendar Server is shown in the following figure.
CO
ES PO
ACES
L L E GE
Page 218
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Because of the control afforded by Sun Cluster software, it can also provide
for scalable services. By leveraging a clusters global file system and the ability
of multiple nodes in a cluster to run infrastructure or application services,
increased demand on these services can be balanced among multiple
concurrent instances of the services. When properly configured, Sun Cluster
software can therefore provide for both high availability and scalability in a
distributed enterprise application.
CO
ES PO
ACES
L L E GE
Page 219
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Self-Check 1.8-1
Answer each item and write it on your paper.
1. Tier that consists of application logic accessed directly by an end user
through a user interface. The logic in this tier could include browser-
based clients, Java components running on a desktop computer, or
Java 2 Platform, Micro Edition (J2ME platform) mobile clients
running on a handheld.
2. Enumerate 6 service qualities impacting solution architecture.
3. Tier consists of logic that performs the main functions of the
application: processing data, implementing business rules,
coordinating multiple users, and managing external resources such
as databases or legacy systems
CO
ES PO
ACES
L L E GE
Page 220
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology
Answer Key 1.6-1
1. Client tier
2. 6 service qualities impacting solution architecture are:
a. Performance
b. Availability
c. Security
d. Scalability
e. Latent Capacity
f. Serviceability
3. Business tier
CO
ES PO
ACES
L L E GE
Page 221
Perform object- POLYTECHNIC
AC
Developed by:
PA
NAB
O, DAV
AO oriented analysis Malik S. COLLEGE
and design in Java Macasalong, MIT Revision # 01
Technology