Você está na página 1de 227

COMPETENCY-BASED LEARNING MATERIALS

PERFORM OBJECT-ORIENTED ANALYSIS AND DESIGN IN


JAVA TECHNOLOGY

Aces Polytechnic College


TADECO Rd., San Francisco, Panabo City

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

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

No. Unit of Competency Module Title Code

Performing object-
Perform object-oriented
oriented analysis and
1. analysis and design in ICT313359
design in Java
Java technology
technology

Create and fine-tune Java Create and fine-tune Java


technology applications technology applications
2. ICT313360
using object-oriented using object-oriented
programming concept programming concept

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

HOW TO USE THIS COMPETENCY-BASED LEARNING MATERIAL ............................... III


LIST OF COMPETENCIES ........................................................................................... IV
MODULE CONTENT ..................................................................................................... 2
LEARNING OUTCOME NO. 1 APPLY BASICS OF JAVA LANGUAGE ............................... 4
INFORMATION SHEET 1.1-1 INTRODUCTION TO JAVA AND BASICS OF A JAVA
PROGRAM ................................................................................................................... 5
SELF-CHECK 1.1-1 ....................................................................................................................................... 28
ANSWER KEY 1.1-1 ....................................................................................................................................... 29
INFORMATION SHEET 1.1-2 SELECTION CONTROL STRUCTURE ............................ 30
TASK SHEET 1.1-2 EMPLOYEE WEEKLY SALARY....................................................................................... 40
PERFORMANCE CRITERIA CHECKLIST 1.1-2 .............................................................................................. 41
INFORMATION SHEET 1.1-3 REPETITION CONTROL STRUCTURE ........................... 42
TASK SHEET 1.1-3 RIGHT TRIANGLE........................................................................................................... 52
PERFORMANCE CRITERIA CHECKLIST 1.1-3 .............................................................................................. 53
INFORMATION SHEET 1.1-4 ARRAYS ...................................................................... 54
TASK SHEET 1.1-4 ADDRESS BOOK ........................................................................................................... 68
PERFORMANCE CRITERIA CHECKLIST 1.1-4 .............................................................................................. 69
LEARNING OUTCOME NO. 2 WORKS WITH METHODS AND ENCAPSULATION ........... 70
INFORMATION SHEET 1.2-1 METHODS IN JAVA ..................................................... 71
SELF-CHECK 1.2-1 ....................................................................................................................................... 79
ANSWER KEY 1.2-1 ....................................................................................................................................... 80
INFORMATION SHEET 1.2-2 ENCAPSULATION......................................................... 81
SELF-CHECK 1.2-2 ....................................................................................................................................... 91
ANSWER KEY 1.2-2 ....................................................................................................................................... 92
LEARNING OUTCOME NO. 3 WORK WITH INHERITANCE AND HANDLING EXCEPTIONS
................................................................................................................................. 93
INFORMATION SHEET 1.3-1 INHERITANCE ............................................................. 94
SELF-CHECK 1.3-1 ....................................................................................................................................... 97
ANSWER KEY 1.3-1 ....................................................................................................................................... 98
INFORMATION SHEET 1.3-2 POLYMORPHISM ......................................................... 99
SELF-CHECK 1.3-2 ..................................................................................................................................... 102
ANSWER KEY 1.3-2 ..................................................................................................................................... 103
INFORMATION SHEET 1.3-3 ABSTRACT CLASSES, JAVA INTERFACES AND
EXCEPTION HANDLING ........................................................................................... 104
SELF-CHECK 1.3-3 ..................................................................................................................................... 110
ANSWER KEY 1.3-3 ..................................................................................................................................... 111
LEARNING OUTCOME NO. 4 EXAMINE OBJECT-ORIENTED CONCEPTS AND
TERMINOLOGY ....................................................................................................... 112

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

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

Qualification Title : PROGRAMMING (JAVA) NC III

Unit of Competency : Perform object-oriented analysis and design in


Java technology
Module Title : Performing object-oriented analysis and design in
Java technology

Technical Education & Skills Development Authority


ACES POLYTECHNIC COLLEGE
Panabo City

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

UNIT OF COMPETENCY : Perform object-oriented analysis


and design IN JAVA TECHNOLOGY

MODULE TITLE : Performing object-oriented analysis


and design IN JAVA TECHNOLOGY
MODULE DESCRIPTOR : This unit covers the knowledge,
skills and attitude needed to use
various Java programming language
constructs to create several Java
technology applications.
Specifically, it consist of
competencies in applying basics of
Java language, working with
methods and encapsulation, and
working with inheritance and
handling exceptions.

It also focuses on effectively using


object-oriented technologies and the
use of software modeling, as applied
to a software development process.
Students will learn to present one
practical & complete object-oriented
analysis and design (OOAD)
roadmap, and will get hands-on
experience, from requirements
gathering to system design.

NOMINAL DURATION : 54 hours


LEARNING OUTCOMES :
At the end of this module you must be able to:
1. Apply basics of Java language
2. Work with methods and encapsulation,
3. Work with inheritance and handling exceptions,
4. Examine object-oriented concepts and terminology,
5. Explain modeling and software development process,
6. Create use case diagrams and use case scenarios,
7. Transition analysis to design using interaction diagrams, and
8. Introduce architectural concepts and architecture tiers diagrams

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

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

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)

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

Application software are those programs that are used to perform


specific tasks and getting peoples work done like, but not limited to:
(1) word-processing software;
(2) spreadsheet;
(3) presentation software;
(4) web browsers.

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.

Both application and system software are created using programming


languages. A programming language is a standardized technique in writing
instructions to computer. There are many programming languages today and
one of these is Java.
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 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

Java was created in 1991 by a development team from Sun


Microsystems headed by James Gosling. However, its first name was not Java
but Oak. Back then, there was already a programming language named Oak
and as soon as they discovered it, the team looked for a new name for many
hours, went out for coffee and the name Java was born.
The original motivation for Java was the need for platform independent
language that could be embedded in various consumer electronic products
like toasters and refrigerators. One of the first projects developed using Java
was a personal hand-held remote control named Star 7. At about the same
time, the World Wide Web and the Internet were gaining popularity. Gosling
et. al. realized that Java could be used for Internet programming.

YOUR FIRST PROGRAM

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.

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

Compiling a program. At first, it might seem that Java is designed to be best


understood by the computer. To the contrary, the language is designed to be
best understood by the programmer (thats you). The computers language is
far more primitive than Java. A compiler is an application that translates a
program from the Java language to a language more suitable for executing on
the computer. The compiler takes a file with a .java extension as input (your
program) and produces a file with the same name but with a .class extension
(the computer-language version). To use your Java compiler, type in a
terminal window the javac command, followed by the file name of the program
you want to compile.

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.

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

PROGRAM 1 is an example of a complete Java program. Its name is


HelloWorld, which means that its code resides in a file named HelloWorld.java
(by convention in Java). The programs sole action is to print a message back
to the terminal window. For continuity, we will use some standard Java terms
to describe the program, but we will not define them until later in the module:
PROGRAM 1 consists of a single class named HelloWorld that has a single
method named main(). This method uses two other methods named
System.out.print() and System.out.println() to do the job. (When referring to a
method in the text, we use () after the name to distinguish it from other kinds
of names.) For the time being, you can think of class as meaning program.
The first line of a method specifies its name and other information; the rest is
a sequence of statements enclosed in braces and each followed by a
semicolon. For the time being, you can think of programming as meaning
specifying a class name and a sequence of statements for its main() method.
In the next two sections, you will learn many different kinds of statements
that you can use to make programs. For the moment, we will just use
statements for printing to the terminal like the ones in HelloWorld.
When you type java followed by a class name in your terminal
application, the
system calls the main() method that you defined in that class, and executes
its statements in order, one by one. Thus, typing java HelloWorld causes the
system to call on the main() method in PROGRAM 1 and execute its two

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

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

BUILT-IN TYPES OF DATA


When programming in java, you must always be aware of the type of data that
your program is processing. The programs in SECTION 1.1 process strings of
characters, many of the programs in this section process numbers, and we
consider numerous other types later in the book. Understanding the
distinctions among them is so important that we formally define the idea: a
data type is a set of values and a set of operations defined on those values.
You are familiar with various types of numbers, such as integers and real
numbers, and with operations defined on them, such as addition and
multiplication. In mathematics, we are accustomed to thinking of sets of
numbers as being infinite; in computer programs we have to work with a finite
number of possibilities. Each operation that we perform is well-defined only
for the finite set of values in an associated data type. There are eight primitive
types of data in Java, mostly for different kinds of numbers. Of the eight
primitive types, we most often use these: int for integers; double for real
numbers; and boolean for true-false values. There are other types of data
available in Java libraries: for example, the programs in the previous section
use the type String for strings of characters. Java treats the String type
differently from other types because its usage for input and output is
essential. Accordingly, it shares some characteristics of the primitive types:
for example, some of its operations are built in to the Java language. For
clarity, we refer to primitive types and String collectively as built-in types.
For the time being, we concentrate on programs that are based on computing
with built-in types. After defining basic terms, we consider several sample
programs and code fragments that illustrate the use of different types of data.
These code fragments do not do much real computing, but you will soon see
similar code in longer programs. Understanding data types (values and
operations on them) is an essential step in beginning to program. It sets the
stage for us to begin working with more intricate programs in the next section.
Every program that you write will use code like the tiny fragments shown in
this section.

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

Precedence. Such expressions are shorthand for specifying a sequence of


computations: in what order should they be performed? Java has natural and
well-defined precedence rules that fully specify this order. For arithmetic
operations, multiplication and division are performed before addition and
subtraction, so that a-b*c and a-(b*c) represent the same sequence of
operations. When arithmetic operators have the same precedence, the order
is determined by left-associativity, so that a-b-c and (a-b)-c represent the
same sequence of operations. You can use parentheses to override the rules,
so you should not need to worry about the details of precedence for most of
the programs that you write.
Converting strings to primitive values for command-line arguments.
Java provides the library methods that we need to convert the strings that we
type as command-line arguments into numeric values for primitive types. We
use the Java library methods Integer.parseInt() and Double.parseDouble() for
this purpose. For example, typing Integer.parseInt("123") in program text
yields the literal value 123 (typing 123 has the same effect) and the code
Integer. parseInt(args[0]) produces the same result as the literal value typed
as a string on the command line.
Converting primitive type values to strings for output. As mentioned at
the beginning of this section, the Java built-in String type obeys special rules.
One of these special rules is that you can easily convert any type of data to a
String: whenever we use the + operator with a String as one of its operands,
Java automatically converts the other to a String, producing as a result the
String formed from the characters of the first operand followed by the
characters of the second operand.
For example, the result of these two code fragments
String a = "1234"; String a = "1234";
String b = "99"; int b = 99;
String c = a + b; String c = a + b;

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

System.out.println(a + " + " + b + " = " + c);


If a, b, and c are int variables with the values 1234, 99, and 1333, respectively,
then this statement prints out the string 1234 + 99 = 1333. WITH THESE
MECHANISMS, OUR VIEW OF each Java program as a black box that takes
string arguments and produces string results is still valid, but we can now
interpret those strings as numbers and use them as the basis for meaningful
computation. Next, we consider these details for the basic built-in types that
you will use most often (strings, integers, floating-point numbers, and true
false values), along with sample code illustrating their use. To understand
how to use a data type, you need to know not just its defined set of values,
but also which operations you can perform, the language mechanism for
invoking the operations, and the conventions for specifying literal values.

Characters and Strings


A char is an alphanumeric character or symbol, like the ones that you
type. There are 216 different possible character values, but we usually restrict
attention to the ones that represent letters,
numbers, symbols, and whitespace characters
such as tab and newline. Literals for char are
characters enclosed in single quotes; for
example, 'a' represents the letter a. For tab,
newline, backslash, single quote and double
quote, we use the special escape sequences '\t',
'\n', '\\', '\'', and '\"', respectively. The
characters are encoded as 16-bit integers using
an encoding scheme known as Unicode, and there are escape sequences for
specifying special characters not found on your keyboard. We usually do not
perform any operations directly on characters other than assigning values to
variables.
A String is a sequence of characters. A literal String is a sequence of
characters within double quotes, such as "Hello, World". The String data type
is not a primitive type, but Java sometimes treats it like one. For example, the
concatenation operator (+) that we just considered is built in to the language
as a binary operator in the same way as familiar operations on numbers.
The concatenation operation (along with the ability to declare String
variables and to use them in expressions and assignment statements) is
sufficiently powerful to allow us to attack some nontrivial computing tasks.
As an example, Ruler (PROGRAM 2) computes a table of values of the ruler
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 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.

Program 2. String concatenation example


Integers
An int is an integer (natural number) between 2147483648 (!2 31) and
2147483647 (2 31!1). These bounds derive from the fact that integers are
represented in binary with 32 binary digits: there are 232 possible values.
(The term binary digit is omnipresent in
computer science, and we nearly always
use the abbreviation bit : a bit is either 0
or 1.) The range of possible int values is
asymmetric because zero is included with
the positive values. See the booksite for
more details about number
representation, but in the present context
it suffices to know that an int is one of the
finite set of values in the range just given.
Sequences of the characters 0 through 9,
possibly with a plus or minus sign at the
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 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

Program 3. Integer Multiplication and Division


general, we have to take care that such a result is not misinterpreted by our
code. For the moment, we will be computing with small numbers, so you do
not have to worry about these boundary conditions.
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 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

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

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

Program 4. Casting to get a random integer

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

Java provides a rich set of operators to manipulate variables. We can divide


all the Java operators into the following groups:

Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators

The Arithmetic Operators:

Arithmetic operators are used in mathematical expressions in the same way


that they are used in algebra. The following table lists the arithmetic
operators:

Assume integer variable A holds 10 and variable B holds 20, then:

Show Examples

Operator Description Example


A + B will give
+ Addition - Adds values on either side of the operator
30
Subtraction - Subtracts right hand operand from A - B will give -
-
left hand operand 10
Multiplication - Multiplies values on either side of A * B will give
*
the operator 200
Division - Divides left hand operand by right hand B / A will give
/
operand 2
Modulus - Divides left hand operand by right hand B % A will give
%
operand and returns remainder 0
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19

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

There are following relational operators supported by Java language

Assume variable A holds 10 and variable B holds 20, then:

Show Examples

Operator Description Example


Checks if the values of two operands are equal or (A == B) is not
==
not, if yes then condition becomes true. true.
Checks if the values of two operands are equal or
!= not, if values are not equal then condition becomes (A != B) is true.
true.
Checks if the value of left operand is greater than
(A > B) is not
> the value of right operand, if yes then condition
true.
becomes true.
Checks if the value of left operand is less than the
< value of right operand, if yes then condition (A < B) is true.
becomes true.
Checks if the value of left operand is greater than
(A >= B) is not
>= or equal to the value of right operand, if yes then
true.
condition becomes true.
Checks if the value of left operand is less than or
(A <= B) is
<= equal to the value of right operand, if yes then
true.
condition becomes true.
The Bitwise Operators:

Java defines several bitwise operators, which can be applied to the integer
types, long, int, short, char, and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a


= 60; and b = 13; now in binary format they will be as follows:

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100


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 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^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators:

Assume integer variable A holds 60 and variable B holds 13 then:

Show Examples

Operator Description Example


(A & B) will
Binary AND Operator copies a bit to the result if it
& give 12 which
exists in both operands.
is 0000 1100
(A | B) will give
Binary OR Operator copies a bit if it exists in either
| 61 which is
operand.
0011 1101
(A ^ B) will give
Binary XOR Operator copies the bit if it is set in one
^ 49 which is
operand but not both.
0011 0001
(~A ) will give -
61 which is
1100 0011 in
Binary Ones Complement Operator is unary and 2's
~
has the effect of 'flipping' bits. complement
form due to a
signed binary
number.
Binary Left Shift Operator. The left operands value A << 2 will give
<< is moved left by the number of bits specified by the 240 which is
right operand. 1111 0000
Binary Right Shift Operator. The left operands A >> 2 will give
>> value is moved right by the number of bits specified 15 which is
by the right operand. 1111
Shift right zero fill operator. The left operands value
A >>>2 will
is moved right by the number of bits specified by
>>> give 15 which
the right operand and shifted values are filled up
is 0000 1111
with zeros.

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

The following table lists the logical operators:

Assume Boolean variables A holds true and variable B holds false, then:

Show Examples

Operator Description Example


Called Logical AND operator. If both the operands (A && B) is
&&
are non-zero, then the condition becomes true. false.
Called Logical OR Operator. If any of the two
(A || B) is
|| operands are non-zero, then the condition becomes
true.
true.
Called Logical NOT Operator. Use to reverses the
!(A && B) is
! logical state of its operand. If a condition is true
true.
then Logical NOT operator will make false.
The Assignment Operators:

There are following assignment operators supported by Java language:

Show Examples

Operator Description Example


C = A + B will
Simple assignment operator, Assigns values from
= assign value of
right side operands to left side operand
A + B into C
Add AND assignment operator, It adds right C += A is
+= operand to the left operand and assign the result to equivalent to C
left operand =C+A
Subtract AND assignment operator, It subtracts C -= A is
-= right operand from the left operand and assign the equivalent to C
result to left operand =C-A
Multiply AND assignment operator, It multiplies C *= A is
*= right operand with the left operand and assign the equivalent to C
result to left operand =C*A
Divide AND assignment operator, It divides left C /= A is
/= operand with the right operand and assign the equivalent to C
result to left operand =C/A

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

There are few other operators supported by Java Language.

Conditional Operator ( ? : ):

Conditional operator is also known as the ternary operator. This operator


consists of three operands and is used to evaluate Boolean expressions. The
goal of the operator is to decide which value should be assigned to the
variable. The operator is written as:

variable x = (expression) ? value if true : value if false

Following is the example:

public class Test {

public static void main(String args[]){


int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}
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 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:

( Object reference variable ) instanceof (class/interface type)

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:

public class Test {

public static void main(String args[]){


String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
System.out.println( result );
}
}

This would produce the following result:

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 {}

public class Car extends Vehicle {


public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result );
}
}

This would produce the following result:


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

Precedence of Java Operators

Operator precedence determines the grouping of terms in an expression. This


affects how an expression is evaluated. Certain operators have higher
precedence than others; for example, the multiplication operator has higher
precedence than the addition operator:

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator *


has higher precedence than +, so it first gets multiplied with 3*2 and then
adds into 7.

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.

Category Operator Associativity


Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

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

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

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

In the programs that we have examined to this point, each of the


statements in the program is executed once, in the order given. Most programs
are more complicated because the sequence of statements and the number of
times each is executed can vary. We use the term control flow to refer to
statement sequencing in a program. In this section, we introduce statements
that allow us to change the control flow, using logic about the values of
program variables.
This feature is an essential component of programming. Specifically, we
consider Java statements that implement conditionals, where some other
statements may or may not be executed depending on certain conditions, and
loops, where some other statements may be executed multiple times, again
depending on certain conditions. As you will see in numerous examples in
this section, conditionals and loops truly harness the power of the computer
and will equip you to write programs to accomplish a broad variety of tasks
that you could not contemplate attempting without a computer.

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.

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

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

Another example is a code snippet below:


int grade = 68;
if( grade > 60 )
System.out.println("Congratulations!");

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

int grade = 68;


if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println("You passed!");
}
else{
System.out.println("Sorry you failed");
}

In the early days of computing, when programmers used low-level


languages and difficult-to-understand flows of control, flowcharts were an
essential part of programming. With modern languages, we use flowcharts
just to understand basic building blocks like the if statement.
The accompanying table contains some examples of the use of if and
ifelse statements. These examples are typical of simple calculations you might
need in programs that you write. Conditional statements are an essential part
of programming. Since the semantics (meaning) of statements like these is
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 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!");
}

Program 5. Flipping a fair coin


IF-ELSE-IF STATEMENTS
The statement in the else-clause of an if-else block can be another if-
else structures. This cascading of structures allows us to make more complex
selections. The if-else if statement has the form,
if( boolean_expression1 )
statement1;
else if( boolean_expression2 )
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 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");
}

PROGRAM 6 is an example of an if-else-if program:

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

COMMON ERRORS WHEN USING THE IF-ELSE STATEMENTS


1. The condition inside the if-statement does not evaluate to a boolean
value. For example,
//WRONG
int number = 0;
if( number ){
//some statements here
}
The variable number does not hold a Boolean value.
2. Using = instead of == for comparison. For example,
//WRONG
int number = 0;
if( number = 0 ){
//some statements here
}
This should be written as,
//CORRECT
int number = 0;
if( number == 0 ){
//some statements here
}
3. Writing elseif instead of else if.

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

PROGRAM 7 is an example of a program that uses switch statement:

Program 7. Grade remarks (using switch)

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:

Here is the syntax of this method:


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

Here is the detail of parameters:

anObject -- the object to compare this String against.

Return Value :

This method returns true if the String are equal; false otherwise.

Example:
public class Test {

public static void main(String args[]) {


String Str1 = new String("This is really not immutable!!");
String Str2 = Str1;
String Str3 = new String("This is really not immutable!!");
boolean retVal;

if( Str1.equals( Str2 )){


retval = true
System.out.println("Returned Value = " + retVal );
}
else{
retval = false;
System.out.println("Returned Value = " + retVal );
}
}
}

This produces the following result:

Returned Value = true


Returned Value = true

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

5. Evaluate your own output using the Performance Criteria Checklist


1.1-2.
6. Present your work to your trainer

Assessment Method:

Observation

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

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

Repetition control structures are Java statements that allows us to execute


specific blocks of code a number of times. There are three types of repetition
control structures, the while, do-while and for loops.
WHILE LOOPS
Many computations are inherently repetitive. The basic Java construct for
handling such computations has the following format:
while (<boolean expression>) { <statements> }
The while statement has the same form as the if statement (the only
difference being the use of the keyword while instead of if), but the meaning
is quite different. It is an instruction to the computer to behave as follows: if
the expression is false, do nothing; if the expression is true, execute the
sequence of statements (just as with if) but then check the expression again,
execute the sequence of statements again if the expression is true, and
continue as long as the expression is true. We often refer to the statement
block in a loop as the body of the loop. As with the if statement, the braces
are optional if a while loop body has just one statement.
The while statement is equivalent to a sequence of identical if
statements:
if (<boolean expression>) { <statements> }
if (<boolean expression>) { <statements> }
if (<boolean expression>) { <statements> }
...
At some point, the code in one of the
statements must change something (such as the
value of some variable in the boolean expression)
to make the boolean expression false, and then
the sequence is broken. A common programming
paradigm involves maintaining an integer value
that keeps track of the number of times a loop
iterates. We start at some initial value, and then
increment the value by 1 each time through the
loop, testing whether it exceeds a predetermined
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 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

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

Program 9. Computing powers of two

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.

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

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

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

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

In this information sheet, we consider a fundamental programming


construct known as the array. The primary purpose of an array is to facilitate
storing and manipulating large quantities of data. Arrays play an essential
role in many data processing tasks. They also correspond to vectors and
matrices, which are widely used in science and in scientific programming. We
will consider basic properties of array processing in Java, with many examples
illustrating why they are useful.
An array stores a sequence of values that are all of the same type.
Processing such a set of values is very common. We might have exam scores,
stock prices, nucleotides in a DNA strand, or characters in a book. Each of
these examples involve a large number of values that are all of the same type.
We want not only to store values but also directly access each individual
value. The method that we use to refer to individual values in an array is
numbering and then indexing them. If we have N values, we think of them as
being numbered from 0 to N!1. Then, we can unambiguously specify one of
them by referring to the ith value for any value of i from 0 to N!1. To refer to
the ith value in an array a, we use the notation a[i], pronounced a sub i. This
Java construct is known as a one-dimensional array.
The one-dimensional array is our first example in this module. We also
consider in this section a more complicated data structure known as a two-
dimensional array.
Typically, when we have a large amount of data to process, we first put
all of the data into one or more arrays. Then we use array indexing to refer to
individual values and to process the data. In this section, we expose the basic
properties of arrays by considering examples where our programs first
populate arrays with computed values from experimental studies and then
process them.

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

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

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

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

Memory representation. Arrays are fundamental data structures in that


they have a direct correspondence with memory systems
on virtually all computers. The elements of an array are
stored consecutively in memory, so that it is easy to
quickly access any array value. Indeed, we can view
memory itself as a giant array. On modern computers,
memory is implemented in hardware as a sequence of
indexed memory locations that each can be quickly
accessed with an appropriate index. When referring to
computer memory, we normally refer to a locations index
as its address. It is convenient to think of the name of the
arraysay, aas storing the memory address of the first
element of the array a[0]. For the purposes of illustration,
suppose that the computers memory is organized as
1,000 values, with addresses from 000 to 999. (This
simplified model ignores the fact that array elements can
occupy differing amounts of memory depending on their
type, but you can ignore such details for the moment.)
Now, suppose that an array of eight elements is stored in
memory locations 523 through 530. In such a situation,
Java would store the memory address (index) of the first
array value somewhere else in memory, along with the
array length. We refer to the address as a pointer and
think of it as pointing to the referenced memory location.
When we specify a[i], the compiler generates code that
accesses the desired value by adding the index i to the
memory address of the array a[]. For example, the Java
code a[4] would generate machine code that finds the
value at memory location 523 + 4 = 527. Accessing element i of an array is an
efficient operation because it simply requires adding two integers and then
referencing memoryjust two elementary operations. Extending the model to
handle different-sized array elements just involves multiplying the index by
the element size before adding to the array address.
Memory allocation. When you use new to create an array, Java reserves
space in memory for it. This process is called memory allocation. 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 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.

Bounds checking. As already indicated, you must be careful when


programming with arrays. It is your responsibility to use legal indices when
accessing an array element. If you have created an array of size N and use an
index whose value is less than 0 or greater than N-1, your program will
terminate with an ArrayIndexOutOfBounds run-time exception. (In many
programming languages, such buffer overflow conditions are not checked by
the system. Such unchecked errors can and do lead to debugging nightmares,
but it is also not uncommon for such an error to go unnoticed and remain in
a finished program. You might be surprised to know that such a mistake can
be exploited by a hacker to take control of a system, even your personal
omputer, to spread viruses, steal personal information, or wreak other
alicious havoc.) The error messages provided by Java may seem annoying to
you at first, but they are small price to pay to have a more secure program.
Setting array values at compile time. When we have a small number of
literal values that we want to keep in array, we can declare and initialize it by
listing the values between curly braces, separated by commas. For example,
we might use the following code in a program that processes playing cards.
String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] rank =
{
"2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Ace"
};
After creating the two arrays, we can use them to print out a random card
name,such as Queen of Clubs, as follows:
int i = (int) (Math.random() * rank.length);
int j = (int) (Math.random() * suit.length);
System.out.println(rank[i] + " of " + suit[j]);
This code uses the idiom introduced in previous information sheet to generate
random indices and then uses the indices to pick strings out of the arrays.
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 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

Exchange. Frequently, we wish to exchange two values in an array.


Continuing our example with playing cards, the following code exchanges the
cards at position I and j using the same idiom that we traced as our first
example of the use of assignment statements:
String t = deck[i];
deck[i] = deck[j];
deck[j] = t;
When we use this code, we are assured that we are perhaps changing the
order of the values in the array but not the set of values in the array. When i
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 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");

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

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

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

Spreadsheets. One familiar use of arrays is a spreadsheet for maintaining a


table of numbers. For example, a teacher with M students and N test grades
for each student might maintain an (M +1)-by-(N +1) array, reserving the last
column for each students average grade and the last row for the average test
grades. Even though we typically do such computations within specialized
applications, it is worthwhile to study the underlying code as an introduction
to array processing. To compute the average grade for each student (average
values for each row), sum the entries for each row and divide by N. The row-
by-row order in which this code processes the matrix

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 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];
}

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

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

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

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

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)

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

public static : modifier (which will be discussed later in this information


sheet)
int: return type
funcName: function name
a, b: formal parameters
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 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

Methods are also known as Procedures or Functions:


Procedures: They don't return any value.
Functions: They return value.
Method definition consists of a method header and a method body. The same
is shown below:
modifier returnType nameOfMethod (Parameter List) {
// method body
}

The syntax shown above includes:


modifier: It defines the access type of the method and it is optional to use.
returnType: Method may return a value.
nameOfMethod: This is the method name. The method signature consists
of the method name and the parameter list.
Parameter List: The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero
parameters.
method body: The method body defines what the method does with
statements.
Example:
Here is the source code of the above defined method called max(). This method
takes two parameters num1 and num2 and returns the maximum between
the two:
/** the snippet returns the minimum between two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

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;

The void Keyword


The void keyword allows us to create methods which do not return a
value. Here, in the following example we're considering a void method
methodRankPoints. This method is a void method which does not return any
value. Call to a void method must be a statement i.e.
methodRankPoints(255.7);. It is a Java statement which ends with a
semicolon as shown below.
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 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");
}
}
}

This would produce the following result:


Rank:A1
PASSING VARIABLES IN METHODS
In our examples, we already tried passing variables to methods. However, we
haven't differentiated between the different types of variable passing in Java.
There are two types of passing data to methods, the first one is pass-by-value
and then, pass-byreference.

Pass-by-value

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

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

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

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

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

Let us look at an example that depicts encapsulation:

/* File name : EncapTest.java */


public class EncapTest{

private String name;


private String idNum;
private int age;

public int getAge(){


return age;
}

public String getName(){


return name;
}

public String getIdNum(){


return idNum;
}

public void setAge( int newAge){


age = newAge;
}

public void setName(String newName){


name = newName;
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 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
}

public void setIdNum( String newId){


idNum = newId;
}
}

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

/* File name : RunEncap.java */


public class RunEncap{

public static void main(String args[]){


EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName()+


" Age : "+ encap.getAge());
}
}

This would produce the following result:

Name : James Age : 20

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,

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

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

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

public class StudentRecordExample


{
public static void main( String[] args ){
//create three objects for Student record
StudentRecord annaRecord = new StudentRecord();
StudentRecord beahRecord = new StudentRecord();
StudentRecord crisRecord = new StudentRecord();
//set the name of the students
annaRecord.setName("Anna");
beahRecord.setName("Beah");
crisRecord.setName("Cris");
//print anna's name
System.out.println( annaRecord.getName() );
//print number of students

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

So for example, we can now rewrite our code to,


public void setAge( int age ){
this.age = age;
}

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

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

Always remember that overloaded methods have the following properties,


the same name
different parameters
return types can be different or 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 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?

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

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

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)

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

Defining Superclasses and Subclasses

To derive a class, we use the extends keyword. In order to illustrate this,


let's create a sample parent class. Suppose we have a parent class called
Person.
public class Person
{
protected String name;
protected String address;
/**
* Default constructor
*/
public Person(){
System.out.println(Inside Person:Constructor);
name = "";
address = "";
}
/**
* Constructor with 2 parameters
*/
public Person( String name, String address ){
this.name = name;
this.address = address;
}
/**
* Accessor methods
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 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,

public class Student extends Person


{
public Student(){
System.out.println(Inside Student:Constructor);
//some code here
}
// some code here
}
When a Student object is instantiated, the default constructor of its
superclass is invoked implicitly to do the necessary initializations. After that,
the statements inside the subclass are executed. To illustrate this, consider
the following code,
public static void main( String[] args ){
Student anna = new Student();
}
In the code, we create an object of class Student. The output of the
program is,

Inside Person:Constructor
Inside Student:Constructor

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

A subclass can also explicitly call a constructor of its immediate


superclass. This is done by using the super constructor call. A super
constructor call in the constructor of a subclass will result in the execution of
relevant constructor from the superclass, based on the arguments passed.
For example, given our previous example classes Person and Student,
we show an example of a super constructor call. Given the following code for
Student,

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

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

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

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

Polymorphism is the ability of an object to take on many forms. The


most common use of polymorphism in OOP occurs when a parent class
reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to
be polymorphic. In Java, all Java objects are polymorphic since any object will
pass the IS-A test for their own type and for the class Object.
It is important to know that the only possible way to access an object is
through a reference variable. A reference variable can be of only one type.
Once declared, the type of a reference variable cannot be changed.
The reference variable can be reassigned to other objects provided that
it is not declared final. The type of the reference variable would determine the
methods that it can invoke on the object.
A reference variable can refer to any object of its declared type or any
subtype of itsdeclared type. A reference variable can be declared as a class or
interface type.

Example:

Let us look at an example.

public interface Vegetarian{}


public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Now, the Deer class is considered to be polymorphic since this has


multiple
inheritance. Following are true for the above example:
A Deer IS-A Animal
A Deer IS-A Vegetarian
A Deer IS-A Deer
A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference,
the following declarations are legal:
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
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 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 ){
....
}

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

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

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

Now, let's create an example abstract class.

public abstract class LivingThing


{
public void breath(){
System.out.println("Living Thing breathing...");
}
public void eat(){
System.out.println("Living Thing eating...");
}
/**
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 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

An interface is a special kind of block containing method signatures


(and possibly constants) only. Interfaces define the signatures of a set of
methods without the body.
Interfaces define a standard and public way of specifying the behavior
of classes. They allow classes, regardless of their location in the class
ierarchy, to implement common behaviors. Note that interfaces exhibit
polymorphism as well, since program may call an interface method and the
proper version of that method will be executed depending on the type of object
passed to the interface method call.
We need to use interfaces if we want unrelated classes to implement
similar methods.
Thru interfaces, we can actually capture similarities among unrelated
classes without artificially forcing a class relationship.
Let's take as an example a class Line which contains methods that
computes the length of the line and compares a Line object to objects of the
same class. Now, suppose we have another class MyInteger which contains
methods that compares a MyInteger object to objects of the same class. As we
can see here, both of the classes have some similar methods which compares
them from other objects of the same type, but they are not related whatsoever.
In order to enforce a way to make sure that these two classes implement some
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 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

To create an interface, we write,

public interface [InterfaceName]


{
//some methods without the body
}
As an example, let's create an interface that defines relationships
between two objects
according to the natural order of the objects.
public interface Relation
{
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}
Now, to use the interface, we use the implements keyword. For
example,
/**
* This class defines a line segment
*/
public class Line implements Relation
{
private double x1;
private double x2;
private double y1;
private double y2;
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 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

Interface vs. Abstract Class

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.

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

What are Exceptions?

An exception is an event that interrupts the normal processing flow of


a program. This event is usually some error of some sort. This causes our
program to terminate abnormally.
Some examples of exceptions that you might have encountered in our
previous exercises are: ArrayIndexOutOfBounds exceptions, which occurs if
e try to access a non-existent array element, or maybe a
NumberFormatException, which occurs when we try to pass as a parameter
a non-number in the Integer.parseInt method.

Handling Exceptions

To handle exceptions in Java, we use a try-catch-finally block. What we


do in our programs is that we place the statements that can possibly generate
an exception inside this block.
The general form of a try-catch-finally block is,
try{
//write the statements that can generate an exception
//in this block
}
catch( <exceptionType1> <varName1> ){
//write the action your program will do if an exception
//of a certain type occurs
}
...
catch( <exceptionTypen> <varNamen> ){
//write the action your program will do if an
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 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.

Exception in thread "main"


java.lang.ArrayIndexOutOfBoundsException: 1
at ExceptionExample.main(ExceptionExample.java:5)

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

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

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

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)

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

Object-Oriented programming or OOP revolves around the concept of


objects as thebasic elements of your programs. When we compare this to the
hysical world, we can find many objects around us, such as cars, lion, people
and so on. These objects are characterized by their properties (or attributes)
and behaviors. For example, a car object has the properties, type of
transmission, manufacturer and color. Its behaviors are turning, braking and
accelerating. Similarly, we can define different properties and behavior of a
lion. Please refer to the table below for the examples.
With these descriptions, the objects in the physical world can easily be
modeled as software objects using the properties as data and the behaviors
as methods. These data and methods could even be used in programming
games or interactive software to simulate the real-world objects! An example
would be a car software object in a racing game or a lion software object in an
educational interactive software zoo for kids.

What Is an Object?

An object is a software bundle of related state and behavior. Software


objects are often used to model the real-world objects that you find in everyday
life. This lesson explains how state and behavior are represented within an
object, introduces the concept of data encapsulation, and explains the
benefits of designing your software in this manner.

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

Difference Between Classes and Objects


In the software world, an object is a software component whose structure is
similar to objects in the real world. Each object is composed of a set of data
(properties/attributes) which are variables describing the essential
haracteristics of the object, and it also consists of a set of methods
(behavior) that describes how an object behaves. Thus, an object is a
oftware bundle of variables and related methods. The variables and methods
in a Java object are formally known as instance variables and instance
methods to distinguish them from class variables and class methods, which
ill be discussed later.
The class is the fundamental structure in object-oriented programming.
It can be thought of as a template, a prototype or a blueprint of an object. It
consists of two types of members which are called fields (properties or
attributes) and methods. Fields specifiy the data types defined by the class,
while methods specify the operations. An object is an instance of the class. To
differentiate between classes and objects, let us discuss an example. What we
have here is a Car Class which can be used to define several Car Objects.
When instantiated, each object gets a fresh set of state variables.
However, the method implementations are shared among objects of the same
class. Classes provide the benefit of reusability. Software programmers can
use a class over and over again to create many objects.

Class Variables and Methods


In addition to the instance variables, it is also possible to define class
variables, which are variables that belong to the whole class. This means that
it has the same value for all the objects in the same class. They are also called
static member variables.

What Is a Package?

A package is a namespace for organizing classes and interfaces in a logical


manner. Placing your code into packages makes large software projects easier
to manage. This section explains why this is useful, and introduces you to the
Application Programming Interface (API) provided by the Java platform.

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

To create an object or an instance of a class, we use the new operator. For


example, if you want to create an instance of the class String, we write the
following code,

String str2 = new String(Hello world!);


or also equivalent to,

String str2 = "Hello";

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.

Another example, to create a Scanner object for user interaction you


will write the code,
Scanner kbd = new Scanner (System.in);

It is important to remember that Oracle has done all classes we need in


Java programming. All we have to do is import those classes from different
packages as we create them and create objects to have reference to those
classes.

Other OOP concepts are inheritance, polymorphism, methods, and


exceptions which are already discussed in the previous information sheets.

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

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

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

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)

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

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

Stage 1: Planning and Requirement Analysis

Requirement analysis is the most important and fundamental stage in


SDLC. It is performed by the senior members of the team with inputs from
the customer, the sales department, market surveys and domain experts in
the industry. This information is then used to plan the basic project approach
and to conduct product feasibility study in the economical, operational, and
technical areas.

Planning for the quality assurance requirements and identification of


the risks associated with the project is also done in the planning stage. The
outcome of the technical feasibility study is to define the various technical
approaches that can be followed to implement the project successfully with
minimum risks.

Stage 2: Defining Requirements

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.

A design approach clearly defines all the architectural modules of the


product along with its communication and data flow representation with the
external and third party modules (if any). The internal design of all the
modules of the proposed architecture should be clearly defined with the
minutest of the details in DDS.

Stage 4: Building or Developing 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.

Developers have to follow the coding guidelines defined by their


organization and programming tools like compilers, interpreters, debuggers
etc are used to generate the code. Different high level programming languages
such as C, C++, Pascal, Java, and PHP are used for coding. The programming
language is chosen with respect to the type of software being developed.

Stage 5: Testing the Product

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.

Stage 6: Deployment in the Market and Maintenance

Once the product is tested and ready to be deployed it is released


formally in the appropriate market. Sometime product deployment happens
in stages as per the organizations. business strategy. The product may first
be released in a limited segment and tested in the real business environment
(UAT- User acceptance testing).

Then based on the feedback, the product may be released as it is or


with suggested enhancements in the targeting market segment. After the
product is released in the market, its maintenance is done for the existing
customer base.

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

Big Bang Model

The other related methodologies are Agile Model, RAD Model, Rapid
Application Development and Prototyping Models.

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

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

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

The Waterfall Model was first Process Model to be introduced. It is also


referred to as a linear-sequential life cycle model. It is very simple to
understand and use. In a waterfall model, each phase must be completed
before the next phase can begin and there is no overlapping in the phases.

WATERFALL MODEL

Waterfall model is the earliest SDLC approach that was used for
software development .

The waterfall Model illustrates the software development process in a


linear sequential flow; hence it is also referred to as a linear-sequential life
cycle model. This means that any phase in the development process begins
only if the previous phase is complete. In waterfall model phases do not
overlap.

Waterfall Model design

Waterfall approach was first SDLC Model to be used widely in Software


Engineering to ensure success of the project. In "The Waterfall" approach, the
whole process of software development is divided into separate phases. In
Waterfall model, typically, the outcome of one phase acts as the input for the
next phase sequentially.

Following is a diagrammatic representation of different phases of


waterfall model.

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

Requirement Gathering and analysis


All possible requirements of the system to be developed are captured
in this phase and documented in a requirement specification doc.

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.

Integration and Testing


All the units developed in the implementation phase are integrated into
a system after testing of each unit. Post integration the entire system is tested
for any faults and failures.

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

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

Waterfall Model Application

Every software developed is different and requires a suitable SDLC


approach to be followed based on the internal and external factors. Some
situations where the use of Waterfall model is most appropriate are:

Requirements are very well documented, clear and fixed.

Product definition is stable.

Technology is understood and is not dynamic.

There are no ambiguous requirements.

Ample resources with required expertise are available to support the


product.

The project is short.

Waterfall Model Pros & Cons

Advantage

The advantage of waterfall development is that it allows for


departmentalization and control. A schedule can be set with deadlines for
each stage of development and a product can proceed through the
development process model phases one by one.

Development moves from concept, through design, implementation,


testing, installation, troubleshooting, and ends up at operation and
maintenance. Each phase of development proceeds in strict order.

Disadvantage

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

In Iterative model, iterative process starts with a simple implementation


of a small set of the software requirements and iteratively enhances the
evolving versions until the complete system is implemented and ready to be
deployed.

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

Iterative and Incremental development is a combination of both iterative


design or iterative method and incremental build model for development.
"During software development, more than one iteration of the software
development cycle may be in progress at the same time." and "This process
may be described as an "evolutionary acquisition" or "incremental build"
approach."
In incremental model the whole requirement is divided into various
builds. During each iteration, the development module goes through the
requirements, design, implementation and testing phases. Each subsequent
release of the module adds function to the previous release. The process
continues till the complete system is ready as per the requirement.
The key to successful use of an iterative software development lifecycle
is rigorous validation of requirements, and verification & testing of each
version of the software against those requirements within each cycle of the
model. As the software evolves through successive cycles, tests have to be
repeated and extended to verify each version of the software.

Iterative Model Application

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

Requirements of the complete system are clearly defined and


understood.

Major requirements must be defined; however, some functionalities or


requested enhancements may evolve with time.

There is a time to the market constraint.

A new technology is being used and is being learnt by the development


team while working on the project.

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.

Iterative Model Pros and Cons

The advantage of this model is that there is a working model of the


system at a very early stage of development which makes it easier to find
functional or design flaws. Finding issues at an early stage of development
enables to take corrective measures in a limited budget.

The disadvantage with this SDLC model is that it is applicable only to


large and bulky software development projects. This is because it is hard to
break a small software system into further small serviceable
increments/modules.

The following table lists out the pros and cons of Iterative and Incremental
SDLC Model:

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

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

This phase starts with gathering the business requirements in the


baseline spiral. In the subsequent spirals as the product matures,
identification of system requirements, subsystem requirements and unit
requirements are all done in this phase.
This also includes understanding the system requirements by continuous
communication between the customer and the system analyst. At the end of
the spiral the product is deployed in the identified market.

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

Construct phase refers to production of the actual software product at


every spiral. In the baseline spiral when the product is just thought of and
the design is being developed a POC (Proof of Concept) is developed in this
phase to get customer feedback.

Then in the subsequent spirals with higher clarity on requirements and


design details a working model of the software called build is produced with
a version number. These builds are sent to customer for feedback.

Evaluation and Risk Analysis

Risk Analysis includes identifying, estimating, and monitoring technical


feasibility and management risks, such as schedule slippage and cost
overrun. After testing the build, at the end of first iteration, the customer
evaluates the software and provides feedback.

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

Based on the customer evaluation, software development process


enters into the next iteration and subsequently follows the linear approach to
implement the feedback suggested by the customer. The process of iterations
along the spiral continues throughout the life of the software.
Spiral Model Application

Spiral Model is very widely used in the software industry as it is in


synch with the natural development process of any product i.e. learning with
maturity and also involves minimum risk for the customer as well as the
development firms. Following are the typical uses of Spiral model:

When costs there is a budget constraint and risk evaluation is


important.

For medium to high-risk projects.

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

Customer is not sure of their requirements which is usually the case.

Requirements are complex and need evaluation to get clarity.

New product line which should be released in phases to get enough


customer feedback.

Significant changes are expected in the product during the development


cycle.

Spiral Model Pros and Cons

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:

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 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 SDLC model is a combination of iterative and incremental process


models with focus on process adaptability and customer satisfaction by rapid
delivery of working software product.

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.

At the end of the iteration a working product is displayed to the


customer and important stakeholders.

What is Agile?

Agile model believes that every project needs to be handled differently


and the existing methods need to be tailored to best suit the project
requirements. In agile the tasks are divided to time boxes (small time frames)
to deliver specific features for a release.
Iterative approach is taken and working software build is delivered after
each iteration. Each build is incremental in terms of features; the final build
holds all the features required by the customer.
Here is a graphical illustration of the Agile Model:

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

Following are the Agile Manifesto principles

Individuals and interactions - in agile development, self-organization


and motivation are important, as are interactions like co-location and
pair programming.

Working software - Demo working software is considered the best


means of communication with the customer to understand their
requirement, instead of just depending on documentation.

Customer collaboration - As the requirements cannot be gathered


completely in the beginning of the project due to various factors,
continuous customer interaction is very important to get proper
product requirements.

Responding to change - agile development is focused on quick


responses to change and continuous development.

Agile Vs Traditional SDLC Models

Agile is based on the adaptive software development methods where as


the traditional SDLC models like waterfall model is based on predictive
approach.
Predictive teams in the traditional SDLC models usually work with
detailed planning and have a complete forecast of the exact tasks and features
to be delivered in the next few months or during the product life cycle.
Predictive methods entirely depend on the requirement analysis and planning
done in the beginning of cycle. Any changes to be incorporated go through a
strict change control management and prioritization.
Agile uses adaptive approach where there is no detailed planning and
there is clarity on future tasks only in respect of what features need to be
developed. There is feature driven development and the team adapts to the
changing product requirements dynamically. The product is tested very
frequently, through the release iterations, minimizing the risk of any major
failures in future.

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

Agile Model Pros and Cons


Agile methods are being widely accepted in the software world recently,
however, this method may not always be suitable for all products. Here are
some pros and cons of the agile model.

Following table lists out the pros and cons of Agile Model:

RAD MODEL

The RAD (Rapid Application Development) model is based on


prototyping and iterative development with no specific planning involved. The
process of writing the software itself involves the planning required for
developing the product.

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

Rapid application development (RAD) is a software development


methodology that uses minimal planning in favor of rapid prototyping. A
prototype is a working model that is functionally equivalent to a component
of the product.
In RAD model the functional modules are developed in parallel as
prototypes and are integrated to make the complete product for faster product
delivery.
Since there is no detailed preplanning, it makes it easier to incorporate
the changes within the development process. RAD projects follow iterative and
incremental model and have small teams comprising of developers, domain
experts, customer representatives and other IT resources working
progressively on their component or prototype.
The most important aspect for this model to be successful is to make
sure that the prototypes developed are reusable.

RAD Model Design

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.

Testing and Turnover


The overall testing time is reduced in RAD model as the prototypes are
independently tested during every iteration. However the data flow and the
interfaces between all the components need to be thoroughly tested with
complete test coverage. Since most of the programming components have
already been tested, it reduces the risk of any major issues.

Following image illustrates the RAD Model:

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 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 Model Application

RAD model can be applied successfully to the projects in which clear


modularization is possible. If the project cannot be broken into modules, RAD
may fail. Following are the typical scenarios where RAD can be used:
RAD should be used only when a system can be modularized to be
delivered in incremental manner.

It should be used if there.s high availability of designers for modeling.

It should be used only if the budget permits use of automated code


generating tools.

RAD SDLC model should be chosen only if domain experts are available
with relevant business knowledge.

Should be used where the requirements change during the course of


the project and working prototypes are to be presented to customer in
small iterations of 2-3 months.

RAD Model Pros and Cons

RAD model enables rapid delivery as it reduces the overall development


time due to reusability of the components and parallel development.
RAD works well only if high skilled engineers are available and the
customer is also committed to achieve the targeted prototype in the given time
frame. If there is commitment lacking on either side the model may fail.

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

SOFTWARE PROTOTYPE MODEL

The Software Prototyping refers to building software application


prototypes which display the functionality of the product under development
but may not actually hold the exact logic of the original software.
Software prototyping is becoming very popular as a software
development model, as it enables to understand customer requirements at an
early stage of development. It helps get valuable feedback from the customer
and helps software designers and developers understand about what exactly
is expected from the product under development.

What is Software Prototyping?

Prototype is a working model of software with some limited


functionality.

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.

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

Following is the stepwise approach to design a software prototype:

Basic Requirement Identification


This step involves understanding the very basics product requirements
especially in terms of user interface. The more intricate details of the internal
design and external aspects like performance and security can be ignored at
this stage.

Developing the initial Prototype


The initial Prototype is developed in this stage, where the very basic
requirements are showcased and user interfaces are provided. These features
may not exactly work in the same manner internally in the actual software
developed and the workarounds are used to give the same look and feel to the
customer in the prototype developed.

Review of the Prototype


The prototype developed is then presented to the customer and the
other important stakeholders in the project. The feedback is collected in an
organized manner and used for further enhancements in the product under
development.

Revise and enhance the Prototype


The feedback and the review comments are discussed during this stage
and some negotiations happen with the customer based on factors like , time
and budget constraints and technical feasibility of actual implementation. The
changes accepted are again incorporated in the new Prototype developed and
the cycle repeats until customer expectations are met.

Prototypes can have horizontal or vertical dimensions. Horizontal


prototype displays the user interface for the product and gives a broader view
of the entire system, without concentrating on internal functions. A vertical
prototype on the other side is a detailed elaboration of a specific function or a
sub system in the product.

The purpose of both horizontal and vertical prototype is different.


Horizontal prototypes are used to get more information on the user interface
level and the business requirements. It can even be presented in the sales
demos to get business in the market. Vertical prototypes are technical in
nature and are used to get details of the exact functioning of the sub systems.
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 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 Prototyping Types

There are different types of software prototypes used in the industry.


Following are the major software prototyping types used widely:

Throwaway/Rapid Prototyping: Throwaway prototyping is also called as


rapid or close ended prototyping. This type of prototyping uses very little
efforts with minimum requirement analysis to build a prototype. Once the
actual requirements are understood, the prototype is discarded and the actual
system is developed with a much clear understanding of user requirements.

Evolutionary Prototyping: Evolutionary prototyping also called as


breadboard prototyping is based on building actual functional prototypes with
minimal functionality in the beginning. The prototype developed forms the
heart of the future prototypes on top of which the entire system is built. Using
evolutionary prototyping only well understood requirements are included in
the prototype and the requirements are added as and when they are
understood.

Incremental Prototyping: Incremental prototyping refers to building


multiple functional prototypes of the various sub systems and then
integrating all the available prototypes to form a complete system.

Extreme Prototyping : Extreme prototyping is used in the web development


domain. It consists of three sequential phases. First, a basic prototype with
all the existing pages is presented in the html format. Then the data
processing is simulated using a prototype services layer. Finally the services
are implemented and integrated to the final prototype. This process is called
Extreme Prototyping used to draw attention to the second phase of the
process, where a fully functional UI is developed with very little regard to the
actual services.

Software Prototyping Application

Software Prototyping is most useful in development of systems having


high level of user interactions such as online systems. Systems which need
users to fill out forms or go through various screens before data is processed
can use prototyping very effectively to give the exact look and feel even before
the actual software is developed.

Software that involves too much of data processing and most of the
functionality is internal with very little user interface does not usually benefit

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

Software prototyping is used in typical cases and the decision should


be taken very carefully so that the efforts spent in building the prototype add
considerable value to the final software developed. The model has its own pros
and cons discussed as below.

Following table lists out the pros and cons of Software Prototype Model:

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

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

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

The students/trainees must be provided with the following:


Reference Book s
Handouts/Modules/Printed Materials

Assessment Method:
Oral recitation
Written examinations
Case Study (Defense)

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

To model a system the most important aspect is to capture the dynamic


behaviour. To clarify a bit in details, dynamic behaviour means the behaviour
of the system when it is running /operating.

So only static behaviour is not sufficient to model a system rather


dynamic behaviour is more important than static behaviour. In UML there are
five diagrams available to model dynamic nature and use case diagram is one
of them. Now as we have to discuss that the use case diagram is dynamic in
nature there should be some internal or external factors for making the
interaction.

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

The purpose of use case diagram is to capture the dynamic aspect of a


system. But this definition is too generic to describe the purpose.

Because other four diagrams (activity, sequence, collaboration and


Statechart) are also having the same purpose. So we will look into some
specific purpose which will distinguish it from other four diagrams.

Use case diagrams are used to gather the requirements of a system


including internal and external influences. These requirements are mostly
design requirements. So when a system is analyzed to gather its
functionalities use cases are prepared and actors are identified.

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

So in brief, the purposes of use case diagrams can be as follows:

Used to gather requirements of a system.

Used to get an outside view of a system.

Identify external and internal factors influencing the system.

Show the interacting among the requirements are actors.

How to draw Use Case Diagram?

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.

The actors can be human user, some internal applications or may be


some external applications. So in a brief when we are planning to draw an use
case diagram we should have the following items identified.

Functionalities to be represented as an use case

Actors

Relationships among the use cases and actors.

Use case diagrams are drawn to capture the functional requirements of


a system. So after identifying the above items we have to follow the following
guidelines to draw an efficient use case diagram.

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.

Give a suitable name for actors.

Show relationships and dependencies clearly in the diagram.

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

Use note when ever required to clarify some important points.

The following is a sample use case diagram representing the order


management system. So if we look into the diagram then we will find three
use cases (Order, SpecialOrder and NormalOrder) and one actor which is
customer.

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

<<extends>> which specifies that in certain situations, or at some point


(called an extension point) a Use Case will be extended by another.

Generalization specifies that a Use Case inherits the characteristics of the


Super-Use Case, and can override some of them or add new ones in a similar
way as the inheritance between classes.
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 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?

As we have already discussed there are five diagrams in UML to model


dynamic view of a system. Now each and every model has some specific
purpose to use. Actually these specific purposes are different angles of a
running system.

So to understand the dynamics of a system we need to use different


types of diagrams. Use case diagram is one of them and its specific purpose
is to gather system requirements and actors.

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:

Requirement analysis and high level design.

Model the context of a system.

Reverse engineering.

Forward engineering.

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

Criterion for good scenarios are the following:

o Acts as a bridge between an initial design idea or problem and a


solution
o Advances the fidelity of an idea
o Stands on its own, without explanation
o Does not prescribe interface elements in any great detail
o Includes a rich description of a person
o Includes a rich description of a goal
o Is credible

Writing Scenarios
The following are the steps to be undertaken in writing scenarios.

Identify the people involved

What are their names?


Where do they work?
What level of technical experience do they have?
What level of technical competence can you assume with this system,
specifically?

Its often helpful to write a three or four sentence introduction to each


person, describing their background and helping to humanize them.

Identify the starting state / context

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?

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

A goal is about a fundamental want, need, or desire that is presently


unattained. Goals rarely change, even as technology progresses. For example,
when using a printer, my goal is not to print it is to communicate my
intent to other people when Im not there through a lasting artifact.

List as many goals as you can think of.

Prioritize the goals, based on your understanding of your users.

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

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

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

Used to get an outside view of a system.

Identify external and internal factors influencing the system.

Show the interacting among the requirements are actors.


3. <<includes>>

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

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 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 is a standard language for specifying, visualizing, constructing,


and documenting the artifacts of software systems.

UML was created by Object Management Group (OMG) and UML 1.0
specification draft was proposed to the OMG in January 1997.

OMG is continuously putting effort to make a truly industry standard.

UML stands for Unified Modeling Language.

UML is different from the other common programming languages


like C++, Java, COBOL etc.

UML is a pictorial language used to make software blue prints.

So UML can be described as a general purpose visual modeling language


to visualize, specify, construct and document software system. Although UML
is generally used to model software systems but it is not limited within this
boundary. It is also used to model non software systems as well like process
flow in a manufacturing unit etc.

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

A picture is worth a thousand words, this absolutely fits while


discussing about UML. Object oriented concepts were introduced much
earlier than UML. So at that time there were no standard methodologies to

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

Conceptual model of UML

To understand conceptual model of UML first we need to clarify What


is a conceptual model? and Why a conceptual model is at all required?

A conceptual model can be defined as a model which is made of


concepts and their relationships.

A conceptual model is the first step before drawing a UML diagram. It


helps to understand the entities in the real world and how they interact
with each other.

As UML describes the real time systems it is very important to make a


conceptual model and then proceed gradually. Conceptual model of UML can
be mastered by learning the following three major elements:

UML building blocks


Rules to connect the building blocks
Common mechanisms of UML

Object oriented concepts

UML can be described as the successor of object oriented analysis and


design.
An object contains both data and methods that control the data. The
data represents the state of the object. A class describes an object and they
also form hierarchy to model real world system. The hierarchy is represented
as inheritance and the classes can also be associated in different manners as
per the requirement.

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

Following are some fundamental concepts of object oriented world:

Objects: Objects represent an entity and the basic building block.

Class: Class is the blue print of an object.

Abstraction: Abstraction represents the behavior of an real world entity.

Encapsulation: Encapsulation is the mechanism of binding the data


together and hiding them from outside world.

Inheritance: Inheritance is the mechanism of making new classes from


existing one.

Polymorphism: It defines the mechanism to exists in different forms.

OO Analysis and Design

Object Oriented analysis can be defined as investigation and to be more


specific it is the investigation of objects. Design means collaboration of
identified objects.

So it is important to understand the OO analysis and design concepts.


Now the most important purpose of OO analysis is to identify objects of a
system to be designed. This analysis is also done for an existing system. Now
an efficient analysis is only possible when we are able to start thinking in a
way where objects can be identified. After identifying the objects their
relationships are identified and finally the design is produced.

So the purpose of OO analysis and design can described as:

Identifying the objects of a system.

Identify their relationships.

Make a design which can be converted to executables using OO


languages.

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

OO Analysis --> OO Design --> OO implementation using OO languages

Now the above three points can be described in details:

During object oriented analysis the most important purpose is to


identify objects and describing them in a proper way. If these objects
are identified efficiently then the next job of design is easy. The objects
should be identified with responsibilities. Responsibilities are the
functions performed by the object. Each and every object has some type
of responsibilities to be performed. When these responsibilities are
collaborated the purpose of the system is fulfilled.

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.

The third phase is object oriented implementation. In this phase the


design is implemented using object oriented languages like Java, C++
etc.

Role of UML in OO design:

UML is a modeling language used to model software and non software


systems. Although UML is used for non software systems the emphasis is on
modeling object oriented software applications. Most of the UML diagrams
discussed so far are used to model different aspects like static, dynamic etc.
Now what ever be the aspect the artifacts are nothing but objects.
If we look into class diagram, object diagram, collaboration diagram,
interaction diagrams all would basically be designed based on the objects.
So the relation between OO design and UML is very important to
understand. The OO design is transformed into UML diagrams according to
the requirement. Before understanding the UML in details the OO concepts
should be learned properly. Once the OO analysis and design is done the next
step is very easy. The input from the OO analysis and design is the input to
the UML diagrams.
UML is popular for its diagrammatic notations. We all know that UML
is for visualizing, specifying, constructing and documenting the components
of software and non software systems. Here the Visualization is the most
important part which needs to be understood and remembered by heart.

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

So learning notations should be emphasized from the very beginning.


Different notations are available for things and relationships. And the UML
diagrams are made using the notations of things and relationships.
Extensibility is another important feature which makes UML more powerful
and flexible.

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

UML class is represented by the diagram shown below. The diagram is


divided into four parts.

The top section is used to name the class.


The second one is used to show the attributes of the class.
The third section is used to describe the operations performed by the
class.
The fourth section is optional to show any additional components.

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

As object is the actual implementation of a class which is known as the


instance of a class. So it has the same usage as the class.

Interface Notation

Interface is represented by a circle as shown below. It has a name which is


generally written below the circle.

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

Collaboration is represented by a dotted eclipse as shown below. It has a


name written inside the eclipse.

Collaboration represents responsibilities. Generally responsibilities are in a


group.

Use case Notation:

Use case is represented as an eclipse with a name inside it. It may contain
additional responsibilities.

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

An actor can be defined as some internal or external entity that interacts


with the system.

Actor is used in a use case diagram to describe the internal or external


entities.

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

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

The usage of Final State Notation is to show the termination point of a


process.

Active class Notation:

Active class looks similar to a class with a solid border. Active class is
generally used to describe concurrent behaviour of a system.

Active class is used to represent concurrency in a system.

Component Notation:

A component in UML is shown as below with a name inside. Additional


elements can be added wherever required.

Component is used to represent any part of a system for which UML


diagrams are made.

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

A node in UML is represented by a square box as shown below with a name.


A node represents a physical component of the system.

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.

Interactions can be of two types:

Sequential (Represented by sequence diagram)


Collaborative (Represented by collaboration diagram)

Interaction Notation:

Interaction is basically message exchange between two UML components.


The following diagram represents different notations used in an interaction.

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

State machine describes the different states of a component in its life cycle.
The notations are described in the following diagram.

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

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

In any diagram explanation of different elements and their functionalities


are very important. So UML has notes notation to support this requirement.

Note Notation:

This notation is shown below and they are used to provide necessary
information of a system.

Relationships

A model is not complete unless the relationships between elements are


described properly. The Relationship gives a proper meaning to an UML
model. Following are the different types of relationships available in UML.

Dependency
Association
Generalization
Extensibility

Dependency Notation:

Dependency is an important aspect in UML elements. It describes the


dependent elements and the direction of dependency.

Dependency is represented by a dotted arrow as shown below. The arrow


head represents the independent element and the other end the dependent
element.

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

Association describes how the elements in an UML diagram are associated.


In simple word it describes how many elements are taking part in an
interaction.

Association is represented by a dotted line with (without) arrows on both


sides. The two ends represent two associated elements as shown below. The
multiplicity is also mentioned at the ends (1, * etc) to show how many
objects are associated.

Association is used to represent the relationship between two elements of a


system.

Generalization Notation:

Generalization describes the inheritance relationship of the object oriented


world. It is parent and child relationship.

Generalization is represented by an arrow with hollow arrow head as shown


below. One end represents the parent element and the other end child
element.

Generalization is used to describe parent-child relationship of two elements


of a system.

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

All the languages (programming or modeling) have some mechanism to


extend its capabilities like syntax, semantics etc. UML is also having the
following mechanisms to provide extensibility features.

Stereotypes (Represents new elements)


Tagged values (Represents new attributes)
Constraints (Represents the boundaries)

Extensibility notations are used to enhance the power of the language. It is


basically additional elements used to represent some extra behaviour of the
system. These extra behaviours are not covered by the standard available
notations.

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

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

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

Any complex system is best understood by making some kind of diagrams or


pictures. These diagrams have a better impact on our understanding. So if we
look around then we will realize that the diagrams are not a new concept but
it is used widely in different form in different industries.

We prepare UML diagrams to understand a system in better and simple way.


A single diagram is not enough to cover all aspects of the system. So UML
defines various kinds of diagrams to cover most of the aspects of a system.

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.

These static parts are represents by classes, interfaces, objects, components


and nodes. The four structural diagrams are:
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 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.

Active class is used in a class diagram to represent the concurrency of the


system.

Class diagram represents the object orientation of a system. So it is generally


used for development purpose. This is the most widely used diagram at the
time of system construction.

Object Diagram

Object diagrams can be described as an instance of class diagram. So these


diagrams are more close to real life scenarios where we implement a system.

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

Component diagrams represent a set of components and their relationships.


These components consist of classes, interfaces or collaborations.

So Component diagrams represent the implementation view of a system.

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.

Finally, component diagrams are used to visualize the implementation.

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

Deployment diagrams are used for visualizing deployment view of a system.


This is generally used by the deployment team.

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.

Behavioral diagrams basically capture the dynamic aspect of a system.


Dynamic aspect can be further described as the changing/moving parts of a
system.

UML has the following types of behavioral diagrams:

Sequence diagram
Collaboration diagram
Statechart diagram
Activity diagram

Sequence Diagram:

A sequence diagram is an interaction diagram. From the name it is clear that


the diagram deals with some sequences, which are the sequence of messages
flowing from one object to another.

Interaction among the components of a system is very important from


implementation and execution perspective.

So Sequence diagram is used to visualize the sequence of calls in a system to


perform a specific functionality.

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

Collaboration diagram is another form of interaction diagram. It represents


the structural organization of a system and the messages sent/received.
Structural organization consists of objects and links.

The purpose of collaboration diagram is similar to sequence diagram. But the


specific purpose of collaboration diagram is to visualize the organization of
objects and their interaction.

Statechart Diagram:

Any real time system is expected to be reacted by some kind of


internal/external events. These events are responsible for state change of the
system.

Statechart diagram is used to represent the event driven state change of a


system. It basically describes the state change of a class, interface etc.

State chart diagram is used to visualize the reaction of a system by


internal/external factors.

Activity Diagram:

Activity diagram describes the flow of control in a system. So it consists of


activities and links. The flow can be sequential, concurrent or branched.

Activities are nothing but the functions of a system. Numbers of activity


diagrams are prepared to capture the entire flow in a system.

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.

Note: Dynamic nature of a system is very difficult to capture. So UML has


provided features to capture the dynamics of a system from different angles.
Sequence diagrams and collaboration diagrams are isomorphic so they can be
converted from one another without losing any information. This is also true for
statechart and activity diagram.

CLASS DIAGRAMS

The class diagram is a static diagram. It represents the static view of an


application. Class diagram is not only used for visualizing, describing and
documenting different aspects of a system but also for constructing
executable code of the software application.

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

The class diagram shows a collection of classes, interfaces, associations,


collaborations and constraints. It is also known as a structural diagram.

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.

So the purpose of the class diagram can be summarized as:

Analysis and design of the static view of an application.


Describe responsibilities of a system.
Base for component and deployment diagrams.
Forward and reverse engineering.

How to draw Class Diagram?

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.

Class diagram is basically a graphical representation of the static view of the


system and represents different aspects of the application. So a collection of
class diagrams represent the whole system.

The following points should be remembered while drawing a class diagram:

The name of the class diagram should be meaningful to describe the


aspect of the system.
Each element and their relationships should be identified in advance.
Responsibility (attributes and methods) of each class should be clearly
identified.

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

Now the following diagram is an example of an Order System of an application.


So it describes a particular aspect of the entire application.

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:

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

Class diagram is a static diagram and it is used to model static view of a


system. The static view describes the vocabulary of the system.

Class diagram is also considered as the foundation for component and


deployment diagrams. Class diagrams are not only used to visualize the static
view of the system but they are also used to construct the executable code for
forward and reverse engineering of any system.

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.

So in a brief, class diagrams are used for:

Describing the static view of the system.


Showing the collaboration among the elements of the static view.
Describing the functionalities performed by the system.
Construction of software applications using object oriented languages.

OBJECT DIAGRAM

Object diagrams are derived from class diagrams so object diagrams are
dependent upon class diagrams.

Object diagrams represent an instance of a class diagram. The basic concepts


are similar for class diagrams and object diagrams. Object diagrams also
represent the static view of a system but this static view is a snapshot of the
system at a particular moment.

Object diagrams are used to render a set of objects and their relationships as
an instance.

Purpose:

The purpose of a diagram should be understood clearly to implement it


practically. The purposes of object diagrams are similar to class diagrams.

The difference is that a class diagram represents an abstract model consisting


of classes and their relationships. But an object diagram represents an
instance at a particular moment which is concrete in nature.
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 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 the purpose of the object diagram can be summarized as:

Forward and reverse engineering.


Object relationships of a system
Static view of an interaction.
Understand object behaviour and their relationship from practical
perspective

How to draw Object Diagram?

We have already discussed that an object diagram is an instance of a class


diagram. It implies that an object diagram consists of instances of things used
in a class diagram.

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.

To capture a particular system, numbers of class diagrams are limited. But if


we consider object diagrams then we can have unlimited number of instances
which are unique in nature. So only those instances are considered which are
having impact on the system.

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.

Before drawing an object diagrams the following things should be remembered


and understood clearly:

Object diagrams are consist of objects.


The link in object diagram is used to connect objects.
Objects and links are the two elements used to construct an object
diagram.

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

The object diagram should have a meaningful name to indicate its


purpose.
The most important elements are to be identified.
The association among objects should be clarified.
Values of different elements need to be captured to include in the object
diagram.
Add proper notes at points where more clarity is required.

The following diagram is an example of an object diagram. It represents the


Order management system which we have discussed in Class Diagram. The
following diagram is an instance of the system at a particular time of
purchase. It has the following objects

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:

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

Object diagrams can be imagined as the snapshot of a running system at a


particular moment. Now to clarify it we can take an example of a running
train.

Now if you take a snap of the running train then you will find a static picture
of it having the following:

A particular state which is running


A particular number of passengers. which will change if the snap is
taken in a different time.

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:

Making the prototype of a system.


Reverse engineering.
Modeling complex data structures.
Understanding the system from practical perspective.

COMPONENT DIAGRAM

Component diagrams are different in terms of nature and behaviour.


Component diagrams are used to model physical aspects of a system.

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.

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

Component diagram is a special kind of diagram in UML. The purpose is also


different from all other diagrams discussed so far. It does not describe the
functionality of the system but it describes the components used to make
those functionalities.

So from that point component diagrams are used to visualize the physical
components in a system. These components are libraries, packages, files etc.

Component diagrams can also be described as a static implementation view


of a system. Static implementation represents the organization of the
components at a particular moment.

A single component diagram cannot represent the entire system but a


collection of diagrams are used to represent the whole.

So the purpose of the component diagram can be summarized as:

Visualize the components of a system.


Construct executables by using forward and reverse engineering.
Describe the organization and relationships of the components.

How to draw Component Diagram?

Component diagrams are used to describe the physical artifacts of a system.


This artifact includes files, executables, libraries etc.

So the purpose of this diagram is different, Component diagrams are used


during the implementation phase of an application. But it is prepared well in
advance to visualize the implementation details.

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.

This diagram is very important because without it the application cannot be


implemented efficiently. A well prepared component diagram is also important
for other aspects like application performance, maintenance etc.

So before drawing a component diagram the following artifacts are to be


identified clearly:
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 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:

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

These diagrams show the physical components of a system. To clarify it, we


can say that component diagrams describe the organization of the
components in a system.

Organization can be further described as the location of the components in a


system. These components are organized in a special way to meet the system
requirements.

As we have already discussed those components are libraries, files,


executables etc. Now before implementing the application these components
are to be organized. This component organization is also designed separately
as a part of project execution.

Component diagrams are very important from implementation perspective. So


the implementation team of an application should have a proper knowledge
of the component details.

Now the usage of component diagrams can be described as:

Model the components of a system.


Model database schema.
Model executables of an application.
Model system's source code.

DEPLOYMENT DIAGRAM

Deployment diagrams are used to visualize the topology of the physical


components of a system where the software components are deployed.

So deployment diagrams are used to describe the static deployment view of a


system. Deployment diagrams consist of nodes and their relationships.

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.

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

UML is mainly designed to focus on software artifacts of a system. But these


two diagrams are special diagrams used to focus on software components and
hardware components.

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.

The purpose of deployment diagrams can be described as:

Visualize hardware topology of a system.


Describe the hardware components used to deploy software
components.
Describe runtime processing nodes.

How to draw Deployment Diagram?

Deployment diagram represents the deployment view of a system. It is related


to the component diagram. Because the components are deployed using the
deployment diagrams. A deployment diagram consists of nodes. Nodes are
nothing but physical hardwares used to deploy the application.

Deployment diagrams are useful for system engineers. An efficient


deployment diagram is very important because it controls the following
parameters

Performance
Scalability
Maintainability
Portability

So before drawing a deployment diagram the following artifacts should be


identified:

Nodes
Relationships among nodes

The following deployment diagram is a sample to give an idea of the


deployment view of order management system. Here we have shown nodes as:

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

The application is assumed to be a web based application which is deployed


in a clustered environment using server 1, server 2 and server 3. The user is
connecting to the application using internet. The control is flowing from the
caching server to the clustered environment.

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.

This interactive behaviour is represented in UML by two diagrams known as


Sequence diagram and Collaboration diagram. The basic purposes of both the
diagrams are similar.

Sequence diagram emphasizes on time sequence of messages and


collaboration diagram emphasizes on the structural organization of the
objects that send and receive messages.

Purpose:

The purposes of interaction diagrams are to visualize the interactive behaviour


of the system. Now visualizing interaction is a difficult task. So the solution is
to use different types of models to capture the different aspects of the
interaction.

That is why sequence and collaboration diagrams are used to capture


dynamic nature but from a different angle.

So the purposes of interaction diagram can be describes as:

To capture dynamic behaviour of a system.


To describe the message flow in the system.
To describe structural organization of the objects.
To describe interaction among objects.

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

As we have already discussed that the purpose of interaction diagrams are to


capture the dynamic aspect of a system. So to capture the dynamic aspect we
need to understand what a dynamic aspect is and how it is visualized.
Dynamic aspect can be defined as the snap shot of the running system at a
particular moment.

We have two types of interaction diagrams in UML. One is sequence diagram


and the other is a collaboration diagram. The sequence diagram captures the
time sequence of message flow from one object to another and the
collaboration diagram describes the organization of objects in a system taking
part in the message flow.

So the following things are to identified clearly before drawing the interaction
diagram:

Objects taking part in the interaction.


Message flows among the objects.
The sequence in which the messages are flowing.
Object organization.

Following are two interaction diagrams modeling order management system.


The first diagram is a sequence diagram and the second is a collaboration
diagram.

The Sequence Diagram:

The sequence diagram is having four objects (Customer, Order, SpecialOrder


and NormalOrder).

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.

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 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 second interaction diagram is collaboration diagram. It shows the object


organization as shown below. Here in collaboration diagram the method call
sequence is indicated by some numbering technique as shown below. The
number indicates how the methods are called one after another. We have
taken the same order management system to describe 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.

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

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

Although Figure 1 applies sequence numbers to the messages, my experience


is if you feel the need to use sequence numbers on communication diagrams
this is a good indication you should be using sequence diagrams instead. The
main difference between communication diagrams and sequence diagrams is
that sequence diagrams are good at showing sequential logic but not that good
at giving you a big picture view whereas communication diagrams are the
exact opposite.

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

Another trick I often use is to consolidate trivial messages such as getter


invocations. In I modeled the series of getter method invocations to obtain the
information needed to display the list of students enrolled in a seminar as the
single message getInfo. I also added a note to the diagram to make it clear
what I was doing, but I typically don't do that. Why is this important? Because
agile developers will only do things that add value, and defining an exact list
of getter invocations wouldn't have added value.

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.

Where to use Interaction Diagrams?

We have already discussed that interaction diagrams are used to describe


dynamic nature of a system. Now we will look into the practical scenarios
where these diagrams are used. To understand the practical application we
need to understand the basic nature of sequence and collaboration diagram.

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

In a brief the following are the usages of interaction diagrams:

To model flow of control by time sequence.


To model flow of control by structural organizations.
For forward engineering.
For reverse engineering.

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

Deployment diagrams are mainly used by system engineers. These diagrams


are used to describe the physical components (hardwares), their distribution
and association.

To clarify it in details we can visualize deployment diagrams as the hardware


components/nodes on which software components reside.

Software applications are developed to model complex business processes.


Only efficient software applications are not sufficient to meet business
requirements. Business requirements can be described as to support
increasing number of users, quick response time etc.

To meet these types of requirements hardware components should be


designed efficiently and in a cost effective way.

Now a day's software applications are very complex in nature. Software


applications can be stand alone, web based, distributed, mainframe based
and many more. So it is very important to design the hardware components
efficiently.

So the usage of deployment diagrams can be described as follows:


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

A Statechart diagram describes a state machine. Now to clarify it state


machine can be defined as a machine which defines different states of an
object and these states are controlled by external or internal events.

Activity diagram explained in next chapter, is a special kind of a Statechart


diagram. As Statechart diagram defines states it is used to model lifetime of
an object.

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.

Following are the main purposes of using Statechart diagrams:

To model dynamic aspect of a system.


To model life time of a reactive system.
To describe different states of an object during its life time.
Define a state machine to model states of an object.
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 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.

Before drawing a Statechart diagram we must have clarified the following


points:

Identify important objects to be analyzed.


Identify the states.
Identify the events.

The following is an example of a Statechart diagram where the state of Order


object is analyzed.

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.

The initial and final state of an object is also shown below.

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

From the above discussion we can define the practical applications of a


Statechart diagram. Statechart diagrams are used to model dynamic aspect
of a system like other four diagrams disused in this tutorial. But it has some
distinguishing characteristics for modeling dynamic nature.

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.

If we look into the practical implementation of Statechart diagram then it is


mainly used to analyze the object states influenced by events. This analysis
is helpful to understand the system behaviour during its execution.

So the main usages can be described as:

To model object states of a system.


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 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 another important diagram in UML to describe dynamic


aspects of the system.

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.

So the purposes can be described as:

Draw the activity flow of a system.


Describe the sequence from one activity to another.
Describe the parallel, branched and concurrent flow of the system.

How to draw Activity Diagram?

Activity diagrams are mainly used as a flow chart consists of activities


performed by the system. But activity diagram are not exactly a flow chart 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 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.

Before drawing an activity diagram we must have a clear understanding about


the elements used in activity diagram. The main element of an activity
diagram is the activity itself. An activity is a function performed by the system.
After identifying the activities we need to understand how they are associated
with constraints and conditions.

So before drawing an activity diagram we should identify the following


elements:

Activities
Association
Conditions
Constraints

Once the above mentioned parameters are identified we need to make a


mental layout of the entire flow. This mental layout is then transformed into
an activity diagram.

The following is an example of an activity diagram for order management


system. In the diagram four activities are identified which are associated with
conditions. One important point should be clearly understood that an activity
diagram cannot be exactly matched with the code. The activity diagram is
made to understand the flow of activities and mainly used by the business
users.

The following diagram is drawn with the four main activities:

Send order by the customer


Receipt of the order
Confirm order
Dispatch order

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.

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

Following are the main usages of activity diagram:

Modeling work flow by using activities.


Modeling business requirements.
High level understanding of the system's functionalities.
Investigate business requirements at a later stage.
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 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.

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

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

The students/trainees must be provided with the following:

1. Reference Book
2. Handouts/Modules/Printed Materials

Assessment Method:
Oral recitation
Written examinations
Case Study (Defense)

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

This information sheet provides an overview of the architectural


concepts upon which Java Enterprise System (Java ES) solutions are based.
The chapter demonstrates how Java ES components, both system service
components and service quality components, are used to support distributed
enterprise solutions.

Java ES solution architectures have two aspects: a logical architecture and a


deployment architecture. The logical architecture depicts the interactions
between the logical building blocks (the software components) of a solution.
The deployment architecture depicts the mapping of the logical architecture
to a physical computing environment. Java ES components play important
roles in both logical architectures and deployment architectures.

This information sheet describes an architectural framework for designing


Java ES solution architectures, followed by an example solution architecture
based on that architectural framework.

The chapter covers the following topics:

Java Enterprise System Architectural Framework


Example Java Enterprise System Solution Architecture
Key Terms in This Chapter

Java Enterprise System Architectural Framework

Java Enterprise System components support the deployment of distributed


enterprise-strength software solutions.

To achieve the required functionality at the levels of performance, availability,


security, scalability, and serviceability mandated by business requirements,
these software solutions must be properly designed.

A number of architectural dimensions are involved in designing distributed


enterprise-strength software solutions. These dimensions represent different
perspectives from which to view the interactions of the many software
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 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:

Infrastructure service dependencies. This dimension emphasizes


the role of system service components (see System Service Components)
in supporting distributed solutions.
Logical tiers. This dimension emphasizes the logical and physical
independence of solution components for the purpose of deploying them
across a network or Internet environment.
Quality of service. This dimension emphasizes how quality of service
requirements, such as availability, security, scalability, and
serviceability, are achieved, including the role of service quality
components (see Service Quality Components).

These three dimensions of solution architecture are shown in the following


figure:

Together these three dimensions represent a single framework that


incorporates the relationships between the software components, both
application components and infrastructure components, that are needed to
achieve the service functions and service quality required of a software
solution.

The following sections describe the three dimensions individually, followed by


a synthesis of the three dimensions into a unified framework.

Dimension 1: Infrastructure Service Dependencies

The interacting software components of distributed enterprise applications


require an underlying set of infrastructure services that allows the distributed
components to communicate with each other, coordinate their work,
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 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.

Infrastructure Service Levels

In designing a distributed software system, whether it consists mostly of


custom-developed components or of out-of-the-box Java ES components, you
need to incorporate a number of infrastructure services. These services
operate at many levels.

The infrastructure service dependency dimension of solution architecture is


illustrated in Dimension 1 figure. The hierarchy of services in Dimension 1
and the dependencies between them constitute an important dimension of a
solutions logical architecture. These infrastructure services provide the
conceptual basis for understanding the role of Java ES system service
components .

In general, the services shown in Dimension 1 divide into three broad


groupings: low-level platform services, high-level application services, and a
group of middleware services, named for their location between the other two
groupings.

Dimension 1: Infrastructure Service Levels

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

Operating system platforms. Provides the basic support for any


process running on a computer. The operating system (such as
Solaris Operating System, Linux, or Microsoft Windows) manages
physical devices as well as memory, threads, and other resources
necessary to support the Java Virtual Machine (JVM machine).
Network transport. Provides basic networking support for
communication between distributed application components running
on different computers. These services include support for protocols
such as TCP and HTTP. Other higher-level communication protocols
(see the messaging level) depend on these basic transport services.
Persistence. Provides support for accessing and storing both static
data (such as user, directory, or configuration information) and
dynamic application data (information that is frequently updated).
Messaging. Provides support for both synchronous and
asynchronous communication between application components.
Synchronous messaging is real-time sending and receipt of messages;
and includes remote method invocation (RMI) between J2EE
components and SOAP interactions with web services. Asynchronous
messaging is communication in which the sending of a message does
not depend on the readiness of the consumer to immediately receive it.
Asynchronous messaging specifications, for example, Java Message
Service (JMS) and ebXML, support guaranteed reliability and other
messaging semantics.
Runtime. Provides support required by any distributed component
model, such as the J2EE or CORBA models. In addition to the remote
method invocation needed for tightly coupled distributed components,
runtime services include component state (life-cycle) management,
thread pool management, synchronization (mutex locking), persistence
services, distributed transaction monitoring, and distributed exception
handling. In a J2EE environment, these runtime services are provided
by EJB, web, and message-driven bean containers in an application
server or web server.
Security and policy. Provides support for secure access to
application resources. These services include support for policies that
govern group or role-based access to distributed resources, as well as
single sign-on capabilities. Single sign-on allows a users authentication
to one service in a distributed system to be automatically applied to
other services (J2EE components, business services, and web services)
in the system.
User collaboration. Provides services that play a key role in
supporting direct communication between users and collaboration
among users in enterprise and Internet environments. As such, these
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 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.

The service levels shown in Dimension 1 reflect a general dependence of the


various infrastructure services on one another, from the lowest-level operating
system services to the highest-level application and integration services. Each
service generally depends on services below it and supports services above it.

Dimension 1, however, does not represent a strict layering of infrastructure


services. Higher-level services can directly interact with lower-level services
without depending on intermediate levels. For example, some runtime
services might depend directly on platform services without requiring any of
the service levels in between. In addition, other service levels, such as a
monitoring or management service, might also be included in this conceptual
illustration.

Java Enterprise System Infrastructure Service Components

Java ES components implement the distributed infrastructure service levels


shown in Dimension 1. The positioning of Java ES system service components
within the different levels is shown in Java ES System Service Components
figure below:

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

In general, each Java ES system service component shown in Java ES System


Service Components figure depends on components below it in the
infrastructure and supports components above it. These dependency and
support relationships are a key factor in designing logical architectures.

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.

Relationships Between Java ES System Service Components


Component Depends On Provides Support To
Portal Server Application Server or
Web Server

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)

Access Manager (for


single sign-on)
Access Application Server or Portal Server
Manager Web Server
If configured for single sign-on:
Directory Server Calendar Server
Messaging Server
Instant Messaging
Application Message Queue Portal Server
Server
Directory Server (for Access Manager
administered objects)
Message Directory Server (for Application Server
Queue administered objects)
Web Server Access Manager (for Portal Server
access control)
Access Manager
Directory None Portal Server
Server
Calendar 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 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

The interacting software components of distributed enterprise applications


can be viewed as residing in a number of logical tiers. These tiers represent
the logical and physical independence of software components, based on the
nature of the services they provide.

The logical tier dimension of solution architecture is illustrated in the


following figure.

Dimension 2: Logical Tiers for Distributed Enterprise Applications

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.

Description of Logical Tiers

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.

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

Logical and Physical Independence

The architectural dimension illustrated in Dimension 2 emphasizes the logical


and physical independence of components, represented by four separate tiers.
These tiers signify the partitioning of application logic across the various
computers in a networked environment:

Logical independence. The four tiers in the architectural model


represent logical independence: You can modify application logic in one
tier (for example, in the business service tier) independently of the logic
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 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.

How you map application components or infrastructure components to a


hardware environment (that is, your deployment architecture) depends on
many factors, depending on the scale and complexity of your software
solution. For very small deployments, a deployment architecture might involve
only a few computers. For large scale deployments, the mapping of
components to a hardware environment might take into account factors such
as the speed and power of different computers, the speed and bandwidth of
network links, security and firewall considerations, and component
replication strategies for high availability and scalability.

Tiered Architecture Applied to System Components

Java ES infrastructure service components provide the underlying


infrastructure support for distributed software solutions. Some of these
solutions, however, include application-level services provided directly by
Java ES components. These solutions use logical tier design approaches.

For example, the email communication services provided by Messaging Server


are implemented using a number of logically distinct configurations of
Messaging Server. these distinct configurations each provide a distinct set of
services. When designing messaging solutions, these distinct configurations
are represented as separate components that are situated in different logical
tiers, as shown in the following figure.

Messaging Server: Example of Tiered Architecture

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

Dimension 3: Quality of Service

The previous two architectural dimensions (infrastructure service


dependencies and logical tiers) mostly concern logical aspects of architecture,
namely which components are needed to interact in what way to deliver
services to end users. However, an equally important dimension of any
deployed solution is the ability of the solution to meet quality-of-service
requirements.

The quality of service dimension of solution architecture highlights the roles


played by Java ES service quality components.

Service Qualities

As Internet and e-commerce services have become more critical to business


operations, the performance, availability, security, scalability, and
serviceability of these services have become key quality-of-service
requirements of large-scale, high-performance deployment architectures.

To design a successful software solution, you have to establish relevant


quality-of-service requirements and design an architecture that meets those
requirements. A number of important service qualities are used to specify

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

Service Qualities Impacting Solution Architecture


System
Service
Qualities Description
Performance The measurement of response time and latency with
respect to user load conditions.
Availability A measure of how often a systems resources and services
are accessible to end users (the uptime of a system).
Security A complex combination of factors that describe the
integrity of a system and its users. Security includes
physical security of systems, network security, application
and data security (authentication and authorization of
users), as well as the secure transport of information.
Scalability The ability to add capacity to a deployed system over time.
Scalability typically involves adding resources to the
system but should not require changes to the deployment
architecture.
Latent capacity The ability of a system to handle unusual peak load usage
without additional resources.
Serviceability The ease by which a deployed system can be maintained,
including monitoring the system, repairing problems that
arise, and upgrading hardware and software components.

The quality-of-service dimension strongly impacts a solutions deployment


architecture: how application components and infrastructure components are
deployed in a physical environment.

The service qualities that affect deployment architecture are closely


interrelated: Requirements for one system quality often affect the design for
other service qualities. For example, higher levels of security might affect
performance, which in turn might affect availability. Adding additional
computers to address availability issues through redundancy often affects
maintenance costs (serviceability).

Understanding how service qualities are interrelated and which trade-offs to


make is key to designing deployment architectures that satisfy both business
requirements and business constraints.

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

Several Java ES components are used principally to enhance the quality of


services provided by system service components or distributed application
components. These software components are often used in conjunction with
hardware components, such as load balancers and firewalls.

The Java ES service quality components, introduced in Service Quality


Components, are summarized as follows:

Availability components. These components provide near-


continuous uptime of a deployed solution.
Access components. These components provide secure Internet
access to system services, and often provide a routing function as well.
Administrative components. These components provide enhanced
serviceability for system components.

The following table shows the most important Java ES service quality
components from an architectural perspective with the system qualities they
impact most.

Service Quality Components and the System Qualities Impacted


Component System Qualities Impacted
Communications Express Security
Scalability
Directory Proxy Server Security
Scalability
High Availability Session Store Availability
Portal Server Secure Remote Access Security
Scalability
Sun Cluster Availability
Scalability
Sun Remote Services Net Connect Serviceability
Sun Cluster Software

Sun Cluster software provides high availability and scalability services for
Java ES components and for applications supported by Java ES
infrastructure.

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

Availability Design Using Sun Cluster Nodes

Sun Cluster data service packages (sometimes referred to as Sun Cluster


agents) are available for all Java ES system service components. You can also
write agents for custom-developed application components.

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

Because of the redundancy necessary to support Sun Cluster environments,


inclusion of Sun Cluster in a solution substantially increases the number of
computers and network links required in your physical environment.

Unlike the services provided by other Java ES components, Sun Cluster


availability services are distributed peer-to-peer services. Sun Cluster
software therefore needs to be installed on every computer in a cluster.

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

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

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

Você também pode gostar