You are on page 1of 362

Page 1 of 362

Page 2 of 362
Unit - 1
Introduction to Object Oriented
Programming

Page 3 of 362
Introduction to Object Oriented Programming

Thinking Object­Oriented

Introduction

Object­oriented programming (OOP) has become extremely popular in the past few years.

Software producers are eager to release object oriented versions of their products. Innumerable volumes and
special issues of academic and trade journals have appeared related to the subject.

In this chapter we will explain the basic principles of object­oriented programming, and by doing so the
following two propositions are illustrated:

OOP is a revolutionary idea, a rare one among those which have come before in programming.

OOP is an evolutionary step, naturally following the footsteps the earlier programming abstractions.

Why Is OOP Popular?

There are a several important reasons for the object­oriented programming to become the dominant
programming paradigm in the past two decades.

Object oriented programming is widely used to solve complex tasks.

It provides a form of abstraction that apply with techniques with which people use to solve problems in their
day­to­day life.

Object­oriented techniques are mainly used to create the complex software systems.

Even though the best tools are available to become proficient in programming languages requires several
aspects like talent, creativity, intelligence, logic, the ability to build and use abstractions, and experience.

Object­oriented programming is a novel way of thinking about what it means to compute, about how we can
structure information and impart our intentions both to each other and to the machine.

A New Paradigm

Object­oriented programming is frequently identified as a new programming paradigm.

Paradigm:  It is a distinct set of concepts or thoughts patterns or example of something. The word also used to
mean the model that hold about a particular area of knowledge.

Other programming paradigms include

The imperative­programming paradigm (languages such as Pascal or C)

The logic programming paradigm (Prolog)

The functional­programming paradigm (ML or Haskell)

A Way of Viewing the World ­ A Real world example

Sharma wishes to send flowers to a friend named Ram, who lives in another city. He cannot simply pick the

Page 4 of 362
Introduction to Object Oriented Programming

flowers and take them to Ram in person due to distance.

So, Sharma simply walks to a nearby flower shop, run by a florist named Varma.

Sharma will tell Varma the kinds of flowers to send to Ram, and the address to which they should be delivered.

Varma send a message to another florist in the city where Ram lives.

That Ram’s florist has a subordinate who makes the flower arrangement.

The florist in Ram′s city get flowers from a flower wholesaler who had interactions with the flower growers,
each of whom had to manage a team of gardeners.

The florist then passes the flowers, along with yet another message, to a delivery person. And finally the
delivery person delivers the flowers to Ram.

Object oriented programming has a collection of interacting agents, called objects. Each object plays their
role.

Each object provides a service, or performs an action, that is used by other members of the community.

Messages and Methods

A method in object­oriented programming is a process associated with a class.

A method defines the behavior of the objects that are produced from the class.

The transmission of a message to an agent (an object) responsible for the action initiates the action in object­
oriented programming.

The message encodes the request for an action and is tagged along by any additional information
(arguments) needed to carry out the request. The object to whom the message is sent is the receiver.

If the receiver accepts the message, the responsibility to carry out the indicated action is accepted.

Page 5 of 362
Introduction to Object Oriented Programming

As a response to a message, the receiver shall implement some method to satisfy the request.

There is an important principle of information hiding in regard to message passing i.e., the actual means by
which the request will be honoured need not be exposed to the client who is sending the request.

There is a designated receiver in message passing and the selection of a method to execute in response to
the message may vary.

For any given message the specific receiver will not be known until the run time, so until then the
determination of which method to invoke cannot be made.

Responsibilities

Describing the behaviour in terms of responsibilities is a fundamental concept in object­oriented programming.

The level of abstraction is increased by discussing a problem in terms of responsibilities. This permits a
greater independence between objects, a critical factor in solving complex problems.

The entire collection of responsibilities associated with an object is often described by the term protocol.

Data structures (that is, objects) are requested by an object oriented program to perform a service.

Classes and Instances

All objects are instances of a class.

The class of the receiver determines the method invoked by an object in response to a message.

In response to similar messages all objects of a given class use the same method.

Example:

In the previous example, although Sharma has only dealt with Varma a few times, Sharma has a rough
idea of the transaction that will occur inside Varma′s flower shop.

Sharma is able to make certain speculations based on his previous experience with other florists, and
hence Sharma can expect that Varma, being an instance of this category, will fit the general pattern.

To represent the category of all florists we can use the term Florist.

In this example, Florist represents a Class. Varma is one of the Florists and hence he represents an object
that is an instance of Class (Florist).

Class Hierarchies­Inheritance

Classes can be organized into a hierarchical inheritance structure.

A child class is a subclass which inherit attributes from a parent class which is higher in the tree.

An parent class is a super class.

Page 6 of 362
Introduction to Object Oriented Programming

This figure shows, the classification from the field of biology listed in a hierarchical tree­like structure, with
more abstract classes (Parent class) listed near the top of the tree, and more specific classes (Child class),
and finally individuals, are listed near the bottom of the tree.

Method Binding and Overriding

Binding is the association between method and class.

Information present in a subclass can override information inherited from a parent class.

Most often, implementation of this approach takes the form of a method in a subclass having the same name
as a method in the parent class, combined with a rule for how the search for a method to match a specific
message is conducted.

With the class of the receiver the search for a method to invoke in response to a given message begins.

The search is conducted in the parent class of this class if no appropriate method is found.

The search continues up towards the parent class chain until either a method is found or the parent class
chain is exhausted.

If methods with the same name can be found higher in the class hierarchy, the method executed is said to
override the inherited behaviour.

Summary of Object­Oriented Concepts

Everything is an object.

Computation is performed by objects communicating with each other, requesting that other objects perform
actions.

Objects communicate through sending and receiving messages. A request for action bundled with whatever
arguments may be necessary to complete the task is a message.

Page 7 of 362
Introduction to Object Oriented Programming

Each object has its own memory, which consists of other objects.

Every object is a specimen of a class. A class simply represents a grouping of similar objects, such as integers
or lists.

The class describes the behaviour or state associated with an object. That is, all objects that are examples of
the same class can perform the same actions.

Classes are organized into a singly rooted tree structure, called the inheritance hierarchy.

Memory and behaviour associated with instances of a class are automatically available to any class associated
with a descendant in this tree structure.

Page 8 of 362
Introduction to Object Oriented Programming

Abstraction

What is Abstraction?

Abstraction is the process of hiding the implementation details and shows only the important details to the user.

Information hiding is the purposeful omission of details in the development of an abstract representation.

Example

In this figure, we have different types of vehicle which have different color, shape, engine type and purpose etc.
that makes them different.

But they have some common properties and behavior among them i.e. they all have tires, engine, steering, gear
etc. They are used for the traveling and can be operated in a common way.

Abstract concept is Vehicle can be the general idea of a car or a truck. It retains only the general vehicle attributes
and behavior, omit the other characteristics of a particular vehicle.

Layers of Abstraction

At the highest level of abstraction we consider program as a group of interacting objects to achieve their goal.

Page 9 of 362
Introduction to Object Oriented Programming

There are 6 layers of abstraction:

Packages and Name Spaces ­ The next level of abstraction is found in some OO languages such as Java
Packages, Namespace in C++. A package, Unit or Name Space which has combined group of objects. Some
features of this unit is shown to the outsiders, other features are not visible to all.

Clients and Servers ­ The next two levels of abstraction considers the relationship between two individual
objects. One object is providing service, and the other using that service. The two layers of abstraction indicates
two views which is either from client side or server side.

Page 10 of 362
Introduction to Object Oriented Programming

Description of Services ­ We can next examine just the person providing a service, independent of the client.
We define the nature of the services that are offered, but not how those services are realized.

Interfaces ­ Interfaces are one way to describe services at this level of abstraction. Here is a simple program to
declare the interface Animal. The two methods eat() and run() are declared inside the interface.

An Implementation of an Interface ­ The Class Mammal implements the interface Animal in the below given
program and eat() method is declared inside the class.

Page 11 of 362
Introduction to Object Oriented Programming

Concern here is with the high level approach to providing the designated service.

A Method in Isolation ­ Finally, we consider the implementation of each method in isolation. This program shown
the same class Mammal implements the interface Animal and run() method is defined in this program.

Every level is important, and often you move quickly back and forth between levels.

Other Forms of Abstraction

Abstraction is used to help understand a complex system.

The abstraction idea is divided into distinct forms. In this example we shows some different forms of a motor
vehicle such as specialization, multiple views and division into parts.

Division into Parts

Encapsulation and Interchangeability

Interface and Implementation

The Service View

Composition

Division into specialization

Patterns

Division into parts : Has­a abstraction

Division into parts takes a complex system, and divides into component parts, which can then be considered in
isolation.

Characterized by sentences that have the words "has­a"
Page 12 of 362
Introduction to Object Oriented Programming

A car has­a engine, and has­a transmission

A bicycle has­a wheel

A window has­a menu bar

Allows us to drop down a level of complexity when we consider the component in isolation.

Encapsulation and Interchangeability

Encapsulation allows the programmer to group data and provide a common interface and to hide irrelevant details
from the user.

It allows two objects differing in internal representation but having the common interface interchangeably usable
(called interchangeability).

For example, a car can have different types of engine and one transmission.

Interface and Implementation

An interface describes what a system is designed to do.

It says nothing about how the assigned task is being performed.

To work, an interface is matched with an implementation that completes the abstraction.

A key step along the path to developing complex computer systems will be the division of a task into component
parts. Each component will have two faces, the interface that it shows to the outside world, and an implementation
that it uses to fulfill the requirements of the interface.

Makes it easier to understand a design at a high level.

Makes possible the interchangeability of software components.

The Service View

Each member of the community of the florist example is providing a service that is used by other members of the
group.

Another way to think of an interface is as a way of describing the service that an object provides.

The interface is a contract for the service­­if the interface is upheld, then the service will be provided as described.

Composition

Composition is one example; a form of has­a relationship;

Characterized by the following

Primitive forms

Rules for combining old values to create new values

The idea that new values can also be subject to further combination

Page 13 of 362
Introduction to Object Oriented Programming

Examples include regular expressions, type systems, windows, lots of other complex systems.

Division into specialization : Is­a abstraction

Is­a abstraction takes a complex system, and views it as an instance of a more general abstraction.

Characterized by sentences that have the words "is­a".

A car is a wheeled vehicle, which is­a means of transportation

A bicycle is­a wheeled vehicle

A pack horse is­a means of transportation

Allows us to categorize artifacts and information and make it applicable to many different situations.

Patterns

Patterns provide a common way to communicate,document and reuse abstractions.

Patterns depicts the useful relationships between objects and it helps to find out the solution of new problems.

Example pattern, Proxy:

A simple example will explain this idea of a pattern. Imagine one is developing an application that will operate over
a network.

It means that the part of the application will run on one computer, and another part will run on another computer
linked by a network connection.

Creating the actual connection between the two computers, and transmitting information along this connection, are
details that are perhaps not relevant to large portions of the application.

One way to structure these relationships is to use a type of pattern termed a proxy.

The proxy is an intermediary that hides the network connection. Objects can interact with the proxy, and not be
aware that any type of network connection is involved at all.

The proxy bundles the request as a package, transmits the package over the network, receives the response, un­
packages the response and hands it back to the client when it receives a request for data or action.

The client is completely unaware of the details of the network protocol in this fashion.

Page 14 of 362
Introduction to Object Oriented Programming

Classes and Methods

Same Ideas, Different Terms

All OOP languages have the following concepts, although the terms they use may differ:

Classes, object type, factory object

Instances, objects

Message passing, method lookup, member function invocation, method binding

Methods, member function, method function

Inheritance, subclassing

This chapter will describe the definition or creation of classes and illustrate the mechanics of declaring a class
and defining methods associated with instances of the class.

Encapsulation and Instantiation

Classes provide a number of very important capabilities:

Encapsulation ­ It is a process of binding the code and data together in to a single unit.

A Service View ­ The ability to characterize an object by the service it provides, without knowing how it
performs its task.

Instantiation ­ The ability to create an instance(i.e,object) of a class.

Example: How do you think a car runs?

Is there only steering, brake and whatever you are able to see directly?

No, there are many parts inside the car to make it run like engine, wires, tank etc. which we don′t see.

Thus we can say that car is basically a collective unit of many parts which help it to run.

Same way, in classes, we have functions and data members wrapped up/encapsulated together.

Internal and External Views

Encapsulation is used to refer the two views of the same system.

The outside, or service view, describes what an object does.

The inside, or implementation view, describes how it does it.

For example, the user would see only the description of the legal operations­say, push, pop, and top in an
abstraction of a stack data type.

On the other hand, the implementer needs to know the actual concrete data structures used to implement the
abstraction.

Page 15 of 362
Introduction to Object Oriented Programming

The concrete details are encapsulated within a more abstract framework.

Behavior and State

A class can be viewed as a combination of behavior and state.

Behavior: It means that action or work perform by an object.(For example Student attend a course
“Computer science”)

State: The state is defined by the attributes of an object.(For example Student have first name,last
name,age etc)

Class Definitions

We will use as a running example the class definition for a playing card abstraction, and show how this
appears in several languages.

Class Definition in C++

A class definition is terminated by a semicolon in C++.

Visibility modifiers (that is, public) means all the class members declared under public will be available to
everyone.

By placing the definition inside the class in C++ the programmer makes clear the link between the two data
types.

A C# Class Definition

Page 16 of 362
Introduction to Object Oriented Programming

C# class definitions have minor differences and there is no semicolon at end and visibility modifiers are applied
to methods and data fields individually.

Java Class Definition

Here is a simple java program to display the string “Hello World”.

Java also applies visibility modifiers to each item individually.

Does not have enumerated data types, uses symbolic constants instead.

Visibility Modifiers

The internal and external aspects of a class are differentiated by the terms public and private.

public means all the class members declared under public will be available to everyone. They are the
external (interface or service) view.

private features can be modified only within a class. They are the internal (implementation) view.

Typically methods are public and data fields are private, but either can be placed in either category.

Page 17 of 362
Introduction to Object Oriented Programming

static and final

static means that all instance share the same copy of the variable. One per class. Similar meaning in many
languages.

final If you make any variable as final, you cannot change the value of final variable(It will be constant). (C++
has const keyword that is similar, although not exactly the same).

public static final int COUNT= 10;

public static final float PIE = 3.14;

public static final int MAX_PRICE = 999;

public static final int MIN_PRICE = 699;

Methods

A method (or message) in object­oriented programming (OOP) is a procedure associated with an object class.
An object is made up of behavior and data.

Data is represented as properties of the object and behavior as methods.

Although syntax will differ depending upon language, all methods have the following:

A name that will be matched to a message to determine when the method should be executed.

A signature, which is the combination of return type and argument types. Methods with the same name can
be distinguished by different signatures.

A body, which is the code that will be executed when the method is invoked in response to a message.

An Example, from C#

Page 18 of 362
Introduction to Object Oriented Programming

The above given program explains about the functions of methods in C#.

We have created a new class called car and the attribute color is declared as private. Then we have declared
the constructor and method Describe() to print the value of the color. Then another class program created with
the main() function.

The we have created object for the car and through that object the Describe() method can be called to print
the appropriate color which is assigned.

Page 19 of 362
Introduction to Object Oriented Programming

Constructor

A constructor is special method of a class which will invoke automatically whenever instance or object of class
is created.

In C++, Java, C# and many other languages it has the same name as the class.

The above program shows that the Car constructor which is automatically invoked to assign the current value
of an object to the color attribute.

Accessor (or getter) Methods

An Accessor (or getter) is a method that simply returns an internal data value. Here is simple program which
returns the color value as String format.

Why to use an Accessor?

There are many reasons why an accessor is preferable to provide direct access to a data field.

The method can be declared as public.

It is used to return the value of a private field.

It makes it easier to change the access behavior (count number of accesses, whatever).

Some conventions encourage the use of a name that begins with get, (as in getRank()), but this is not
universally followed.

Setters (or mutators)

A setter (sometimes called a mutator method) is a method that is used to change the property of an
object(change or modify the value of the variable). This program shows that the method setColor() is defined
to assign the current value of the color.

Page 20 of 362
Introduction to Object Oriented Programming

Mutators are less common than accessors, but the reasons for using them are similar to accessors.

Constant or Immutable Data Fields

Some languages allow data fields to be declared as constant and it cannot be modified(const modifier in
C++, final in Java, other languages have other conventions).

Constant data fields can be declared as public, since they cannot be changed.

Separation of Definition and Implementation

In some languages (such as C++ or Object Pascal) the definition of a method can be separated from its
implementation.

They may even be in a different file:

In the above given program we have created two class one is add and another one is main.

In the add class we have declared the method add1() which accepts two parameters and performs the

Page 21 of 362
Introduction to Object Oriented Programming

addition of two values that is x and y and print the result which is stored in the variable c.

Considerations in Method Definitions

Before defining the method we need to consider few points.

Have to summarize the purpose of the method.

The naming conventions should be followed for assigning the names for the methods.

We have to decide what type of parameters and return type are used.

Interfaces in Java

An interface is like a class, but it has no implementation.

Later, another class can declare that it supports the interface, and it must provide an implementation.

In the above given program we have declared the interface Pet and method test() is declared inside the
interface.

The definition for test() method is defined in the class Dog that is main class.

We have created object for the class Pet and using Pet class object we are calling the mrthod test() which is
implemented inside the Dog class. This test method prints the output as “Interface Method Implemented”.

Properties

Properties are a way to define getters and setter methods.The below given method pointx() declared the
variable x as 0 and return the value of x.

Page 22 of 362
Introduction to Object Oriented Programming

Inner or Nested Classes

The java programming language allows you to define a class within another class is called Nested class and
the class that holds the inner class is called Outer class. The below given program shows the class
Java_inner_Class which is declared inside the class Java_Outer_Class.

Class Data Fields

A Java field is a variable inside a class.All the instances of a class can share a common data field.

A variety of mechanisms are used by different languages to implement this.

For example, suppose we wanted to keep track of how many instances of a class have been created.The
below given can be used to print the number of instances for a class. Initially we have declared the variable
count as zero. Then we are declaring the method Number_Objects() to increment the count
variable.Whenever the objects are created using new operator then the count variable is incremented.

Page 23 of 362
Introduction to Object Oriented Programming

Real World Examples

Class

Let’s say that you are going to buy a car, the showroom manager asks you some details like color, model,
engine type (Petrol/Diesel), dashboard and seat color.  

We can understand about class and objects from the above situation. The “CAR” is The class here and you
are actually getting an object of the class, it may be whatever brand with the inputs you provided to the
showroom manager. 

So whenever we need to create an object (buying a car), we need to give some details (mandatory input
ie., attribute of the class) 

Constructor:

Now you have provided the inputs needed for the car, these inputs will be processed by the manufacturing
plant(constructor) and return you with the car(object). So whenever you create an object a function called
constructor is called to create that object.

Summary

In this chapter we have examined the static, or compile time features of classes like:

The syntax used for class definition

The meaning of visibility modifiers (public and private)

The syntax used for method definition

Accessor or getter methods, and mutator or setter methods

Variations on class themes

Oberon (methods without classes)
Page 24 of 362
Introduction to Object Oriented Programming

Interfaces

Properties

Nested classes

Class data fields

Page 25 of 362
Introduction to Object Oriented Programming

Messages, Instances, and Initialization

Introduction

In the following chapter,

We will explore the mechanics of message passing.

We will investigate on creation and initialization.

Creation: Allocation of memory space for a new object and the binding of that space to a name.

Initialization : Not only the setting of initial values in the data area for the object, similar to the initialization of
fields in a record, but also the more general process of establishing the initial conditions necessary for the
manipulation of an object.

The degree to which the latter task can be hidden from clients who use an object in most object­oriented
languages is an important aspect of encapsulation and one of the principle advantages of object­oriented
techniques over other programming styles.

Message Passing Syntax

Message passing sometimes also called method lookup: The dynamic process of asking an object to perform a
specific action.

A message is always given to some object, called the receiver.

The action performed in response is determined by the receiver, different receivers can do different actions
in response to the same message.

Although the syntax may differ in different languages, all messages have three identifiable parts:

The message receiver

The message selector

An optional list of arguments

The below given example shows the message passing syntax in various languages.

Example:

Page 26 of 362
Introduction to Object Oriented Programming

Statically Typed and Dynamically Typed Languages

Languages can be divided into two groups depending upon whether they are statically or dynamically typed.

In a statically typed language, a variable is associated with a type which is known at compile time, and that
type remains unchanged throughout the execution of a program. Equivalently, the variable can only be
assigned a value which is an instance of the known/specified type.

In a dynamically typed language, a variable has no type, and its value during execution can be anything of
any shape and form.

The below given example shows that the variable num is a statically typed variable and the value 5 is
assigned to them.

Then the number variable is declared as Dynamically types variable since its value is changed due to the
Arithmetic calculations performed.

Example:

Accessing the Receiver from Within a Method

Inside a method, the receiver can be accessed by the keyword.

this is used in Java, C++, C#

self is used in Smalltalk, Objective­C, Object Pascal

current is used in Eiffel

Page 27 of 362
Introduction to Object Oriented Programming

The above given program display the id and name of the student.

The student constructor is declared to assign the value of id and student to the current object and show()
method is sued to display the id and name of the student.

Two objects have been declared and whenever the object is created the parameters are passed automatically
to the constructor once it is invoked.

Implicit Use of This

If this keyword is not defined in accessing the variable then it is implicitly assumed to refer as this.

Is assumed to be equivalent to:

Page 28 of 362
Introduction to Object Oriented Programming

The above example shows the difference between using the this operator. Two constructors declaration are
same.

Object Creation

In most programming languages objects are created dynamically using the new operator (Java, C++, C#).

The declaration simply names a variable, the new operator is needed to create the new object value.

The above figure shows the syntax used in object creation for various different languages.

creation occurs when a class name is used in the fashion of a function in Python.

Pointers and Memory Allocation

Pointers are used in all object­oriented languages in their underlying representation.

Since all object references are in fact pointers in the internal representation Java has no pointers that the
programmer can see.

Memory Recovery

Memory created using the new operator is known as heap­based memory, or just heap memory.

Objects are dynamically allocated in most languages. So, they must be recovered at run­time.

There are two broad approaches to this:

Force the programmer to explicitly use Delete operator when a value is no longer being used: Delete
sname; // C++ example.

Page 29 of 362
Introduction to Object Oriented Programming

In Java the destruction of object from memory is done automatically by the JVM is called Garbage collection.

Memory Errors

A run­time overhead is imposed by the Garbage collection systems, but prevent a number of potential memory
errors as:

Running out of memory because the programmer forgot to free values.

Using a memory value after it has been recovered

The below example shows the value is assigned to the pointer for the student class and delete operator is used
to delete the pointer object. Delete is used to free the memory allocation.

Free the same value twice

Constructors

Constructor in java is a special type of method that is used to initialize the object.Java constructor is invoked at
the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as
constructor.

In C++, Java, C# a constructor is a function with the same name as the class.

In Python constructors are all named __init__

In Delphi, Objective­C, constructors have special syntax, but can be named anything. (Naming your
constructors create is a common convention).

Page 30 of 362
Introduction to Object Oriented Programming

The above given example shows the constructor Student.this keyword is used to assign the value of the
variable for the current object.

Overloaded Constructors

Constructors are often overloaded, which means that they perform number of functions with the same name.

They are distinguished by the type signature, and the arguments used in the function call or declaration.

The below given example shows the overloaded constructors. There are two constructors one which accepts
two arguments and another one which accepts one argument. In both constructor this keyword is used to refer
the current class instance variable.

Constant Values

In Java an immutable (constant) data field is simply declared as final and can be initialized directly. In the below

Page 31 of 362
Introduction to Object Oriented Programming

given example integer speedlimit is declared as final. So the value cannot be changed. Whenever we attempt
to run the program it will shows as error.

Alternatively, a final value can be assigned in the constructor.

Immutable values in C++ are designated using the keyword const.

Difference between const and final:

The const modifier in C++ says that the associated value is truly constant, and its value cannot be changed.

The final modifier in Java only says that the associated variable will not be assigned a new value.

Destructors and Finalizers

A destructor function allows the programmer to perform certain actions at the other end of a value’s lifetime,
when the variable is about to die and have its memory recovered.

Whenever memory space for an object is released it is invoked automatically.

It does not take any arguments and is never directly invoked by the user.

Page 32 of 362
Introduction to Object Oriented Programming

The above given shows that there is a class Student declared the Student constructor and destructor is used to
delete the object.

The destructor function name is same as the class name and same syntax which is used in the constructor
declaration.

A method named finalize in Java will be which is executed before deleting any object in java.

This can occur at any time, or may never occur.

Chapter Summary

In this chapter we have examined the following topics:

Message­Passing Syntax

Statically and Dynamically Typed Languages

Accessing the Receiver from Within a Method

Object Creation

Pointers and Memory Allocation

Constructors

Constant Values

Destructors and Finalizers.

Page 33 of 362
Introduction to Object Oriented Programming

Inheritance and Substitution

Introduction

By inheritance, we mean the property that instances of a child class (or subclass) can access both data and
behavior (methods) associated with a parent class (or superclass).

In this chapter we will discuss the concepts of inheritance and substitution.

The intuitive and practical meanings of inheritance

The syntax used to describe inheritance and substitution

Some of the various forms of inheritance

The benefits and costs of inheritance

An Intuitive Description of Inheritance ­ Abstract idea of Inheritance

The idea of inheritance was motivated by us with a hierarchy of categories.

The following diagram exposes the concept of inheritance in real world.

Reasons to Use Inheritance

Page 34 of 362
Introduction to Object Oriented Programming

Basically there are two major motivations:

Inheritance as a means of code reuse. The code is not needed to be rewritten for the child class because a
child class inherit behaviour from a parent class. The amount of code needed to develop a new idea is greatly
reduced.

Inheritance as a means of concept reuse. This appears when a child class overrides behaviour defined in the
parent. Although no code is shared between parent and child, the former and latter share the definition of the
method.

Note that private aspects of the parent are part of the child, but are not accessible within the child class.

There are two common views of class hierarchies:

All classes are part of a single large class hierarchy. Thus, there is one class that is the original ancestor of all
other classes. e.g., Smalltalk, Java and Delphi Pascal.

Classes are only placed in hierarchies if they have a relationship ­ results in a forest of many small hierarchies,
but no single ancestor.  e.g., C++, Objective­C, and Apple Object Pascal.

Inheritance is both Extension and Contraction

Since the behaviour of a child class is strictly larger than the behaviour of the parent, the child is an extension of
the parent. (larger)

Since the child can override behaviour to make it fit in a specialized situation, the child is a contraction of the
parent. (smaller)

This interplay between inheritance and overriding, and extension and contraction, is what allows object­oriented
systems to take very general tools and specialize them for specific projects. This interplay is ultimately the source
of a great deal of the power of OOP.

The is­a Rule

Our idealization of inheritance is captured in a simple rule­of­thumb.

Try forming the English sentences "An A is­a B". If it "sounds right" to your ear, then A can be made a subclass
of B.

A dog is­a mammal, and therefore a dog inherits from mammal

A car is­an engine sounds wrong, and therefore inheritance is not natural. But a car has­an engine sounds
good.

Inheritance in Various Languages ­ Syntax for Inheritance in Various
languages

Languages use a variety of different syntax to indicate inheritance:

class Student : public StudentDetails ­­ c++

class Student extends StudentDetails ­­ Java

class Student : StudentDetails ­­ C#

Page 35 of 362
Introduction to Object Oriented Programming

(defclass Student (StudentDetails ) () ) ­­ CLOS

type Student = object (StudentDetails ) ­­ Object Pascal

class Student < StudentDetails ­­ Ruby

Subclass, Subtype, and Substitution

Private, Public and Protected

There are now three levels of visibility modifiers:

private: They are accessible only within the class definition (but memory is still found in the child class, just not
accessible).

public: They are accessible anywhere.

protected: They are accessible within the class definition or within the definition of child classes.

Note: Java interprets protected to mean accessible within same package 

Example:

The car class has some of its own functions like accelerate, change the gear position, apply break, start/stop
engine etc.,

These are the functions which user can access which means it has been set as Public.

There can also be some functions which car required like to know the fuel level and gear position status to start
the engine which the car itself handles on its own, so this has been set as Private.

Substitution

The following observations can be made on Substitution:

All data areas associated with the parent class must be possessed by the instances of the subclass.

Instances of the subclass must implement, through inheritance at least (if not explicitly overridden) all
functionality defined for the parent class. (They can also define new functionality, but that is unimportant for the
present argument).

Thus, the behaviour of the parent class is mimicked by the instances of the child class. It therefore seems
reasonable that a variable declared as a parent, should be able to hold a value generated from the child class.

Subclass vs Subtype

The problem with substitution is that a child class can override a method and make arbitrary changes.

It is therefore useful to define two separate concepts:

To say that A is a subclass of B merely asserts that A is formed using inheritance.

To say that A is a subtype of B asserts that A preserves the meaning of all the operations in B.

It is possible to form subclasses that are not subtypes; and (in some languages at least) form subtypes that are not

Page 36 of 362
Introduction to Object Oriented Programming

subclasses.

Overriding and Virtual Methods

Syntax for Overriding

Some languages, such as C++, require the programmer to indicate in the parent class that overriding is a potential.
The below example shows the method overriding.

Other languages, such as Object Pascal, require a modifier in the child class that overriding has taken place:

Still other languages (C#, Delphi) require indications in both parent and child. 

And some languages (Smalltalk) do not require any indication in either parent class or child class.

Interfaces and Abstract Classes

An interface is similar to a class, but does not provide any implementation.

A child class must override all methods. A middle ground is an abstract class. Here some methods are defined,
and some (abstract methods) are undefined. A child class must fill in the definition for abstract methods.

The below given shows the abstract class and getName() method is declared as abstract and it must be redefined
in the class which is inherited.

An interface is like an abstract class in which all methods are abstract. In C++ an abstract method is called a pure
virtual method.

Page 37 of 362
Introduction to Object Oriented Programming

Forms of Inheritance

The inheritance can be used in a variety of different ways and for different purposes. Many of these types of
inheritance are given their own special names.

We will explain some of these specialized forms of inheritance.

Specialization

Specification

Construction

Generalization or Extension

Limitation

Variance

Specialization Inheritance

At large the most common form of inheritance is for specialization.

A good example is that the Java hierarchy of Graphical components in the AWT:

Component

Label

Button

TextComponent

TextArea

TextField

CheckBox

ScrollBar

Each child class overrides a method inherited from the parent class in order to specialize the class in some way.

Specification Inheritance

If the parent class is abstract, we often say that it is providing a specification for the child class, and therefore it is
called the specification inheritance (a variety of specialization inheritance).

Example: Java class Shape

Inheritance for Construction

If the parent class is used as a source for behaviour, but the child class has no is­a relationship with the parent,
then we say the child class is using inheritance for construction.

Example: Subclassing the idea of a Set from an existing List class. Generally it is not a good idea, since it can
Page 38 of 362
Introduction to Object Oriented Programming

break the principle of substitutability, but nevertheless sometimes found in practice. (More often in dynamically
typed languages, such as Smalltalk).

Inheritance for Generalization or Extension

If a child class generalizes or extends the parent class by providing more functionality, but does not override any
method, we call it inheritance for generalization.

The child class doesn′t change anything inherited from the parent, it simply adds new features.

Example: Java Properties inheriting form Hashtable.

Inheritance for Limitation

If a child class overrides a method inherited from the parent in a way that makes it unusable (for example, issues
an error message), then we call it inheritance for limitation.

Example: An existing List data type that allows items to be inserted at either end, or you override methods allowing
insertion at one end in order to create a Stack. Generally not a good idea, since it breaks the idea of substitution.
But again, it is sometimes found in practice.

Inheritance for Variance

Two or more classes that seem to be related, but it′s not clear who is the parent and who is the child. Better
solution is to abstract out common parts to new parent class, and use subclassing for specialization.

Example: Mouse and TouchPad and JoyStick

Summary of Forms of Inheritance

Specialization ­ The child class is a special case of the parent class; in other words, the child class is a subtype of
the parent class.

Specification ­ The parent class defines behaviour that is implemented in the child class but not in the parent class.

Construction ­ The child class makes use of the behaviour provided by the parent class, but is not a subtype of the
parent class.

Generalization ­ The child class modifies or overrides some of the methods of the parent class.

Extension ­ The child class adds new functionality to the parent class, but does not change any inherited
behaviour.

Limitation ­ The child class restricts the use of some of the behaviour inherited from the parent class.

Variance ­ The child class and parent class are variants of each other, and the class­subclass relationship is
arbitrary.

Combination ­ The child class inherits features from more than one parent class. This is multiple inheritance and
will be the subject of a later chapter.

The Benefits of Inheritance

The following are some of the benefits of inheritance.

Page 39 of 362
Introduction to Object Oriented Programming

Software Reuse

Code Sharing

Improved Reliability

Consistency of Interface

Rapid Prototyping

Polymorphism

Information Hiding

The Costs of Inheritance

Although the benefits of inheritance in object­oriented programming are great, almost nothing is without cost of one
sort or another.

For this reason, we must consider the cost of object­oriented programming techniques, and in particular the cost of
inheritance.

Execution speed : It is seldom possible for general­purpose software tools to be as fast as carefully hand­
crafted systems. Thus, inherited methods, which must deal with arbitrary subclasses, are often slower than
specialized code.

Program size : The use of any software library frequently imposes a size penalty not imposed by systems
constructed for a specific project.

Message Passing Overhead : It is a fact that message passing is by nature a more costly operation than simple
procedure invocation.

Program Complexity : Although object­oriented programming is often touted as a solution to software
complexity, in fact, overuse of inheritance can often simply replace one form of complexity with another.

This does not mean you should not use inheritance, but rather than you must understand the benefits, and weigh
the benefits against the costs.

Example

Inheritance is a process of object reusability.

The below given program explains the concept of inheritance. There are two class one is parent class and another
one is child class.

The mthod p1() is declared in the Parent class and method c1() is declared in the child class. The child class can
inherit the features of Parent class through extends keyword. An object has been created for the child class to
access both parent and child class methods.

Page 40 of 362
Introduction to Object Oriented Programming

Chapter Summary

Topics we have addressed have included the following:

The meaning of inheritance

Inheritance in Various Languages

Subclass, Subtype, and Substitution

Overriding

Interfaces and Abstract Classes

The various forms of inheritance

The cost and benefits of inheritance

Page 41 of 362
Introduction to Object Oriented Programming

Static and Dynamic Behavior

What do the terms Static and Dynamic Mean?

In Programming languages:

Static almost always means fixed or bound at compile time, and cannot thereafter cannot be changed.

Dynamic almost always means not fixed or bound until run time, and therefore can change during the
course of execution.

In this chapter we will review examine how differences in static and dynamic features effect object­oriented
programming languages.

Static versus Dynamic Typing

Static and Dynamic Classes in Statically Typed Languages

Static and Dynamic Method Binding in Statically Typed Languages

Static and Dynamic Typing

Java or Pascal is known as a statically typed programming .Here, for instance, variables have declared type
which is fixed at compile time.

A variable is merely a name in a Smalltalk or CLOS which is nothing but dynamically typed programming
language. Generally types are associated with values whereas variables are not connected to types. Various
types can be held by variables during the course of execution.

Advantages and Disadvantages

Pros and cons of Argument:

Static typing authorise a great error reduction, more work at compile time and results in faster execution
time.

Dynamic typing leads to greater flexibility, easier to write which come out as non declarative statements.

Both arguments have some empirical and thus both types will survive as languages in the upcoming future.

The Polymorphic Variable

A polymorphic variable is a variable which can possess various types of values during the course of
execution.  

The annex of object­oriented ideas in a statically typed language can strengthen a new twist.

Recall the argument for substitution­ an instance of a child class should be vouchsafed to be assigned to a
variable of the parent class.The below declaration shows the legal variable declaration.

Page 42 of 362
Introduction to Object Oriented Programming

Static and Dynamic Class

The class of the declaration is the static class for the variable in a statically typed languages while the class of
the value is the dynamic class.

Many of the statically typed OO languages obligate the dynamic class to be a child class of the static class.

Importance of Static Class

The legality of a message conveyed is determined at compile time based on the static class in a statically
typed object­oriented language.

A message can bring out a compile error. Though there is no run­time, error could possibly arise. In the below
given example we have created object for the Parent class and if we try to call the method it will generate an
error.

Reverse Polymorphism

Sometimes it is mandatory to undo the assignment to a polymorphic variable. That is, to determine the

Page 43 of 362
Introduction to Object Oriented Programming

variables true to dynamic value, and assigns it to a variable of the appropriate type.

This process is coined as down casting, or reverse polymorphism due to its undoing polymorphic assignments.

In the above given program the two class Dog and Cat extends Mammal(ie,Parent class). In this example the
object fido belongs to the Dog can be assigned to the parent class object pet. But it is not legal to assign the
parent class object to the child class object.

Two components of reverse polymorphism

There are two specific problems associated with the question of reverse polymorphism.

The problem of identity ­ If the value declared as an instance of a parent class actually holds a value from a
subclass.

The task of assignment ­ If the value from the parent class is assigned to a variable declared as the
subclass.

In some languages mechanisms are provided to address these two problems together, while in other
languages they are separated.

Static and Dynamic Method Binding

The question is whether the binding for information be associated with the static class of a variable or the
dynamic class.

Alice holds a small Mammal. Bill asks, “Does this animal give birth to live young one?"

Static answer ­ All mammals give birth to a live young one and therefore yes.

What if the Mammal is a platypus? Dynamic answer ­ Platypus lays eggs and therefore no.

Even statically typed OOP languages can use dynamic binding. But static type is used to determine legality of
operation.

Documenting Method Binding

Dynamic binding is the default in many languages. The act of a child class overriding a method in the parent,
using the same type signature, then the selected method will be determined by the dynamic type.
Page 44 of 362
Introduction to Object Oriented Programming

In other languages (C++, Delphi, C#) the programmer must indicate which methods are dynamically bound
and which are statically type. In C#, for example, this is done using the virtual keyword.

The below given example shows the method binding. The Animal is the parent class and Dog and Bird are the
child classes. These two classes extends the Parent class Animal. The virtual method speak() is used in the
parent class. This method is overrided in the child class Dog.

Merits of Static versus Dynamic Method Binding

Efficiency – in static binding program execution takes only less time to complete but dynamic binding requires
more time.

Error detection ­ static binding permits errors to be caught at compile time rather than run­time.

Flexibility ­ dynamic binding permits greater flexibility whereas static binding creates rigidity and inhibits reuse.

Chapter Summary

A statically typed language associates the types with variables on the other hand a dynamically typed
language associates the types with values.

Static typing facilitates better error detection, better run­time efficiency, and less flexibility.

An object variable can still hold values from a child class in a statically typed OO language.

The static class is the class of the declaration but the dynamic class is the class of the value held currently.

The static class is used to check the legality of a message.

Using either the static or dynamic class a message can be bound to a method. Dynamic class is used by the
most languages. The programme is allowed to choose method to be used in some languages.

Page 45 of 362
Introduction to Object Oriented Programming

Multiple Inheritance

Introduction

Multiple Inheritance means the Inheritance is implemented from more than one parent class.

In this chapter we will discuss the following topics.

Inheritance as Categorization

Problems Arising from Multiple Inheritance

Inner Classes.

Inheritance as Categorization

To define the process of inheritance it is a form of categorization.  e.g., A TextWindow is a type of Window, so
class TextWindow inherits from class Window.

Most of the objects can be categorised by variety of ways in the real world. e.g., The author of the textbook
can be categorised as,

North American

Male

Professor

Parent

They are entirely different from each other as these are not proper subsets of the other, so single rooted
inheritance hierarchy cannot be made out of them.

Inheritance as Combination

Real world objects are the combinations of features from different classification schemes. Each category gives
some new insight into the whole.

Author is North American, and

Author is Male, and

Author is a Professor, and

Author is a Parent.

Note that we have not lost the is­a relationship; it still applies in each case.

An Example ­ Incomparable Complex Numbers

If we have class complex, which represents the complex number abstraction, it is advisable to make the
complex class into a subclass of Number.

Page 46 of 362
Introduction to Object Oriented Programming

Complex numbers have the following:

The two abstract classifications are:

Magnitude ­ things that can be compared with each other.

Number ­ things that can perform arithmetic

The three specific classifications with constrains are :

Integer ­ comparable and arithmetic

Char ­ comparable but not arithmetic

Complex ­ arithmetic but not comparable

The difficulty is that comparison between 2 complex numbers is ambiguous. i.e., complex numbers are
immeasurable.

Possible Solutions

Create the subclass Number for Magnitude class but comparison operators in class complex to give error
message must be redefined if used. (subclassing for limitation).

Avoid using inheritance ­ redefine all operators in all classes. (flattening the inheritance tree).

Use part inheritance, but simulate others ­ use Number, but have each number implement all relational
operators.

Number and Magnitude must be independent and it can have Integer inherited from both the class. (multiple
inheritance).

Another Example ­ Walking Menus

A Menu is the set of options presented to the user.

A Menu maintains a collection of Menu Items.

Each Menu Item knows how to respond when selected.

A cascading menu is both a Menu Item and a Menu.

Problem with Multiple Inheritance ­ Name Ambiguity

The most common difficulty arising from the use of multiple inheritance is that names can be used to mean
more than one operation.

Page 47 of 362
Introduction to Object Oriented Programming

Example:

Car extends Vehicle,Truck extends Vehicle and assume Driver can extend both Car and Truck what would be
the Problem.

Consider both car,truck has a same method driveVehicle.

Now if Driver Class wants to drive it gets confused whether to driveVehicle of Car or Truck.

One Solution: Redefinition

One solution is there to redefine one or the other operation in the child class. The below given example shows
the multiple inheritance concept. In here the class Driver extends two class Car and Truck. The driveVehicle()
method is defined as virtual.

Problem with Redefinition Solution

However, the redefinition solution is not without cost.

Now what happens when we run up against the principle of substitution?

Page 48 of 362
Introduction to Object Oriented Programming

This problem can be mitigated, but the solution is complex and not perfect.

Other Approaches to Name Ambiguity

The Other programming languages use different approaches to solve the problem of ambiguous names.

Eiffel uses the ability to rename features from the parent class. A polymorphic variable accessing through
the parents name will access the renamed feature in the child.

CLOS and Python resolve ambiguous names by the order in which the parent classes are listed. The first
occurrence of the name found in a systematic search is the one selected.

Multiple Inheritance of Interfaces

Multiple inheritance of interfaces does not present the same problem of name ambiguity as does multiple
inheritance of classes.

Either the ambiguous methods in the parent classes have different type signatures, in which case there is
no problem, or

The ambiguous methods in the parent classes have the same signature. Still there is no problem, since
what is inherited is only a specification, not an implementation.

This is why Java permits multiple inheritance of interfaces, not of classes.

Nevertheless, C# does not permit the same method name to be inherited from two parent interfaces.

Inheritance from Common Ancestors

Another problem with Multiple Inheritance occurs when parent classes have a common root ancestor. Does
the new object have one or two instances of the ancestor?

Page 49 of 362
Introduction to Object Oriented Programming

Data Field in Common Ancestor

Let us assume that the common ancestor declares a data member. Should the child class have one copy of
this data field, or two?

Both answers can be justified with examples.

C++ has implemented this concept using the virtual parent class. If your parent is virtual there is one copy, and
if not there are two.

Inner Classes

The ability to extend classes in C++ and Java provides a mechanism that is nearly equivalent to multiple
inheritance, without the semantic problems. The below example shows the inner class InnerChild which is
declare inside another class Child. These two classes extends the parent class named as ParentOne

You can access methods from both parent classes within the inner class. This idiom is used a lot in Java. It
solves many problems that would otherwise be addressed using Multiple Inheritance. It is not exactly
equivalent to Multiple Inheritance, but very close.

Chapter Summary

Inheritance as Categorization

Problems Arising from Multiple Inheritance

Page 50 of 362
Introduction to Object Oriented Programming

Inner Classes.

Page 51 of 362
Introduction to Object Oriented Programming

Polymorphism and Software Reuse

Definition of Polymorphic

Polymorphous: Having multiple forms, characters, or styles.

From Greek language ‘poly’ means many, and ‘Morphos’ means form (Morphus was the Greek god of sleep,
who could assume many forms, and from which we derive the name Morphine, among other things).

In programming languages it is used for a variety of different mechanisms. 

Major Forms of Polymorphism in Object Oriented Languages

There are four major forms of polymorphism in object­oriented languages:

Overloading (ad hoc polymorphism) – A single name that refers to two or more different implementations.

Overriding (inclusion polymorphism) ­ A child class redefining a method inherited from a parent class.

The Polymorphic Variable (assignment polymorphism) ­­ A variable holding different types of values during
the course of execution. It is called Pure Polymorphism when a polymorphic variable is used as a
parameter.

Generics (or Templates) ­ A way of creating general tools or classes by parameterizing on types.

Two Approaches to Software Reuse

One of the major goals of OOP is software reuse.

We can illustrate this by considering two different approaches to reuse:

Inheritance ­­ The ‘is­a’ relationship.

Composition ­­ The ‘has­a’ relationship.

We do this by considering an example problem that could use either mechanism.

Example ­ Using Inheritance

Page 52 of 362
Introduction to Object Oriented Programming

In the above example, class Person is a base class and classes MathsTeacher and Footballer are the derived
from Person.

The derived class appears with the declaration of a class followed by a colon, the keyword public and the
name of base class from which it is derived.

Since, MathsTeacher and Footballer are derived from Person, all data member and member function of
Person can be accessible from them.

Using Composition

The below example program shows the concept of Composition. There is a parent class Car and other two
classes named as Maruti and Engine.

The relationship between class Car, Maruti and Engine states that Maruti is a car and Maruti has a Engine.

Class car has general information such as Car details and its color. The class Maruti extends the class Car
and inherit all its features. It also define specific functionality.

Page 53 of 362
Introduction to Object Oriented Programming

Advantages and Disadvantages of Each Mechanism

Composition is simple and clear which indicates what operations are provided.

Inheritance makes shorter code, possibly increased functionality, but makes it more difficult to understand
what behaviour is being provided.

Inheritance may open the door for unintended usage, by the means of unintended inheritance of behaviour.

Underlying details using composition are easier to change (i.e., change the data representation).

Polymorphism may be permitted by inheritance.

Very small execution time is the advantage for inheritance.

Efficiency and Polymorphism

Programming with polymorphism always involves compromises between ease of development and use,
readability, and efficiency.

In this the efficiency has been considered and dismissed.

The advantages of rapid development and consistent behaviour and the possibilities of code reuse overcome
the small losses in efficiency.

Will Widespread Software Reuse Become Reality?

Even though there are right mechanisms, there is no guarantee of the reuse of software to occur.

The following are some of the reasons for this:

Inheritance and composition provide the means for producing reusable components, but they do not
provide guidelines for how such a task should be performed.

Page 54 of 362
Introduction to Object Oriented Programming

Producing reusable components is difficult. The benefits cannot usually be realized within a single project.

The benefits of developing reusable components do not immediately improve a project, there is usually little
incentive for programmers to strive toward reusability.

Each new problem typically requires a slightly different set of behaviours, it is often difficult to design a true
useful and general purpose software component at the first time.

Many programmers and managers are leery of software that has not been developed in­house.

Many programmers have little formal training or have not kept pace with recent programming innovations,
to be aware of mechanisms for reusable software components.

Chapter Summary

Polymorphism in Programming Languages

Mechanisms for Software Reuse

Efficiency and Polymorphism

Will Widespread Software Reuse Become Reality?

Page 55 of 362
Introduction to Object Oriented Programming

Overloading and Overriding

A Definition of Overloading

We use the term overloaded if it has two or more meanings.

Most words in natural languages are overloaded, and ambiguity is resolved by means of context.

Same is the case of OO languages.

Overloaded names can be resolved by two important classes of context.

Overloading based on Scopes

Overloading based on Type Signatures

Overloading Based on Scopes

A term scope defines the portion of a program in which a name can be used, or the way it can be used.

Scopes are introduced using lots of different mechanisms:

Classes or interfaces

Packages or Units

Procedures or Functions

in some languages, even Blocks

An advantage of scopes is that the same name can appear in two or more scopes with no ambiguity.

Florist Example:

The above diagram explains about the Overloading concept and sendFlowersTo() method is overloaded between
the two classes.

Resolving Overloaded Names

By looking at the type of the receiver this type of overloading is resolved.

Allows the same name to be used in unrelated classes.

Since names need not be distinct they are allowed to be short, easy to remember, meaningful too.

Page 56 of 362
Introduction to Object Oriented Programming

Overloading Based on Type Signatures

A different type of overloading allows multiple implementations in the same scope to be resolved using type
signatures.

The below given example different overloaded methods. The sum() is the method overloaded in the class
Example. The first method pass one argument,second method pass two arguments and like wise third method
pass three arguments.

A combination of argument type and return type is called a type signature. By looking at the signature of a call, one
can tell which version is intended.

Resolution Performed at Compile Time

Note that resolution is almost always performed at compile time, based on static types, and not dynamic values.

Page 57 of 362
Introduction to Object Oriented Programming

The above given example shows the compile time polymorphism. There are two class class B and class A. Class B
is the child class and Class A is the parent class. These two classes overloaded the method M()with different
arguments.

In the class Example the two objects are created one is for Parent class and another one is for child class. The
respective methods can be called based on the object.

Substitution as Conversion

Resolving overloaded function or method calls can get very complex, When one adds conversions into the mix.

There are many types of conversions:

Implicit value changing conversion (such as integer to real)

Implicit conversion that does not change value (pointer to child class converted into pointer to parent)

Explicit conversions (casts)

Conversion operators (C++ and the like)

Redefinitions

A redefinition occurs when the type signature of a method in the parent class is changed by the child class. 

Page 58 of 362
Introduction to Object Oriented Programming

Two different types of rules are used to resolve name:

The merge model. The scope of the child is merged with the scope of the parent.

The hierarchical model. Scopes are separate. Search is made for first scope containing name, then for best fit
within the scope.

Example Illustrating Redefinition Models

The following example will highlight the difference in these two models. The below given example explains about
the overloading concept and it execute the parent method. First it will print the parent method and then it will print
the child class method.

It will execute parent method in Java and C# (Merge model) and give error in C++ (hierarchical model). Delphi
allows programmer control over this.

Optional Parameters

Some languages allow the programmer to create optional parameters, usually only at the end of the parameter list.

Page 59 of 362
Introduction to Object Oriented Programming

Such a program will have more than one type signature.

In the above class Rectangle areaRect is the method defined. This methos has two required parameter and one
optional parameter. The object has been created for the Rectangle class and it call the areaRect method by
passing two values.

After passing the required values the area has been calculated and it will be printed.

Overriding

If two methods have the same name and type signature, a method in a child class overrides a method in a parent
class.

Like overloading, there are two distinct methods with the same name.

The following are the differences:

Overriding only occurs in the context of the parent­child relationship.

Using the type signature.

Sometimes Overridden methods are combined together.

Overriding is done at run­time, not at compile time.

Notating Overriding

When a method with the same name and type signature is redefined by a child class naturally it comes as an
output of overriding particularly in some languages (Smalltalk, Java).

Overriding occurs only, if the parent class has declared the method in some special way (ex: keyword virtual) in
language like C++.

Overriding takes place if the child class declares the method in some special way (Ex: keyword override) in some
languages specially in Object Pascal.

In some languages (C#, Delphi) overriding occurs if both the parent and the child class declare the method in
some special way.

In the below given the method is declared as virtual in the Parent class and override method is declared in the
Child class with same type signature.

Replacement and Refinement

Page 60 of 362
Introduction to Object Oriented Programming

Two different ways to handle overriding:

The code in the parent class is replaced by the code in the child class with the help of replacement.

A refinement manipulates the code in the parent class, and adds it to the code in the child class.

Almost all the languages use both types of semantics in different situations. For example Constructors frequently
use refinement.

Reasons to use Replacement

Below given are the reasons for replacement of methods:

The method in the parent class is abstract and it must be replaced.

The method in the parent class is a default method so it is not appropriate for all situations.

The method in the parent can be more efficiently executed in the child.

We will give examples of the latter two.

Overriding a Default Method

The below shown is an example of overriding a default method in Smalltalk. Class Number incubes child classes
Integer, Fraction and Float. Method in class Number is defined as follow as:

The method in class Float ought to perform something different, here it is computing the square root. The parent
class method works a lot than the child classes.

Overriding for Optimization

The following given example can show how a child class can do the same action more efficiently and effectively
than the parent class. Class Boolean has child classes True and False.

Page 61 of 362
Introduction to Object Oriented Programming

These general algorithms do work for either true or false values.

More Efficient Versions in class True

In class True we can be very clear that the left argument is true, hence it can make more efficient algorithms.

The same efficient code can be in class False. Though these are faster than the code in the parent class, they
have the same effect.

Downside of Replacement

The down side of replacement semantics is that there is no assurance that the child class has no meaning equal to
the parent class.

For example, a child class could reframe sqrt to compute the cube root of its argument.

This leads to the difference between subclasses and subtypes.

A reframing is more difficult, since whatever the parent does is inherited to be part of the child. This is the reason
for most languages use refinement semantics for constructors.

Refinement in Beta

Beta is interesting that it always uses refinement.

The parent method is always executed first if it executes the special Inner statement.

Meanwhile the child method is also executed. The child class can in turn do an inner, and so on arbitrarily.

If a class has no child, the inner statement has no effect at all.

Page 62 of 362
Introduction to Object Oriented Programming

Simulating Refinement with Replacement

Despite language usage replacement, the most important features of a refinement can be simulated.

The above given program shows the example() method is overrided.super keyword is used to call the parent class
method.

Note that this is not quite the same as Beta, as here the child wraps around the parent, while in Beta the parent
wraps around the child.

Constructors use Refinement

Most languages have constructors which will always use refinement.

This assures that whatever initialization the parent class performs will always be updated and accepted as part of
the initialization in the child class.

Overriding versus Shadowing

In programming languages it is not uncommon for one declaration of a variable to shadow a previous variable of
the same name.

In the below given program the x is the instance variable declared as private and in the example method another x
variable is declared as argument and it shadows the instance variable x which is declared already as private.

Page 63 of 362
Introduction to Object Oriented Programming

One can resolve Shadowing at compile time. It does not demand any run­time search.

Shadowing of Instance Variables in Java

Java allows instance variables to be redefined and uses shadowing. In the below given program the variable x is
used both Parent class and Child class.The respective variable can be called using respective object.

That is if you want to print parent class variable we have to use parent class object likewise if you want to print the
Child class object so we need to use the child class object.

Shadowing Methods

Most languages require the virtual keyword in the parent class. If it is omitted, it will use shadowing.

The below example shown the shadowing the methods which is declared in both Parent class and Child class. The
methods can be called through Parent class an Child class objects.

Page 64 of 362
Introduction to Object Oriented Programming

Deferred Methods

If in the parent class when the method is defined but not implemented, we can say that the method is deferred.
They are sometimes called abstract methods and in C++ otherwise pure virtual method.

Overriding, Shadowing and Redefinition

Covariance and Contra variance

When a method is overridden, we could alter the argument types or return types.

Covariant means making a change down the inheritance hierarchy and making it more specific whereas change
that moves up the inheritance hierarchy is said to be contra variant.

The below example shows the Contravariance used in the classes.

Page 65 of 362
Introduction to Object Oriented Programming

In applying this idea leads to trouble with the principle of substitution.

Chapter Summary

An override occurs when a method in the child classes uses the same name and type signature as a method in the
parent class.

Unlike overloading, overriding is resolved at run­time.

There are two possible means for an overriding, replacement and refinement.

A name can shadow another name. Some languages permit both shadowing and overriding. Shadowing is
resolved at compile time.

A change in the type signature can be covariant or contravariant, if it moves down or up the type hierarchy. The
semantics of both types of change can be subtle.

Page 66 of 362
Introduction to Object Oriented Programming

Assignments

Explain the following OOPS concepts using a common real world example:

Abstraction

Encapsulation

Inheritance

Polymorphism

Provide a sample program in Java if possible.

Answer: Let’s take the example of a mobile phone to illustrate the concepts of oops.

Object

When we take a mobile as an object. The purpose of its invention was Calling, Receiving a call & Messaging.
But today we have thousands of new features which are inbuilt. There are so many models available in the
market. Number of the feature is still increasing.

The above shown diagram vividly shows that each brand (Samsung, Nokia, IPhone) have their own list of
features along with basic functionality of dialing, receiving a call & messaging.  

Object is termed as Any real world entity which has some characteristics or does some performance. This
object is also called as an instance i.e. ­ a copy of entity in programming language.

When we take the above stated example, manufacturing of mobiles in a company is numerous for each model
which are actually an instance. This object is differentiated from each other via some identity or its
characteristics. This characteristic is given some unique name.

Mobile mbl1 = new Mobile ();  

Mobile mbl2 = new Mobile (); 

Class
Page 67 of 362
Introduction to Object Oriented Programming

A Class is a contemplation of the object. It describes the object well. We call it as a blue print of an object. It
portrays how the object has to be represented. Class consists of name,attributes & operations.

In our example, A Mobile can be a class which has some attributes like Profile Type, IMEI Number, Processor,
and some more.) & operations like Dial, Receive & SendMessage. It is represented as shown below. 

It is represented as shown below. 

Program:

Page 68 of 362
Introduction to Object Oriented Programming

Abstraction

Abstraction reveals only relevant details and conceal the remaining.

Ex: We take any mobile like Nokia, Samsung, IPhone. 

Important aspects of mobile phones

Some internal method concatenates the numbers and displays together on screen While dialling a number.
The ambiguity lies here that the person doesn’t know what and how it takes place internally.

Once a person clicks on the green button, it means sending signals to the person’s mobile which is
intended to be called but we are not aware of how it works in such a way.

This is known as abstraction where a method takes some parameter as input & returns some result after some
logic execution without indicating what is written within the method.

Program:

Page 69 of 362
Introduction to Object Oriented Programming

Encapsulation

Encapsulation is defined as the process of enclosing one or more details from outside world through access
right. It says how much access should be given to particular details.

Both Abstraction & Encapsulation work hand in hand because Abstraction says what details to be made visible
& Encapsulation provides the level of access right to that visible details. i.e. – It implements the desired level of
abstraction.

Taking consideration of Bluetooth, When we switch on the Bluetooth, we can connect to another mobile but not
able to access the same. Features like dialing a number, accessing inbox etc. This is because, Bluetooth
feature is given some level of abstraction. 

When mobile A is connected with mobile B via Bluetooth whereas mobile B has been already connected to
mobile C then A is not allowed to connect C via B. This is because of accessibility restriction. Regarding this,
access specifier like public, private, protected, and internal handle it carefully.

Program:

Polymorphism

The ability of doing the same operation with different type of input can be termed as Polymorphism.

To be precise it is “many forms of single entity”. This plays an important role in the concept of OOPS.

Let’s form a hypothesis that a Samsung mobile has a 5MP camera i.e. – it has a functionality of Camera
Click().

Now the same mobile is equipped with Panorama mode in camera. Functionality would be the same but with
different mode. This is coined as Static polymorphism or Compile time polymorphism.

In Compile time polymorphism, the compiler is aware of which overloaded method is going to make a call.

Compiler checks the type and number of parameters passed to the method and decides which method to call.
It indicates an error if there is no method which go hand with the method signature of the method. It is called
as compile time.

Next, in SendMessage had the purpose of sending message to single person at a time. But if Nokia had given

Page 70 of 362
Introduction to Object Oriented Programming

provision for sending message to a group at a time, the purpose of sending to many can be solved in a single
time. i.e. ­ Overriding the functionality to send message to a group. This type is called Dynamic polymorphism
or Runtime polymorphism.

For overriding the method demands settings. Then it can be overridden to virtual & its new implementation has
to be embellished with override keyword.

Runtime polymorphisms helpful in pointing at any derived class from the object of the base class at runtime
that shows the ability of runtime binding.

Program: Compile time polymorphism

Program: Runtime polymorphism

Page 71 of 362
Introduction to Object Oriented Programming

Inheritance

Inheritance is known as the ability to extend the functionality of same group from base entity to new entity
same group. Inheritance will lead us to reuse the functionality which we have already explained. 

There are 5 types of inheritance which are listed as below:

Single level inheritance

Multi­level inheritance

Hierarchical inheritance

Hybrid inheritance

Multiple inheritance

Single level inheritance: There is one base class and a single derived class.i.e ­ Samsung broadens its base
mobile features.

Multilevel inheritance: The name itself suggests that it is more than one single level of derivation which besides
and beyond base, features are extended by Samsung brand. Recently Samsung has manufactured its new

Page 72 of 362
Introduction to Object Oriented Programming

model with new added features or advanced OS like Android OS, v4.4.2 (kitkat).Hence it is assign that it
travels from generalization to more specification.

Hierarchical inheritance: Multiple derived classes expand from base class. It’s like single level inheritance but
along with Samsung Nokia also takes part in inheritance.

Hybrid inheritance: Single, Multilevel, & hierarchal inheritance construct a hybrid inheritance.

Program:

Page 73 of 362
Introduction to Object Oriented Programming

Interface

Where derived class will extend from multiple base classes is known as Multiple inheritance.

If Samsung follows the functions of multiple Phone (Mobile & Telephone), this would result in a complete mess
for complier to grasp which function to be called when any event in mobile is triggered like Dial () where Dial is
available in both the Phone i.e. ­ (Mobile & Telephone). To avoid this confusion C# came with the concept of
interface which is different from multiple inheritance actually.

An interface is exactly same like a class in declaration of properties, methods, delegates & events but it is not
the same in its implementation.

Interface executes the class to have a standard contract to issue all implementation to the interface members. 

Then what is the use of interface without implementation? They are useful to have readymade contracts. we
have to implement functionality over this contract. 

In our example, Dial would remain Dial in case of Mobile or Telephone. It won’ t be correct once we use
different name when its task is intended to Call the person. Interface can be depicted with the keyword
‘interface’. The basic rule of interface is that all properties and methods within the interface ought to be
implemented unless it is not been used.

Page 74 of 362
Introduction to Object Oriented Programming

Program:

Page 75 of 362
Unit - 2
Introduction to Java
Programming Language

Page 76 of 362
Introduction to Java programming Language

An Introduction to Java

We will discuss the following topics in this chapter:

Java As a Programming Platform

The Java “White Paper” Buzzwords

Simple

Object­Oriented

Network­Savvy

Robust

Secure

Architecture­Neutral

PortableInterpreted

High­Performance

Multithreaded Dynamic

Java and the Internet

Short History of Java

Common Misconceptions about Java

Java as a Programming Platform

Java is a complete platform, with a big library, containing lots of reusable code, and an execution environment
providing services such as security, portability across operating systems, and automatic garbage collection.

As a programmer, one needs a language like Java with a pleasant syntax and comprehensible semantics (i.e., not
C++).

There are some languages giving you portability and garbage collection, but they don’t have much of a library,
forcing you to roll on your own if you want fancy graphics or networking or database access.

Java has everything—a good language, a high­quality execution environment, and a vast library.

The Java "White Paper" Buzzwords

The following are the Java "White Paper" Buzzwords.

Simple :

Java is designed as closely to C++ as possible in order to make the system more comprehensible.

Java omits many rarely used, poorly comprehended and puzzling features of C++ those, in our experience,
bring more grief than benefit.
Page 77 of 362
Introduction to Java programming Language

The syntax for Java is a cleaned­up version of the syntax for C++ indeed.

However, the designers did not, try to fix all the clumsy features of C++.

For instance, the syntax of the switch statement remain same in Java.

To enable the construction of software that can run stand­alone in small machines is one of the goals of Java.

Object­Oriented:

A technique for programming that focuses on the data(i.e., objects) and on the interfaces to that object is
called the object­oriented design.

The object­oriented facilities of Java are essentially those of C++.

The major difference between Java and C++ lies in multiple inheritance, which Java has replaced with the
simpler concept of interfaces, and in the Java metaclass model.

Network­Savvy:

Java has an extensive library of routines for managing with TCP/IP protocols like HTTP and FTP.

Java applications can open and access objects across the Net via URLs with the same ease as when
accessing a local file system.

Communication between distributed objects is enabled by the remote method invocation mechanism.

Robust:

Java is meant for writing programs that must be loyal in a variety of ways.

Java puts a lot of priority on early checking for possible problems, later dynamic (runtime) checking, and
eliminating situations that are error­prone.

The single biggest difference between Java and C/C++ is that Java has a pointer model that eliminates the
possibility of overwriting memory and corrupting data which the latter doesn’t have.

Secure:

Java is aimed to be used in networked/distributed environments.

Java allows the construction of virus­free and tamper free systems.

Java was invented to make certain kinds of attacks impossible, few among them are:

Overrunning the runtime stack—a common attack of worms and viruses.

Corrupting memory outside its own process space.

Reading or writing files without permission.

Architecture­Neutral:

The compiler makes an architecture­neutral object file format—the compiled code is executable on many
processors, given the presence of the Java runtime system.

Page 78 of 362
Introduction to Java programming Language

The Java compiler does this by generating byte­code instructions which are designed to be both easy to interpret
on any machine and easily translated into native machine code on the fly.

Security is increased by Java’s virtual machine because it can check the behaviour of instruction sequences.

Portable:

There are no “implementation­dependent” aspects of the specification unlike C and C++.

The sizes of the primitive data types are defined, as in the behaviour of arithmetic on them.

The libraries that are a part of the system define portable interfaces. For example, there is an abstract Window
class and implementations of it for UNIX, Windows, and the Macintosh.

Interpreted:

The Java interpreter can execute Java byte­codes directly on any machine to which the interpreter has been
ported.

Since linking is a more incremental and lightweight process, the development process can be much more rapid
and exploratory.

High­Performance:

There are situations where higher performance is required while the performance of interpreted byte­codes is
usually more than adequate.

The just­in­time compilers have become so good that they are competitive with traditional compilers and, in
some cases, even outperform them because they have more information available.

For example, a just­in­time compiler can monitor which code is executed frequently and optimize just that code
for speed. A more sophisticated optimization is the elimination of function calls.

Multithreaded:

Better interactive responsiveness and real­time behaviour are the benefits of multithreading.

Threads in Java can take advantage of multiprocessor systems if the base operating system does so.

With regards to thread implementations Java is not platform­independent.

Java offloads the implementation of multithreading to the underlying operating system or a thread library.

The ease of multithreading is one of the main reasons why Java is such a popular language for server­side
development.

Dynamic:

Java is a more dynamic language than C or C++. It was framed to adapt to an evolving environment.

Without any effect on their clients libraries can freely add new methods and instance variables.

Finding out runtime type information is straightforward in Java.

This is extremely useful for systems that need to analyse objects at runtime, such as Java GUI builders, smart

Page 79 of 362
Introduction to Java programming Language

debuggers, pluggable components, and object databases.

Java and the Internet

Applets are the Java programs that work on web pages.

You need a Java­enabled web browser, which will execute the byte­codes for you to use an applet.

Inserting an applet into a web page works much like embedding an image. It reacts to user commands, changes
its appearance, and exchanges data between the computer presenting the applet and the computer serving it.

Today, most web pages simply use JavaScript or Flash when dynamic effects are desired in the browser.

Java, on the other hand, it has become the most popular language for developing the server­side applications that
produce web pages and carry out the backend logic.

Above Figure shows a good example of a dynamic web page that carries out sophisticated calculations. The Jmol
applet displays molecular structures. By using the mouse, you can rotate and zoom each molecule to better
understand its structure.

A Short History of Java

1991:

A group of Sun engineers, led by Patrick Naughton and James Gosling wanted to design a small computer
language that could be used for consumer devices like cable TV switchboxes. The language had to be small
and generate very tight code.

It was important that the language should not be tied to any single architecture. The project was code­named
“Green.”

The Sun people was from a UNIX background, so they based their language on C++ rather than Pascal and
made the language (“Oak”) object­oriented rather than procedure oriented. Oak was the name of an existing
Page 80 of 362
Introduction to Java programming Language

computer language, so the name changed into Java.

Oak was the name of an existing computer language, so the name changed to Java.

1992:

Green project delivered its first product, called “*7.” an extremely intelligent remote control.

The Green project (with a new name of “First Person, Inc.”) spent all of 1993 and half of 1994 looking for
people to buy its technology. None was ready.

1994:

First Person dissolved.

The HotJava browser released which was written in Java. It also had applets. Browser capable of executing
code inside web pages.

1996:

Sun released the first version of Java as Java 1.0.

By filling in the most obvious gaps, greatly improved the reflection capability, and added a new event model for
GUI programming Java 1.0’s successor version 1.1 came out.

1998:

Java 1.2 released with an altered name Java 2 Standard Edition Software Development Kit Versions 1.2.

Besides the Standard Edition, two other editions were introduced: the Micro Edition for embedded devices such
as cell phones, and the Enterprise Edition for server­side processing.

Versions 1.3 and 1.4 of the Standard Edition are incremental improvements over the initial Java 2 release, with
an ever­growing standard library, increased performance, and, of course, quite a few bug fixes.

Version 5.0 was the first release since version 1.1 that updated the Java language in significant ways. Generic
types were introduced.

2006:

Version 6 was released.

2009:

Sun Microsystems was purchased by Oracle.

2011:

Java 7 was released.

Table shows the evolution of the Java language and library. As you can see, the size of the application
programming interface (API) has grown tremendously.

Page 81 of 362
Introduction to Java programming Language

Common Misconceptions about Java

Java is an extension of HTML.

One uses XML hence one doesn’t need Java.

Java is an easy programming language to learn.

Java will become a universal programming language for all platforms.

Java is just another programming language.

Now that C# is available so Java is obsolete.

Java is proprietary, and it should therefore be avoided.

Java is interpreted, so it is too slow for serious applications.

All Java programs run inside a web page.

Java programs are major security risks.

JavaScript is a simpler version of Java.

With Java, one can replace one’s computer with a $500 “Internet appliance.”

Page 82 of 362
Introduction to Java programming Language

The Java Programming Environment

Introduction

In this chapter we will discuss the following topics:

Installing the Java Development Kit

Downloading the JDK

Setting the Executable Path

Installing the Library Source and Documentation

Installing the Core Java Program Examples

Navigating the Java Directories

Choosing a Development Environment

Using the Command­Line Tools

Troubleshooting Hints

Using an Integrated Development Environment

Compiling and Running Programs from a Text Editor

Running a Graphical Application

Building and Running Applets

Installing the Java Development Kit

Downloading the JDK:

To download the Java Development Kit, visit the following website:
www.oracle.com/technetwork/java/javase/downloads

Page 83 of 362
Introduction to Java programming Language

Setting the Executable Path

After you are done installing the JDK, you need to carry out an additional step:

Add the jdk/bin directory to the executable path: The list of directories that the operating system traverses
to locate executable files.

In Windows:

In the system properties dialog, click the Advanced tab and click on the Environment button.

Scroll through the System Variables window until you find a variable named Path.

Click the Edit button.

Add the jdk\bin directory to the beginning of the path, using a semicolon to separate the new entry, like this:
jdk\bin;other stuff.

Be careful to replace jdk with the actual path to your Java installation, such as c:\jdk1.7.0_02.

Save your settings.
Page 84 of 362
Introduction to Java programming Language

Test whether you did it right:

Start a shell window. Type the line:

javac ­version.

And press the Enter key. You will get a display such as this one:

javac 1.7.0_02.

Installing the Library Source and Documentation

Follow the steps:

Make sure the JDK is installed and that the jdk/bin directory is on the executable path.

Open a shell window.

Change to the jdk directory (e.g., cd /usr/local/jdk1.7.0 or cd c:\jdk1.7.0).

Make a subdirectory src:

Execute the command:

Installing the Core Java Program Examples

Here are the steps:

Make sure the JDK is installed and the jdk/bin directory is on the execution path.

Make a directory CoreJavaBook.

Download the corejava.zip file to that directory from http://horstmann.com/corejava.html.

Open a shell window.

Change to the CoreJavaBook directory.

Execute the command jar xvf corejava.zip

Page 85 of 362
Introduction to Java programming Language

Navigating the Java Directories

The two most useful subdirectories for learning Java are docs and src.

docs directory : It contains the Java library documentation in HTML format. You can view it with any web
browser such as Firefox.

src directory : It contains the source code for the public part of the Java libraries.

Choosing a Development Environment

The basic JDK contains nothing similar to a development environment with a built­in text editor and menus to
compile and launch a program along with an integrated debugger.

In a shell window you do everything by typing in commands.

After mastering the basic steps of compiling and running Java programs, you need to use a professional
development environment.

The freely available Eclipse and NetBeans programs are the two excellent choices.

On the whole, you should know how to use the basic JDK tools, and then you should become comfortable with
an integrated development environment.

Using the Command­Line Tools

Compiling and launching a Java program from the command line.

Open a shell window.

Create the Welcome directory in the CoreJavaBook folder and v1ch02 directory inside the CoreJavaBook
folder.

Go to the CoreJavaBook/v1ch02/Welcome directory.

Enter the following commands:

Page 86 of 362
Introduction to Java programming Language

javac Welcome.java.

java Welcome.

You should see the output shown in Figure in the shell window.

The javac program is the Java compiler. It compiles the file Welcome.java and create the Welcome.class
file.

The java program launches the Java virtual machine. It executes the bytecodes that the compiler placed in
the class file.

Using an Integrated Development Environment

Steps to Install Eclipse:

To use Eclipse for Java programming, you need to first install Java Development Kit (JDK).

Download Eclipse from https://www.eclipse.org/downloads.

To install Eclipse, simply unzip the downloaded file into a directory of your choice.

Steps to create a Java project in Eclipse

After starting Eclipse, select File ­> New Project from the menu.

Select “Java Project” from the wizard dialog.

Click the Next button. Supply the project name “Welcome” and type in the full path name of the directory
that contains Welcome.java

Page 87 of 362
Introduction to Java programming Language

Be sure to check the option labelled “Create project from existing source”.

Click the Finish button. The project is now created.

Click on the triangle in the left pane next to the project window to open it, and then click on the triangle next
to “Default package”. Double­click on Welcome.java. You should now see a window with the program code.

With the right mouse button, click on the project name (Welcome) in the leftmost pane. Select Run ­> Run
As ­> Java Application. An output window appears at the bottom of the window.

The program output is displayed in the output window.

Page 88 of 362
Introduction to Java programming Language

Compiling and Running Programs from a Text Editor

Writing the Java program:

Open a simple text editor program such as Notepad and type the following content:

Save the file as HelloWorld.java (note that the extension is .java) under a directory, let’s say, C:\Java.

Compiling

Type the following command to change the current directory to the one where the source file is stored: cd
C:\Java

And type the following command to compile: javac HelloWorld.java

After compiling, it generates theHelloWorld.class file which is bytecode form of the HelloWorld.java file.

Running the Java program

Page 89 of 362
Introduction to Java programming Language

Type the following command to run the program: java HelloWorld.

That invokes the Java Virtual Machine to run the program called HelloWorld.

The following will be the output:

Running a Graphical Application

Now we will demonstrate a graphical application.

This program is a simple image file viewer that just loads and displays an image.

We will compile and run it from the command line.

Open a shell window.

Change to the directory CoreJavaBook/v1ch02/ImageViewer.

Enter the following:

javac ImageViewer.java.

java ImageViewer.

A new program window pops up with our ImageViewer application.

Page 90 of 362
Introduction to Java programming Language

Now, select File ­> Open and look for an image file to open. To close the program, click on the Close box in the
title bar or select File ­>Exit from the menu.

Building and Running Applets

We will see how to build and run an applet from the command line. Then we will load our applet into the applet
viewer that comes with the JDK. Finally, we will display it in a web browser.

First, open a shell window and go to the directory CoreJavaBook/v1ch02/WelcomeApplet, then enter the
following commands:

javac WelcomeApplet.java

appletviewer WelcomeApplet.html

The Figure shows what you will see in the applet viewer window.

Page 91 of 362
Introduction to Java programming Language

The contents of the WelcomeApplet.html file are shown below.

Running applet inside Browser

Once you have configured your browser, you can try loading the applet inside the browser:

Start your browser.

Select File ­> Open File (or the equivalent).

Go to the CoreJavaBook/v1ch02/WelcomeApplet directory. You should see the WelcomeApplet.html file in

Page 92 of 362
Introduction to Java programming Language

the file dialog load the file.

Your browser now loads the applet, including the surrounding text.

The applet viewer is good for testing applets in isolation, but you need to put applets inside a browser to
see how they interact with the browser and the Internet.

Page 93 of 362
Introduction to Java programming Language

Fundamental Programming Structures in Java

Introduction

In this chapter we will discuss the following topics:

A Simple Java Program

Comments

Data Types

Variables

Operators

Strings

Input and Output

Control Flow

Big Numbers

Arrays.

A Simple Java Program

The following simple java program displays the output: We will not use ‘Hello World’.

The following rules apply while writing a java program:

Java is case sensitive.

public: access modifier ­ controls the level of access other parts of a program have to this code.

class: reminds that everything in a Java program lives inside a class.

Following the keyword class is the name of the class­ must begin with a letter, after that, they can have any
combination of letters and digits.

You cannot use a Java reserved word (such as public or class) for a class name.

File name for the source code must be the same as the name of the public class, with the extension .java
appended.

Page 94 of 362
Introduction to Java programming Language

The Java compiler compiles the source code and automatically names the bytecode file   class and
stores it in the same directory as the source file.

Launch the program by using the following command: java ClassName.

With the code in the main method JVM starts execution.

The code for any method must be started by an opening brace { and ended by a closing race }.

Every statement must end with a semicolon.

Java uses the general syntax as it is equivalent of a function call:

Methods in Java, like functions in any programming language, can use zero, one, or more Parameters.

Comments

Comments are not shown up in the executable program.

Three ways of marking comments are:

Data Types

Java is a strong typed language. Every variable must have a declared type.

Java has eight primitive types.

Integer Types:

Page 95 of 362
Introduction to Java programming Language

Negative values are allowed for numbers without fractional parts.

The int type is the most practical type.

If you want to represent the number of inhabitants of our planet, you’ll need a long one.

The byte and short types are mainly intended for specialized applications, such as low­level file handling.

Floating­Point Types:

The floating­point types denote numbers with fractional parts.

The name double numbers have twice the precision of the float type.

Most applications use double. The limited precision of float is simply not sufficient for many situations.

Numbers of type float have a suffix F (for example, 3.14F).

Floating­point numbers without an F suffix (such as 3.14) are always considered to be of type double.

The boolean Type:

The Boolean type has two values they are false and true.

It is used for evaluating logical conditions.

You cannot convert integers to a boolean values.

The char Type:

To describe individual characters the char type is used.

For example, ´A´ is a character constant with value 65. It is different from "A", a string containing a single
character.

Besides the \u escape sequences that indicate the encoding of Unicode code units, there are several escape

Page 96 of 362
Introduction to Java programming Language

sequences for special characters, as shown:

In Java, the char type describes a code unit in the UTF­16 encoding.

Unless you are actually manipulating UTF­16 code units do not use the char type in your programs.

Variables

Every variable has a type in Java.

By placing the type first you declare a variable, followed by the name of the variable.

Examples:

Since a declaration is a complete Java statement the semicolon is necessary.

A variable name must begin with a letter and must be a sequence of letters or digits.

Letter: ´A´–´Z, ´a´–´z´, ´_´, ´$´, or any Unicode character that denotes a letter in a language.

Digits: ´0´–´9´ and any Unicode characters that denote a digit in a language.

The length of a variable name is essentially unlimited.

One cannot use a Java reserved word for a variable name.

One can have multiple declarations on a single line: int i, j; // both are integers.

Initializing Variables:

By means of an assignment statement a declared variable must be explicitly initialized.

You can never use an uninitialized variable.

You assign to a previously declared variable by using the variable name on the left, an equal sign (=), and then
some Java expression with an appropriate value on the right.

Page 97 of 362
Introduction to Java programming Language

You can both declare and initialize a variable on the same line.

For example:

In Java you can put declarations anywhere in your code.

Constants:

In Java, keyword final used to denote a constant.

Class Circle: A constant is available to multiple methods inside a single class with the keywords static final.

Example:

In the above given program we have created the class circle and declared the variable PI as final and its value
cannot be changed. It displays the PI value 3.14159.

Operators

+, ­, *, / are used in Java for addition, subtraction, multiplication, and division.

Integer remainder (sometimes called modulus) is denoted by %.

Convenient shortcut for using binary arithmetic operators in an assignment

Page 98 of 362
Introduction to Java programming Language

Increment and Decrement Operators.

n++ adds 1 to the current value of the variable n, and n­­ subtracts 1 from it.

There is also a prefix form, ++n. e.g.,

Relational and boolean Operators:

Java has the full complement of relational operators.

== equality.

!= inequality.

< (less than), > (greater than), <= (less than or equal), and >= (greater than or equal).

&& logical “and”­ The value of expression1 && expression2 is automatically false if the first expression is false,
without evaluating the second expression.

|| Logical “or” operator. ­ The value of expression1 || expression2 is automatically true if the first expression is
true, without evaluating the second expression.

?: ternary operator that is occasionally useful. The expression condition ? expression1 : expression2.

Bitwise Operators:

The bitwise operators are:

& (“and”) | (“or”) ^ (“xor”) ~ (“not”).

>> and << operators which shift a bit pattern to the right or left.

>>> Operator fills the top bits with zero, unlike >> which extends the sign bit into the top bits. There is no <<<
operator.

Conversions between Numeric Types:

It is frequently necessary to convert from one numeric type to another.

Figure displays the legal conversions.

Page 99 of 362
Introduction to Java programming Language

Casts:

Numeric conversions are possible in Java, but of course information may be lost.

Conversions in which loss of information is possible are done by means of casts.

For example:

Now, the variable nx has the value 9 because casting a floating­point value to an integer discards the fractional
part.

Parentheses and Operator Hierarchy:

Operations are executed in the hierarchical order as indicated ff no parentheses are used. Operators on the
same level are processed from left to right, except for those that are right­associative, as indicated in the table.

Enumerated Types:

Page 100 of 362


Introduction to Java programming Language

An enumerated type has a finite number of named values.

For example:

Now you can declare variables of this type:

Strings

Java strings are sequences of Unicode characters.

Java does not have a built­in string type.

Java library contains a predefined class called String.

Each quoted string is an instance of the String class:

Substrings:

You can take a substring from a larger string with the substring method of the String class.

Concatenation:

Use + to join (concatenate) two strings.

Message variable set to the string "NewDelhi".
Page 101 of 362
Introduction to Java programming Language

Strings Are Immutable:

The String class gives no methods that let you change a character in an existing string.

The objects of the String class is referred as immutable since you cannot change the individual characters in a
Java string.

Testing Strings for Equality:

Use the equals method.

The subsequent expression returns true if the strings s and t are equal or false otherwise: s.equals(t)

To test whether two strings are matching except for the upper/lowercase letter distinction, use the
equalsIgnoreCase method: "Hello".equalsIgnoreCase("hello")

Empty and Null Strings:

The empty string "" is a string of length 0. Test empty string by calling if (str.length() == 0).

A String variable can hold null that indicates that no object is currently related with the variable. To test whether
a string is null, use the condition if (str == null).

Code Points and Code Units:

Java strings are employed as sequences of char values.

The char data type is a code unit for representing Unicode code points in the UTF­16 encoding.

The most commonly used Unicode characters can be represented with a single code unit.

A pair of code units is required by the supplementary characters.

For example:

To get the true length—that is, the number of code points—call:

Return the number of Unicode code points in the specified text range.

The String API:

The String class in Java comprises more than 50 methods.

Some are:

char charAt(int index)
Page 102 of 362
Introduction to Java programming Language

int codePointAt(int index)

boolean endsWith(String suffix)

int indexOf(String str)

Building Strings:

Whenever strings are concatenated, a new String object is constructed. This is time­consuming and wastes
memory.

By using the StringBuilder class this problem is avoided

Each time you need to add another part, which is called the append method.

To get a String object, Call the toString method.

Input and Output

Reading Input:

To read console input, construct a Scanner that is attached to System.in:

Use the various methods of the Scanner class to read input.

For example, the nextLine method reads a line of input.

The Scanner class is defined in the java.util package.

Formatting Output:

Page 103 of 362


Introduction to Java programming Language

Java uses printf method to format the output.

For example, the call prints x with a field width of 8 characters and a precision of 2 characters:

The format specifier starts with a % character is replaced with the corresponding argument.

The conversion character that ends a format specifier indicates the type of the value to be formatted: f is a
floating­point number, s a string, and d a decimal integer.

File Input and Output:

Construct a Scanner object like this, to read from a file:

If the file name contains backslashes, remember to escape each of them with an additional backslash:

Read from the file by using any of the Scanner methods.

To write to a file, construct a PrintWriter object. In the constructor, simply supply the file name:

If the file does not exist, new file will be created.

Use the print, println, and printf commands when printing to System.out.

Control Flow

Java supports both conditional statements and loops to determine control flow:

Block Scope:

A block or compound statement is any number of simple Java statements surrounded by a pair of braces {}.

Blocks define the scope of your variables.

A block can be nested inside another block.

Conditional Statements:

The conditional statement in Java has the form if (condition) statement.

Page 104 of 362


Introduction to Java programming Language

The condition must be surrounded by parentheses.

For example:

In this code all the statements surrounded by the braces will be executed when your age is greater than or
equal to 18.

Loops:

While a condition is true the while loop executes a statement.

The general form is while (condition) statement.

The while loop will never execute if the condition is false at the outset.

A while loop tests at the top. Therefore, the code in the block may never be executed.

To make sure a block is executed at least once, you will need to move the test to the bottom, using the do/while
loop

This loop executes the statement(s) atleast once and only then tests the condition.

Example:

Page 105 of 362


Introduction to Java programming Language

In the above example initially the do statement is executed first before checking the while condition statement.

After the statement is executed while loop checks the condition of x value until less than 20 and prints the
statement in the do loop. If the x value is greater than 20 then while loop stop its execution.

Determinate Loops:

The for loop is a general construct to support iteration controlled by a counter or similar variable that is updated
after every iteration.

The following loop prints the numbers from 1 to 10 on the screen.

The first slot of the for statement usually holds the counter initialization.

The second slot gives the condition that will be tested before each new pass through the loop.

The third slot specifies how to update the counter.

Multiple Selections ­ The switch Statement:

Java has a switch statement that is exactly like the switch statement in C and C++.

In the above given program the execution starts at the case label that matches the value on which the selection
is performed and continues until the next break or the end of the switch.

If none of the case labels match, then the default clause is executed, if it is present.

Statements That Break Control Flow:

Page 106 of 362


Introduction to Java programming Language

Break statement: The same break statement that you use to exit a switch can also be used to break out of a
loop. A labeled break statement lets you break out of multiple nested loops.

Continue statement : transfers control to the header of the innermost enclosing loop.

If the continue statement is used in a for loop, it jumps to the “update” part of the for loop.

Arrays

A data structure that stores a collection of values of the same type is an array.

You access each individual value through an integer index.

Example, if a is an array of integers, then a[i] is the ith integer in the array.

Declare an array variable by specifying the array type, which is the element type followed by [ ]—and the array
variable name.

Use the new operator to create the array.

The array elements are numbered from 0 to 99 (and not 1 to 100).

The “for each” Loop:

Java has a powerful looping construct that allows you to loop through each element in an array without having
to fuss with index values.

The enhanced for loop sets the given variable to each element of the collection and then executes the
statement.

The collection expression must be an array or an object of a class that gears the Iterable interface, such as
ArrayList.

The below given example explains about the enhanced for loop and it prints each element of the array a on a
separate line.

For example,

Array Initializers and Anonymous Arrays:

Java has a shorthand to make an array object and supply initial values at the same time.

Example:

Page 107 of 362


Introduction to Java programming Language

Need not call new when you use this syntax.

You can even initialize an anonymous array:

Array Copying:

You can copy one array variable into another, but then both variables refer to the same array:

To copy all values of one array into a new array, use the copyOf method in the Arrays class.

Command­Line Parameters:

Every Java program has a main method with a String [] args parameter.

This parameter shows that the main method receives an array of strings—viz., the arguments specified on the
command line.

Array Sorting:

To sort an array of numbers, use one of the sort methods in the Arrays class:

The Arrays class provides several other convenient methods for arrays that are included in the API.

Multidimensional Arrays:

Multidimensional arrays use more than one index to access array elements.

They are used for tables and other more complex arrangements.

Declaring a two­dimensional array in Java is simple. For example: double[ ][ ] balances;

One cannot use the array until you initialize it with a call to new.

One can do the initialization as follows: balances = new double[NYEARS][NRATES];
Page 108 of 362
Introduction to Java programming Language

Page 109 of 362


Introduction to Java programming Language

Objects and Classes

Introduction

In this chapter, we will discuss the following topics:

Introduction to Object­Oriented Programming

Using Predefined Classes

Defining Your Own Classes

Static Fields and Methods

Method Parameters

Object Construction

Packages

Documentation Comments

Class Design Hints

Introduction to Object­Oriented Programming

An object­oriented program is made up of objects. Each object has a specific functionality which is exposed to its
users and a hidden implementation.

Classes:

The template or blueprint from which objects are made is a class.

Create an instance of the class by constructing an object from a class.

Encapsulation: it is combining data and behavior in one package and hiding the implementation details from
the users of the object.

The bits of data in an object are called its instance fields, and the procedures that operate on the data are
called its methods.

Inheritance: Concept of classes built by extending other classes.

Objects: (Instance of a Class).

Key characteristics of objects:

The object’s behavior— by supporting the same behavior all objects that are instances of the same class
share a family resemblance.

The object’s state—each object stores information about what it currently looks like.

The object’s identity—the state of an object does not completely describe it, because each object has a
distinct identity.

Page 110 of 362


Introduction to Java programming Language

Identifying Classes:

The process starts at the top, with the main function in a traditional procedural program.

There is no “top” in an object­oriented system.

A simple rule of thumb in identifying classes is to look for nouns in the problem analysis. Methods, on the other
hand, correspond to verbs.

Relationships between Classes:

The most common relationships between classes are:

Dependence (“uses–a”) it is the most obvious and also the most general.

Aggregation (“has–a”) it is easy to understand because it is concrete;

Inheritance (“is–a”) it expresses a relationship between a more special and a more general class.

Using Predefined Classes

Objects and Object Variables:

To work with objects, first construct them and specify their initial state. Then apply methods to the objects.

Constructors: it is a special method whose purpose is to construct and initialize objects.

Example: Constructor for the Date class is called Date. new Date() // constructs a new object which is initialized
to the current date and time.

It can pass the object to a method:

It can apply a method to the object that you just constructed. One of the methods of the Date class is the
toString method. That method yields a string representation of the date.

To apply the toString method to a newly constructed Date object: String s = new Date().toString();

In Java, the value of any object variable is a reference to an object that is stored elsewhere.

All Java objects live on the heap. When an object contains another object variable, it contains just a pointer to
yet another heap object.

Mutator and Accessor Methods:

Only the get method looks up the state of the object and reports on it.

The state of the object is modified by the set and add methods.

Mutator methods change instance fields.

Methods that access only instance fields without modifying them are called accessor methods.

A common convention is to prefix accessor methods with the prefix get and mutator methods with the prefix
set.

The below given explains about the Mutator and Accessor methods. In here the class Student the name is
Page 111 of 362
Introduction to Java programming Language

declared as String variable and we have declared two methods getName() and setName() methods. The
getName() method is used to return the name and setName() method is used to assign the value for the name
attribute.

For example,

Defining Your Own Classes

To build a complete program, you combine several classes, one of which has a main method.

The simplest form for a class definition in Java is given below.

Example of a simple java class: StudentTest.java

Page 112 of 362


Introduction to Java programming Language

The example program consists of two classes: The Student class and a class StudentTest with the public
access specifier.

The main method is in the StudentTest class.

The name of the source file is StudentTest.java because the name of the file must match the name of the
public class.

You can have only one public class in a source file, but you can have any number of non public classes.

When you compile this source code, the compiler creates two class files in the directory: StudentTest.class and
Student.class.

Then you start the program by giving the bytecode interpreter the name of the class that contains the main
method of your program: java StudentTest

Use of Multiple Source Files:

The example has two classes in a single source file. Many programmers prefer to put each class into its own
source file.

You can compile the java program by using the below commands.

When the Java compiler sees the Employee class being used inside EmployeeTest.java, it will look for a file
named Employee.class.

Page 113 of 362


Introduction to Java programming Language

If it does not find that file, it automatically searches for Employee.java and compiles it.

First Steps with Constructors:

The Constructor runs when you construct objects of the class, giving the instance fields the initial state you
want them to have.

A constructor has the same name as the class.

A class can have more than one constructor.

A constructor can take zero, one, or more parameters.

A constructor has no return value.

A constructor is always called with the new operator.

Implicit and Explicit Parameters:

Methods operate on objects and access their instance fields:

The implicit parameter, is the object of type Employee that appears before the method name.

The second parameter is the number inside the parentheses after the method name, it is an explicit
parameter.

In every method, the keyword this refers to the implicit parameter.

Class­Based Access Privileges:

A method can access the private data of the object on which it is invoked.

A method can also access the private data of all objects of its class.

Private Methods:

Change the public keyword to private to implement a private method in Java.

As long as the method is private, it is never used outside the other class, so it can simply be dropped if
needed.

A method cannot simply be dropped because other code might rely on it if it is public.

Final Instance Fields

You can define an instance field as final.

It must be initialized when the object is constructed. That is, you must guarantee that the field value has been
set after the end of every constructor. Afterwards, the field may not be modified again.

The final modifier is particularly useful for fields whose type is primitive or an immutable class.

Page 114 of 362


Introduction to Java programming Language

Example:

Static Fields and Methods

Static Fields:

If you define a field as static, then there is only one such field per class.

In contrast, each object has its own copy of all instance fields.

A Static field belongs to the class, not to any individual object.

Static Constants:

Static variables are quite uncommon. However, static constants are more common.

For example, the Math class defines a static constant:

Static Methods

Methods that do not operate on objects are Static methods.

For example, the pow method of the Math class is a static method.

The expression Math.pow(x, a), computes the power x^a.

It does not use any Math object to carry out its task. i.e., it has no implicit parameter.

Cannot access instance fields from a static method. However, static methods can access the static fields in their
class.

Uses of static methods in two situations:

When a method doesn′t need to access the object state because all needed parameters are supplied as
explicit parameters (example: Math.pow).

A method needs only to access static fields of the class. (example: Student.getName).
Page 115 of 362
Introduction to Java programming Language

The main Method:

You can call static methods without having any objects.

For example, you never construct any objects of the Math class to call Math.pow.

The main method is a static method for the same reason.

The main method does not operate on any objects.

When a program starts, there are no objects yet.

The static main method executes, and constructs the objects that the program needs.

Method Parameters

call by value : The method just gets the value that the caller provides.

call by reference : The method gets the location of the variable that the caller provides.

A method can modify the value stored in a variable passed by reference but not in one passed by value.

Java always uses call by value. That means that the method gets a copy of all parameter values.

For example, consider the following call:

No matter how the method is implemented, we know that after the method call, the value of percent is still 10.

There are, however, two kinds of method parameters:

Primitive types (numbers, boolean values)­ it is impossible for a method to change a primitive type parameter.

Object references ­ methods can change the state of an object parameter. The reason is simple. The method
gets a copy of the object reference, and both the original and the copy refer to the same object.

Object Construction

Page 116 of 362


Introduction to Java programming Language

Java offers quite a variety of mechanisms for writing constructors.

Overloading:

If several methods have the same name but different parameters overloading occurs.

The compiler must sort out which method to call.

It picks the correct method by matching the parameter types in the headers of the various methods with the
types of the values used in the specific method call.

A compile­time error occurs if the compiler cannot match the parameters or if more than one match is possible.
This process is called overloading resolution.

Java allows you to overload any method, not just constructor methods.

Default Field Initialization

If you don´t set a field explicitly in a constructor, it is automatically set to a default value:

numbers to 0.

boolean values to false.

object references to null.

The Constructor with No Arguments:

Many classes contain a constructor with no arguments that create an object whose state is set to an
appropriate default.

For example, here is a constructor with no arguments for the Employee class:

If you write a class with no constructors, then a no­argument constructor is provided for you. This constructor
sets all the instance fields to their default values.

If a class supplies at least one constructor but does not supply a no­argument constructor, it is illegal to
construct objects without supplying arguments.

Explicit Field Initialization:

It is always a good idea to make sure that, regardless of the constructor call, every instance field is set to

Page 117 of 362


Introduction to Java programming Language

something meaningful.

The initialization value doesn′t have to be a constant value. It can be a method call.

Parameter Names:

It can be somewhat frustrating to come up with parameter names when you write very trivial constructors.

Some programmers prefix each parameter with an “a”.

Parameter variables shadow instance fields with the same name.

This keyword denotes the implicit parameter, that is, the object that is being constructed.

The below given example shows the constructor Employee which accepts two arguments and this keyword is
used to assign the value for the current instance.

Example:

Calling Another Constructor:

If the first statement of a constructor has the form this(. . .), then the constructor calls another constructor of
the same class.

Example:

Initialization Blocks:

You have already perceived two ways to initialize a data field:

By setting a value in a constructor.

By assigning a value in the declaration.

There is a third mechanism in Java, termed an initialization block.

Example:

Page 118 of 362


Introduction to Java programming Language

Class declarations can contain arbitrary blocks of code. These blocks are executed whenever an object of that
class is constructed.

Here is what happens in detail when a constructor is called:

All data fields are initialized to their default values (0, false, or null).

All field initializers and initialization blocks are executed, in the order in which they occur in the class
declaration.

If the first line of the constructor calls a second constructor, then the body of the second constructor is
executed.

The body of the constructor is executed.

Object Destruction and the finalize Method:

Java does automatic garbage collection, manual memory reclamation is not needed, so Java does not support
destructors.

You can add a finalize method to any class. The finalize method will be called before the garbage collector
sweeps away the object.

If a resource needs to be closed as soon as you have finished using it, you need to manage it manually. Supply
a close method that does the necessary cleanup, and call it when you are done with the object.

Packages

Java allows you to group classes in a collection called a package.

It guarantees the uniqueness of class names.

From the point of view of the compiler, there is absolutely no relationship between nested packages.

For example, the packages java.util and java.util.jar have nothing to do with each other. Each is its own
independent collection of classes.

Class Importation:

A class can utilize all classes from its own package and all public classes from other packages.

You can access the public classes in another package in two ways:

Page 119 of 362


Introduction to Java programming Language

Add the full package name in front of every class name. For example: java.util.Date today = new java.util.Date();

Use the import statement. You can import a specific class or the whole package. You place import
statements at the top of your source files. Example: import java.util.*; Then you can use Date today = new
Date(); without a package prefix.

Only use the * notation to import a single package.

Cannot use import java.* or import java.*.* to import all packages with the java prefix.

Static Imports:

A form of the import statement permits the importing of static methods and fields, not just classes.

For example: if you add the following directive to the top of your source file, then you can use the static
methods and fields of the System class without the class name prefix.

Addition of a Class into a Package:

To place classes inside a package, you must put the name of the package at the top of your source file, before
the code that defines the classes in the package.

If you don´t put a package statement in the source file, then the classes in that source file belong to the default
package.

The default package has no package name.

Place source files into a subdirectory that matches the full package name.

Example:

Package Scope:

Features tagged as public can be used by any class.

Private features can be used only by the class that defines them.

If you don’t specify either public or private, the feature (that is, the class, method, or variable) can be accessed

Page 120 of 362


Introduction to Java programming Language

by all methods in the same package.

Variables must explicitly be marked private, or they will default to being package­visible.

Documentation Comments

The JDK contains a very valuable tool, called javadoc, that produces HTML documentation from your source files.

Comment Insertion:

The javadoc utility extracts information for the following items:

Packages.

Public classes and interfaces.

Public and protected fields.

Public and protected constructors and methods.

You can (and should) supply a comment for each of these features.

Each comment is placed immediately above the feature it describes.

A comment starts with a /** and ends with a */.

Each /** . . . */ documentation comment contains free­form text followed by tags.

A tag starts with an @, such as @author or @param.

The first sentence of the free­form text should be a summary statement.

The javadoc utility automatically generates summary pages that extract these sentences.

Class Comments:

The class comment must be placed after any import statements, directly before the class definition. The below
example shows the multiline comments.

Example:

Method Comments:

Page 121 of 362


Introduction to Java programming Language

Each method comment must immediately head the method that it describes.

In addition to the general­purpose tags, you can use the following tags:

@param variable description : adds an entry to the “parameters” section of the current method.

@return description : adds a “returns” section to the current method.

@throws class description : adds a note that this method may throw an exception.

Field Comments:

You only need to document public fields, generally that means static constants.

Example:

General Comments:

The following tags can be used in class documentation comments:

@author name : makes an “author” entry.

@version text : makes a “version” entry.

The following tags can be used in all documentation comments:

@since text : makes a “since” entry.

@deprecated text : This tag adds a comment that the class, method, or variable should no longer be used.
The text should suggest a replacement.

@see reference : adds a hyperlink in the “see also” section.

Package and Overview Comments:

To generate package comments, you want to add a separate file in each package directory.

You have two choices:

Supply an HTML file named package.html. All text between the tags ... is extracted.

Supply a Java file named package­info.java. The file must contain an initial Javadoc comment, delimited with
/** and */, followed by a package statement. It should contain no further code or comments.

Comment Extraction:

Assume that docDirectory is the name of the directory where you want the HTML files to go.

Page 122 of 362


Introduction to Java programming Language

Follow these steps to extract the comments :

Change to the directory that contains the source files you want to document. If you have nested packages to
document, such as com.horstmann.corejava, you must be working in the directory that contains the
subdirectory com. (This is the directory that contains the overview.html file, if you supplied one.).

Run the command.

For a single package: javadoc ­d docDirectory nameOfPackage.

To document multiple packages: javadoc ­d docDirectory nameOfPackage1 nameOfPackage2...

If your files are in the default package: javadoc ­d docDirectory *.java.

If you omit the ­d docDirectory option, the HTML files are extracted to the current directory.

Class Design Hints

The following are some hints that will make your classes more acceptable in well­mannered OOP circles:

Always keep data private.

Always initialize data.

Don’t use too many basic types in a class.

Not all fields need individual field accessors and mutators.

Break up classes that have too many responsibilities.

Make the names of your classes and methods reflect their responsibilities.

Page 123 of 362


Introduction to Java programming Language

Inheritance

Introduction

We will discuss the following topics in this chapter:

Classes, Superclasses, and Subclasses

Object: The Cosmic Superclass

Generic ArrayLists

Object Wrappers and Autoboxing

Reflection

Enumeration Classes

Design Hints for Inheritance.

Classes, Superclasses, and Subclasses

The “is–a”relationship is the hallmark of inheritance.

Use the Java keyword extends to denote inheritance.

The keyword extends indicates that you are making a new class that derives from an existing class.

The existing class is also called the superclass, base class, or parent class.

The new class is also called the subclass, derived class, or child class.

Subclasses have more functionality than their superclasses.

When designing classes, you place the most general methods into the superclass and more specialized
methods in its subclasses.

A subclass can add fields, and it can add methods or override the methods of the superclass. However,
inheritance can never take away any fields or methods.

Java uses the keyword super to call a superclass method.

Inheritance Hierarchies:

The collection of all classes extending a common superclass is called an inheritance hierarchy.

The path from a particular class to its ancestors in the inheritance hierarchy is its inheritance chain.

Multiple inheritance is not supported by Java.

Polymorphism:

The “is–a” rule states that every object of the subclass is an object of the superclass.

Page 124 of 362


Introduction to Java programming Language

Another way of formulating the “is–a” rule is the substitution principle.

The principle states that you can use a subclass object whenever the program expects a superclass object.

Object variables are polymorphic.

For example, you can assign a subclass object to a superclass variable.

Dynamic Binding:

It is important to understand what happens when a method call is applied to an object. Here are the details:

The compiler looks at the declared type of the object and the method name.

Next, the compiler determines the types of the parameters that are supplied in the method call. This
process is called overloading resolution.

If the method is private, static, final, or a constructor, then the compiler knows exactly which method to
call. This is called static binding. Otherwise, the method to be called depends on the actual type of the
implicit parameter, and dynamic binding must be used at runtime.

When the program runs and uses dynamic binding to call a method, then the virtual machine must call
the version of the method that is appropriate for the actual type of the object to which it refers.

Preventing Inheritance: Final Classes and Methods:

Classes that cannot be extended are called final classes.

The final modifier in the definition of the class indicates this.

Example:

There is only one good reason to make a method or class final is to make sure that its semantics cannot be
changed in a subclass.

Casting:

The process of forcing a conversion from one type to another is called casting.
Page 125 of 362
Introduction to Java programming Language

You can cast an object reference from one class to another.

Example: Manager boss = new staff();

To use an object in its full capacity after its actual type has been temporarily forgotten is the only one
reason why you would want to make a cast.

To sum up:

You can cast only within an inheritance hierarchy.

Use instanceof to check before casting from a superclass to a subclass.

Abstract Classes:

Use the abstract keyword to eliminate the need to implement the method.

A class with one or more abstract methods must itself be declared abstract.

In addition to abstract methods, abstract classes can have fields and concrete methods.

Abstract methods act as placeholders for methods that are implemented in the subclasses.

When you extend an abstract class, you have two choices.

You can leave some or all of the abstract methods undefined; then you must tag the subclass as abstract
as well.

You can define all methods, and the subclass is no longer abstract.

A class can even be declared as abstract even though it has no abstract methods.

Abstract classes cannot be instantiated ­ no objects of that class can be created.

Protected Access:

You declare a class feature as protected when you want to restrict a method to subclasses only.

Here is a summary of the four access modifiers in Java that control visibility:

Visible to the class only (private).

Visible to the world (public).

Visible to the package and all subclasses (protected).

Visible to the package—the (unfortunate) default. No modifiers are needed.

Page 126 of 362


Introduction to Java programming Language

Object: The Cosmic Superclass

Every class in Java extends Object.

Some services provided by the Object class are:

The equals Method:

The equals method in the Object class tests whether one object is considered equal to another.

The equals method, as implemented in the Object class, determines whether two object references are
identical: ObjectA.equals(ObjectB);

The Java Language Specification requires that the equals method has the following properties:

It is reflexive: For any non­null reference x, x.equals(x) should return true.

It is symmetric: For any references x and y, x.equals(y) should return true if and only if y.equals(x) returns
true.

It is transitive: For any references x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then
x.equals(z) should return true.

It is consistent: If the objects to which x and y refer haven’t changed, then repeated calls to x.equals(y)
return the same value.

For any non­null reference x, x.equals(null) should return false.

The hashCode Method:

A hash code is an integer that is derived from an object.

The hashCode method is defined in the Object class. Therefore, every object has a default hash code.
That hash code is derived from the object´s memory address.

Example :The String class uses the following program to compute the hash code:

Page 127 of 362


Introduction to Java programming Language

The toString Method:

It returns a string representing the value of this object.

The toString method of the Point class returns a string like this:

toString() − This returns a String object representing the value of this Integer. The above program returns
the String object representing the specified integer.

Generic Array Lists

The ArrayList class is similar to an array, but, without any additional code it automatically adjusts its capacity
as you add and remove elements.

ArrayList is a generic class with a type parameter.

In the below given program contents are added to the arraylist through by using add() functions. Then
remove() method is used to remove the contents from the arraylist.

Page 128 of 362


Introduction to Java programming Language

Accessing Array List Elements:

Use the get and set methods to access or change the element of an array.

For example:

To add the i th  element, you use:

You can remove an element from the middle of an array list:

Compatibility between Typed and Raw Array Lists:

For added safety always use type parameters.

Suppose you have the following legacy class:

Page 129 of 362


Introduction to Java programming Language

In this program you can pass a typed array list to the update method without any casts.

The list object is simply passed to the addCats() method.

Object Wrappers and Autoboxing

All primitive types have class counterparts.

For example, a class Integer corresponds to the primitive type int.

These kinds of classes are usually called wrappers.

The wrapper classes have obvious names as Integer, Long, Float, Double, Short, Byte, Character, Void, and
Boolean.

The wrapper classes are immutable—you cannot change a wrapped value after the wrapper has been
constructed.

They are also final, so you cannot subclass them.

It is not possible to form an ArrayList.

It is OK to declare an array list of Integer objects:

Page 130 of 362


Introduction to Java programming Language

Java makes it easy to add and get array elements: The call, List.add(3); is automatically translated to
list.add(Integer.valueOf(3));

This conversion is called Autoboxing.

It is automatically unboxed when an Integer object is assigned to an int value. i.e., the compiler translates

Automatic boxing and unboxing even works with arithmetic expressions.

Use the following statement to convert a string to an integer:

Important methods of the Integer class:

Enumeration Classes

public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};

The type defined by this declaration is actually a class.

This class has exactly four instances. It is not possible to construct new objects.

Uses == to compare values of enumerated types.

Add constructors, methods, and fields to an enumerated type.

Example:

Page 131 of 362


Introduction to Java programming Language

All enumerated types are subclasses of the class Enum. They inherit a number of methods from that class.

In the above give program the enumerator Day is declared and assigned the values from Sunday to Saturday.

The object has been created for the Day Enumerator and printDayGreeting method is called by passing the
enumerated variable.

In the printDayGreeting() method the day is checked as Friday. If it is not Friday then the output is printed as
“Some other day”.

Reflection

The reflection library gives you a very rich and elaborate toolset to write programs that manipulate Java code
dynamically.

In JavaBeans this feature is heavily used.

A program that can analyze the capabilities of classes is called reflective.

The Class class:

While a program is running, the Java runtime system always upholds what is called runtime type
identification on all objects.

You can also access this information by working with a special Java class.

The class that holds this information is called, somewhat confusingly, Class.

Page 132 of 362


Introduction to Java programming Language

The getClass() method in the Object class returns an instance of Class type.

A Class object defines the properties of a particular class.

The most commonly used method of Class is getName. This returns the name of the class:

You can obtain a Class object corresponding to a class name by using the static forName method.

A third method for obtaining an object of type Class is , if T is any Java type, then T.class is the matching
class object.

For example:

To create an instance of a class on the fly, use the newInstance () method.

For example:

A Primer on Catching Exceptions:

A program can “throw an exception” when an error occurs at runtime.

Throwing an exception is more flexible than terminating the program because you can provide a handler
that “catches” the exception and deals with it.

There are two types of exceptions: unchecked exceptions and checked exceptions.

Checked exceptions ­ the compiler checks that you provide a handler.

Many common exceptions come under this, such as accessing a null reference, are unchecked.

In the below given example the exception occurs when an integer is divided by zero. So we can use
Arithmetic Exception to handle the error and print the Exception object.

Example:
Page 133 of 362
Introduction to Java programming Language

Using Reflection to Analyze the Capabilities of Classes:

The three classes Field, Method, and Constructor in the java.lang.reflect package describe the fields,
methods, and constructors of a class, respectively.

All three classes have a method called getName that returns the name of the item.

All three classes also have a method called getModifiers that returns an integer, with various bits turned on
and off, that describes the modifiers used, such as public and static.

Methods like isPublic, isPrivate, or isFinal in the modifier class to tell whether a method or constructor was
public, private, or final.

The getFields, getMethods, and getConstructors methods of the Class class return arrays of the public
fields, methods, and constructors that the class supports.

The getDeclaredFields, getDeclaredMethods, and getDeclaredConstructors methods of the Class class
return arrays consisting of all fields, methods, and constructors that are declared in the class.

Using Reflection to Analyze Objects at Runtime:

You can use reflection to look at fields of objects that were not known at compile time.

If f is a field, then f.get(obj) returns an object whose value is the current value of the field of obj.

The call f.set(obj, value) sets the field represented by f of the object obj to the new value.

Using Reflection to Write Generic Array Code:

The Array class in the java.lang.reflect package allows you to create arrays dynamically.

An array of objects cannot be cast to an array of some class.

To be able to make a new array of the same type as the original array, we need the methods of the Array
class in the java.lang.reflect package.

The static newInstance () method of the Array class that constructs a new array is the key.

Page 134 of 362


Introduction to Java programming Language

You must supply the type for the entries and the desired length as parameters to this method:

Design Hints for Inheritance

The following are some hints for using Inheritance.

Place common operations and fields in the superclass.

Don’t use protected fields.

Use inheritance to model the “is–a” relationship.

Don’t use inheritance unless all inherited methods make sense.

Don’t change the expected behaviour when you override a method.

Use polymorphism, not type information.

Don’t overuse reflection.

Page 135 of 362


Introduction to Java programming Language

Interfaces and Inner Classes

Introduction

In this chapter we will discuss the following topics:

Interfaces

Object Cloning

Interfaces and Callbacks

Inner Classes

Interfaces

An interface is not a class but a set of requirements for the classes that want to conform to the interface in the
Java programming language.

All methods of an interface are automatically public.

Interfaces never have instance fields, and the methods are never implemented in the interface. Supplying
instance fields and method implementations is the job of the classes that implement the interface.

To make a class implement an interface, you carry out two steps:

You declare that your class intends to implement the given interface.

You supply definitions for all methods in the interface.

To declare that a class implements an interface, use the implements keyword: Employee implements Comparable.

In the below given program the Employee class implements the interface comparable and compareTo() method is
used to compare the employee salary.

Example:

Page 136 of 362


Introduction to Java programming Language

Properties of Interfaces:

Interfaces are not classes. i.e., you can never use the new operator to instantiate an interface.

Declare interface variables as: Comparable x; // OK.

An interface variable must refer to an object of a class that implements the interface: x = new Employee(. . .);

You can use instanceof to check whether an object implements an interface: if (anObject instanceof
Comparable) { . . . }.

Interfaces and Abstract Classes:

There is a major problem with using an abstract base class to express a generic property.

A class can only extend a single class. But, each class can implement as many interfaces as it likes.

Object Cloning

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by
using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.

The clone method is a protected method of Object, which means that your code cannot simply call it.

For every class, you need to decide whether,

The default clone method is good enough;

The default clone method can be patched up by calling clone on the mutable subobjects;

Page 137 of 362


Introduction to Java programming Language

Clone should not be attempted.

The third option is actually the default. To choose either the first or the second option, a class must.

Implement the Cloneable interface; and,

Redefine the clone method with the public access modifier.

The following program clones an instance of the class Student.

Initially we can create an object for the class Student and then we can use clone() method to create cloning for the
same value.

In here the Roll no and name of the student has been cloned using the clone() method.

Interfaces and Callbacks

The callback pattern is a common pattern in programming.

Page 138 of 362


Introduction to Java programming Language

You need to specify the action that should occur whenever a particular event happens in this pattern.

There is a interface named CallBack is declared.

Through the Caller class object, the register method has been called an it will notifiy the methodToCallBack
method which is declared in the CallBackImpl class.

In the below given program we have implemented the interface CallBack and declared the method
methodToCallBack() and its definition is given in the CallBackImpl class.Next we have created the Caller class and
we have created object for Caller class and CallBack class.

Then we have called register method to register the callback.After calling the register() method then it will call the
methodToCallBack() to print “I have been called back”.

Example:

Inner Classes

Page 139 of 362


Introduction to Java programming Language

An inner class is a class that is defined inside another class.

There are three reasons:

Inner class methods can access the data from the scope in which they are defined, including the data that
would otherwise be private.

Inner classes can be hidden from other classes in the same package.

Anonymous inner classes are handy when you want to define callbacks without writing a lot of code.

In the below given program the Inner class is declared inside the Outer class.

We have created object for the Outer class.With that object display() method is invoked. Inside the Outer class
we have created object for Inner class and invoked the show() method which is defined inside the inner class.

The nesting is a relationship between classes, not objects.

An object that comes from an inner class has an implicit reference to the outer class object that instantiated it.

Through this pointer, it gains access to the total state of the outer object.

Page 140 of 362


Introduction to Java programming Language

Static inner classes do not have this added pointer.

Example of Inner class inside a method

The syntax for inner classes is rather complex. The below example is same as the above program but here we
have declared the Inner class inside the display() method.

Local Inner Classes:

Page 141 of 362


Introduction to Java programming Language

Local classes are never declared with an access specifier (that is, public or private).

Their scope is always restricted to the block in which they are declared.

They are completely hidden from the outside world. It is one great advantage of using the local classes.

The below given program is an example of LocalInner classes. Local is the class which is declared inside the
localInner class.

In here the variable data is declared as private and it id accessible inside the Local class also.

Example:

Anonymous Inner Classes:

If you want to make only a single object of this class, you don’t even need to give the class a name. Such a
class is called an anonymous inner class.

Syntax:

Page 142 of 362


Introduction to Java programming Language

Here, Eatable is an interface then, the inner class implements that interface.

An anonymous inner class cannot have constructors because the name of a constructor must be the same as
the name of a class, and the class has no name.

On the other hand the construction parameters are given to the superclass constructor.

Static Inner Classes:

You can suppress the generation of that reference by declaring the inner class static, if you want to use an
inner class simply to hide one class inside another, but you don’t need the inner class to have a reference to
the outer class object.

A normal inner class has a connection between its objects and the outer class object that created the inner
class object.

This allows an inner class definition to reference an instance variable, or invoke a method of the outer class.

There are certain situations, however, when an inner class must be static.

If an object of the inner class is created within a static method of the outer class.

If the inner class must have static members.

Since a static inner class has no connection to an object of the outer class, within an inner class method.

Instance variables of the outer class cannot be referenced.

Nonstatic methods of the outer class cannot be invoked.

To invoke a static method or to name a static variable of a static inner class within the outer class, preface
each with the name of the inner class and a dot.

Page 143 of 362


Introduction to Java programming Language

Introduction to GUI

Introduction

We will discuss the following topics in this chapter:

AWT Architecture

Light­Weight vs Heavy­Weight

AWT Event Model

AWT Event Hierarchy & Event Handling

Using Top­Levels

Components and containers

Introduction to Layouts

Focus Architecture

AWT Architecture

Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window­based application in java.

Java AWT components are platform­dependent i.e. components are displayed according to the view of operating
system.

AWT is heavyweight i.e. its components use the resources of system.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox,
Choice, List etc.

Page 144 of 362


Introduction to Java programming Language

Container: The Container is a component in AWT that contains other components like buttons, textfields, labels
etc. The classes that extend Container class are called container such as Frame, Dialog and Panel.

Window: The window is the container that has no borders and menu bars. You must use frame, dialog or another
window for creating a window.

Panel: The Panel is the container that doesn´t contain title bar and menu bars. It can have other components like
button, textfield etc.

Frame: The Frame is the container that contain title bar and can have menu bars. It can have other components
like button, textfield etc.

Java AWT Example

Page 145 of 362


Introduction to Java programming Language

To create simple awt example, you need a frame. There are two ways to create a frame in AWT.

By extending Frame class (inheritance).

By creating the object of Frame class (association).

Simple example of AWT by inheritance:

Simple example of AWT by association:

Output:

Page 146 of 362


Introduction to Java programming Language

Light­Weight vs Heavy­Weight

Lightweight components.

They are not tied directly to GUI components supported by underlying platform

Heavyweight components.

Tied directly to the local platform.

AWT components.

Some Swing components.

Understanding the Z­Order:

Top­level component in Swing (JWindow, JDialog, JApplet, and JFrame) is heavyweight, while everything else
isn′t.

If a heavyweight component is added to a container that has lightweight components, the heavyweight is
always on top; the lightweight component must share the same z­order as the parent container.

Lightweight components cannot draw themselves outside the container they reside in, or they are clipped.

Mixing Swing and AWT:

Let′s discuss some of the common problems that will occur if light and heavy weight components are mixed.

Overlapping heavyweight and lightweight components:

Page 147 of 362


Introduction to Java programming Language

The basic strategy is to ensure that lightweight components and heavyweight components in the same container do
not overlap.

Figure shows a list of layout managers and panes that can and cannot be used to mix lightweight and
heavyweight components.

Heavyweight components in front of lightweight menus:

Heavyweight components are always drawn in front of lightweight menus.

The problem is any menus that are drawn are placed behind the component.

Hence, a user may bring up a menu but unable to select a specific menu item.

Figure shows four heavyweight panels positioned in front of a lightweight Edit menu.

While you can still select a menu, you can′t see it : the repainting mechanism in Java redraws the heavyweight

Page 148 of 362


Introduction to Java programming Language

panels over the menus as they are activated.

Pop ups

Pop­up components include elements found in Swing menus, pop­up menus, and combo boxes.

These components get into trouble because they may be called upon to display themselves outside the
confines of their heavyweight top­level container.

Spring can use a heavyweight AWT Window to display the pop up instead.

Pop­up components in Swing contain a property called lightWeightPopupEnabled that allows them to switch
from lightweight to heavyweight to display themselves.

Figure shows which type of component Swing uses in various scenarios.

To mix lightweight and heavyweight components, you should always set the lightWeightPopupEnabled property
for any pop ups in the application to false, including menus.

Heavyweight components in JScrollPane:

Heavy weight components don’t work in JScrollPane.

The component inside the JScrollPane object fails to clip properly when it is placed inside the pane, and visible
artifacts are easy to pick up.

Heavyweight components inside internal frames:

It is a bad idea.

The problem here is that internal frames can overlap by design.

The component is still drawn on top of the overlapping internal frame if an overlap occurs, and the internal
frame with the heavyweight component is on the bottom.

Page 149 of 362


Introduction to Java programming Language

AWT Event Model

Events are handled in terms of event sources and event listeners in Java.

An event source is an object that produces an event and an event listener is an object that wants to be informed
when an event occurs.

For example, a button is an event source, and an animation object might be an event listener.

Using an addXXXListener:

How do the sources know who is interested in their events?

There are two parts to the communication:

The Setup­ who is listening to whom.

The Event­ when sources inform listeners of the occurrence of an event.

To handle this, each component has methods that can be used to register objects as listeners for its events.

These methods are of the form: addXXXListener(XXXListener l)

Where XXX describes the kinds of events that are of interest.

For example,

All Component objects have a method: addMouseMotionListener(MouseMotionListener l) so if foo is a
component and bar wants to know about mouse events in foo, we can say:
foo.addMouseMotionListener(bar) provided that bar implements the MouseMotionListener interface.

Page 150 of 362


Introduction to Java programming Language

Listener Interfaces:

The MouseMotionListener interface has the following methods:

public abstract void mouseDragged(MouseEvent e);

public abstract void mouseMoved(MouseEvent e);

So, any object that wants to listen for mouse motion events must implement this interface by providing bodies
for these methods.

The parameters to the methods in a listener interface are used for passing information to the listener about the
event that occurred.

For example, a MouseEvent object has getX() and getY() methods for finding out where the mouse was when
the event occurred.

Most Listener interfaces and Event types are contained in the package java.awt.event.

Event Model Example:

If we want a text field the user can type into, and we want a button that can be used to reset the text field to a
default value, something like shown below.

In the below given program when the user is clicked the rest button then the text in the text box will be
resetted. 

Page 151 of 362


Introduction to Java programming Language

AWT Event Hierarchy & Event Handling

Event Classes:

Event Object Contents:

Page 152 of 362


Introduction to Java programming Language

java.awt.AWTEvent:

Class hierarchy and methods:

Page 153 of 362


Introduction to Java programming Language

Event Sources and Their Listeners:

Component (ALL components extend this)

ComponentListener, FocusListener, KeyListener, MouseListener, MouseMotionListener

Dialog ­ WindowListener

Frame ­ WindowListener

Button ­ ActionListener

Choice ­ ItemListener

Checkbox ­ ItemListener

CheckboxMenuItem ­ ItemListener

List ­ ItemListener, ActionListener

MenuItem ­ ActionListener

Scrollbar ­ AdjustmentListener

TextField ­ ActionListener, TextListener

TextArea ­ TextListener

Listener Adapter Classes

Page 154 of 362


Introduction to Java programming Language

Provide empty default implementations of methods in listener interfaces with more than one method.

They include:

To use, extend from them

override methods of interest

usefulness is limited by single inheritance

can’t do if another class is already being extended

implementation for methods that are not of interest could look like this

Event Handling

Any program that uses GUI (graphical user interface) such as Java application written for windows, is event
driven. Event describes the change of state of any object.

Example: Pressing a button, Entering a character in Textbox.

Components of Event Handling.

Event handling has three main components,

Events: An event is a change of state of an object.

Events Source: Event source is an object that generates an event.

Listeners: A listener is an object that listens to the event. A listener gets notified when an event occurs.

How Events are handled?

A source generates an Event and sends it to one or more listeners registered with the source. Once event is
received by the listener, they process the event and then return. Events are supported by a number of Java
packages, like java.util, java.awt and java.awt.event.

Important Event Class and Interface.

Page 155 of 362


Introduction to Java programming Language

Example:

Page 156 of 362


Introduction to Java programming Language

HTML code: 

The above given program triggered the keypressed, keyreleased and Keytyped events.

Output:

Page 157 of 362


Introduction to Java programming Language

Using Top­Levels

Swing provides three generally useful top­level container classes: JFrame, JDialog, and JApplet.

Instructions to use these classes:

Every GUI component must be part of a containment hierarchy to appear onscreen. A containment hierarchy is
a tree of components that has a top­level container as its root. We′ll show you one in a bit.

Each GUI component can be contained only once. If a component is already in a container and you try to add it
to another container, the component will be removed from the first container and then added to the second.

Each top­level container has a content pane that, generally speaking, contains (directly or indirectly) the visible
components in that top­level container´s GUI.

You can optionally add a menu bar to a top­level container. The menu bar is by convention positioned within
the top­level container, but outside the content pane. Some look and feels, such as the Mac OS look and feel,
give you the option of placing the menu bar in another place more appropriate for the look and feel, such as at
the top of the screen.

Here´s a picture of a frame created by an application.

The frame contains a green menu bar (with no menus) and, in the frames content pane, a large blank, yellow
label.

Page 158 of 362


Introduction to Java programming Language

The containment hierarchy for this example´s GUI:

Top­Level Containers and Containment Hierarchies.

Each program that uses Swing components has at least one top­level container.This top­level container is the
root of a containment hierarchy: the hierarchy that contains all of the Swing components that appear inside the
top­level container.

A standalone application with a Swing­based GUI has at least one containment hierarchy with a JFrame as
its root.

Example: If an application has one main window and two dialogs, the application has three containment
hierarchies, and thus three top­level containers. One containment hierarchy has a JFrame as its root, and
each of the other two has a JDialog object as its root.

A Swing­based applet has at least one containment hierarchy, exactly one of which is rooted by a JApplet
object.

Example: An applet that brings up a dialog has two containment hierarchies. The components in the browser
window are in a containment hierarchy rooted by a JApplet object. The dialog has a containment hierarchy
rooted by a JDialog object.
Page 159 of 362
Introduction to Java programming Language

Adding Components to the Content Pane:

frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);

As the code indicates the content pane of a top­level container can be seen by calling
the getContentPane method.

The default content pane is a simple intermediate container which derives it from JComponent, and that
uses a BorderLayout as its layout manager.

The getContentPane method returns a Containerobject, not a JComponent object.

To make a component the content pane, use the top­level container´s setContentPane method. For example:

Adding a Menu Bar:

All top­level containers can hold a menu bar.

Create aJMenuBar object, populate it with menus, and then call setJMenuBar to add a menu bar to a top­level
container

The TopLevelDemo adds a menu bar to its frame with this code: frame.setJMenuBar(greenMenuBar);

The Root Pane:

Each top­level container relies on a reclusive intermediate container called the root pane.

The root pane manages the content pane and the menu bar, along with a couple of other containers.

List of the components that a root pane provides to a frame:

Page 160 of 362


Introduction to Java programming Language

The layered pane contains the menu bar and content pane, and enables Z­ordering of other components.

The glass pane is often used to intercept input events occurring over the top­level container, and can also be
used to paint over multiple components.

Components and Containers

A component is the basic user interface object In java and is found in all Java applications. Components include
lists, buttons, panels, and windows. 

A container is a component that holds and manages other components. Containers display components using a
layout manager.

Swing components inherit from the javax.Swing.JComponent class.

Swing provides the following useful top­level containers, all of which inherit from JComponent:

JWindow:

A top­level window that doesn´t have any trimmings and can be displayed anywhere on a desktop.

A heavyweight component. You usually use JWindow to create pop­up windows and "splash" screens.

Extends AWT´s Window class.

JFrame:

A top­level window that can contain borders and menu bars.

A subclass of JWindow and is thus a heavyweight component. You place a JFrame on a JWindow.

Extends AWT´s Frame class.

JDialog.

A lightweight component that you use to create dialog windows. You can place dialog windows on a JFrame
or JApplet.

Extends AWT´s Dialog class.

Page 161 of 362


Introduction to Java programming Language

JApplet.

A container that provides the basis for applets which run within web browsers. 

A lightweight component that can contain other graphical user interface (GUI) components.

Extends AWT´s Applet class.

Each top­level container depends on another intermediate container called the root, which provides a number of
components to each.

Each top­level container consists of the following panes:

Root pane: The root pane is an intermediate container that intermediates among the layered pane, content pane,
and glass pane. It can also manage an optional menu bar. You use a root pane to paint over multiple components
or to catch input events.

Layered pane: It contains the content pane and the optional menu bar. It can also contain other components of it
arranges so that they overlap each other. The layered pane provides six functional layers where placing the
components you add to it can be done.

Content pane: The content pane holds all the visible components of the root pane except the menu bar. It spreads
its umbrella on all the visible section of the JFrame or JWindow and added components are there in the display
area. Java automatically generates a content pane when you create a JFrame or JWindow instead you can create
your own content pane, of opaque.

Glass pane: By default The glass pane is invisible but you can enable it visible. When it becomes visible, it
contains the components of the content pane, blocks all input events from reading these components, and can
paint over an existing area containing one or more components.

JComponent services

JComponent is the root class for all Swing components such as JPanel, JLabel, and JButton. This class inherits
from the Container class and enables for adding containers and components to an application.

It credits the following functionality features to its subclasses:

Customizing component appearance.

Checking component states.

Page 162 of 362


Introduction to Java programming Language

Adding event handling.

Painting components.

Modifying the containment hierarchy.

Arranging the layout of components.

Retrieving component size and position information.

TextComponent Printing.

Using components and containers.

All Swing applications have a containment hierarchy with a top­level container at its root to which components
can be added.

For example:

You can create a dialog within a JFrame container by adding a JDialog container to it via a content pane.

Use the add method to add components to all containers except JFrame and JWindow.

Use the setVisible method to make the component visible.

After adding the components to a container, you can:

Set their size: use the setSize method.

Specify the focus: use the setFocusable method.

Introduction to Layouts

Layout can be defined as the arrangement of components within the container.

Layout Manager:

The layout manager automatically slablises all the components within the container.

Though it is possible to layout the controls by hand, it becomes very difficult due to the following two reasons.

It is very tedious to handle a large number of controls within a single.

Often the width and height information of a component is not given while arranging them.

When either size of the applet or the application window changes, it reflects a change in the size, shape and
arrangement of the components i.e. it adapts to the dimensions of applet viewer or the application window.

It is associated with every Container object.

Each layout manager is an object of the class that implements the LayoutManager interface.

The LayoutManager interface declares those methods to be implemented by the class whose object will act as
a layout manager.

The LayoutManager2 is the sub­interface of the LayoutManager which is for those classes that know how to

Page 163 of 362


Introduction to Java programming Language

layout containers based on layout constraint object.

AWT Layout Manager Classes:

Following mentioned is the list of commonly used controls when designed GUI using AWT.

BorderLayout: The borderlayout arranges the components to fit in the five regions like east, west, north,
south and center.

CardLayout: The CardLayout object treats each component in the container as a card. Only one card is
made to be visible at a time.

FlowLayout: The FlowLayout is the default layout. It layouts the components in a directional flow.

GridLayout: The GridLayout manages the components in form of a rectangular grid.

GridBagLayout: This is the most flexible layout manager class. The object of GridBagLayout aligns the
component vertically, horizontally or along their baseline without requiring the components of same size.

Focus Architecture

When the user presses keys on the keyboard Focus specifies the component that receives keyboard events.

The KeyboardFocusManager manages state and initiates changes. It is a critical element of the focus subsystem.

It tracks the focus owner. The component that receives typing from the keyboard.

The focused window is the window that contains the focus owner.

A focus cycle (or focus traversal cycle) is a set of components that share a common ancestor in the containment
hierarchy.

The focus cycle root is the container that is the root for a particular focus traversal cycle.

The following Swing objects can be focus cycle roots: JApplet, JDesktopPane, JDialog, JEditorPane, JFrame,
JInternalFrame, and JWindow.

A focus traversal policy determines the order of a group of components is navigated.

Swing provides the LayoutFocusTraversalPolicy class. It decides the order of navigation based on layout
manager­dependent factors, such as size, location, and orientation of components.

Within a focus cycle, components can be navigated in a forward or backward direction.

Components are navigated in most Look and Feel models by using the Tab and Shift­Tab keys.

These defaults focus traversal keys intended to be modified in programme wise.

Ex. Adding enter can give a forward focus traversal key with the following four line of code.

Page 164 of 362


Introduction to Java programming Language

Tab shifts the focus in the forward direction.

Shift­Tab moves the focus in the backward direction.

Validating Input:

GUI design can be a common requirement. It is a component. It controls the user’s input.

Formatted text field components can be helpful in using an input to a variety of Localized formats.

Custom formatter can also be used.

Instead of custom formatter, input verifier can be an alternative.

It permits the programmer to deny specific values like a properly formatted but invalid zip code, or values
outside of a desired range.

In order to use an input verifier, you create a subclass of Input Verifier, create an instance of your subclass,
and set the instance as the input verifier for one or more components.

Whenever the component is about to leave the focus a component′s input verifier is consulted.

If the component′s value is not acceptable, the input verifier can take appropriate action, such as refusing to
yield the focus on the component or replacing the user′s input with the last valid value and then allowing the
focus to transfer to the next component.

Input Verifier is not called when the focus is transferred to another top­level component.

Making a Custom Component Focusable:

For gaining the focus a component must satisfy three requirements: it must be visible, enabled, and focusable.

Example:

Page 165 of 362


Introduction to Java programming Language

The call to the setFocusable(true) method enables the component focusable.

Picture has a focus listener to visually show changes in the focus (by drawing a red border only when the
component has the focus). 

To the component has a mouse picture to seek the focus while clicking on the picture.

The listener′s mouseClicked method requests for the focus to be transferred to the picture.

Customizing Focus Traversal:

The focus subsystem decides a default order that is applied while the focus traversal keys are used (such as
Tab) to navigate.

The setFocusCycleRoot method use set a focus traversal policy on any container.

Use theisFocusTraversalPolicyProvider() method to determine whether a Container is a focus traversal policy
provider or not.

Use the setFocusTraversalPolicyProvider() method to set a container to provide focus traversal policy.

Tracking Focus Changes to Multiple Components:

Registering a PropertyChangeListener on the KeyboardFocusManager can be done unless a focus listener is
appropriate.

The property change listener is notified of every change involving the focus, including changes to the focus
owner, the focused window, and the default focus traversal policy.

The Focus API:

The focus API falls into four categories:

Useful Methods for Components.

Creating and Using a Custom FocusTraversalPolicy.

Input Verification API.

KeyboardFocusManager Properties.

Page 166 of 362


Introduction to Java programming Language

Useful Methods for Components:

Creating and Using a Custom FocusTraversalPolicy:

Page 167 of 362


Introduction to Java programming Language

Input Verification API:

Page 168 of 362


Introduction to Java programming Language

KeyboardFocusManager Properties.

This table defines the bound properties for KeyboardFocusManager.

A listener can be registered for these properties by calling addPropertyChangeListener.

Page 169 of 362


Introduction to Java programming Language

Page 170 of 362


Introduction to Java programming Language

Graphics Programming

Introduction

The following topics are focused in this chapter:

Java2D Rendering Model

Strokes & Fills

Geometries

Fonts and Text Layout

Transformations

Using Color

Hardware Acceleration and Active Rendering Techniques

Java2D Rendering Model

The Graphics2D object which extends java.awt.Graphics and its state attributes at the same time The Java 2D™
rendering process is restricted through the graphic 2D object.

The Graphics2D state attributes, like line styles and transformations are mainpulated to graphic objects when they
are offered.

Setting the Graphics2D context and then calling one of the Graphics2D rendering methods can give text, shapes or
image like draw or fill.

Interfaces and Classes:

Interfaces:

Composite.

CompositeContext.

Paint.

PaintContext.

Stroke.

Classes:

AffineTransform (java.awt.geom).

AlphaComposite.

BasicStroke.

Color.

GradientPaint.
Page 171 of 362
Introduction to Java programming Language

Graphics2D.

TexturePaint.

Rendering Concepts

To render a graphic object using the Java 2D™ API, setting up the Graphics2D context and pass the graphic object
to one of the Graphics2D rendering methods are needed.

You can modify the state attributes that form the Graphics2D context to:

Vary the stroke width.

Change how strokes are joined together.

Set a clipping path to limit the area that is rendered.

When objects are rendered Translate, rotate, scale, or shear objects.

Define colors and patterns to fill shapes with.

Specify how multiple graphics objects should be composed.

Several methods for adding and modifying attributes in the graphics context are defined by Graphics2D.

The representation of an object is taken a particular attribute, like a Paint or Stroke object.

If you alter an attribute object that is part of the Graphics2D context, you need to call the appropriate set method to
notify the context. 

Rendering Process:

While rendering a graphic object, the geometry, image, and attribute information are combined to calculate
which pixel values must be changed on the display.

The rendering process for a Shape can be broken down into four steps:

If the Shape is to be stroked, the Stroke attribute in the Graphics2D context is used to generate a
new Shape that encompasses the stroked path.

The coordination of the Shape’s path are transformed from user space into the device space according to the
transform attribute in the Graphics2D context.

The Shape’s path is clipped by using the clip attribute in the Graphics2D context.

The remaining Shape, if any, is filled using the Paint and Composite attributes in the Graphics2D context.

Rendering text is similar to rendering a shape.

Images are handled differently; transformations and clipping operations are performed on the image’s bounding
box.

Strokes & Fills

Strokes:

Page 172 of 362


Introduction to Java programming Language

A BasicStroke object is used to define the stroke attributes for Graphics2D context.

It defines characteristics such as the line width, endcap style, segment join­style, and the dashing pattern.

In order to set or change the Stroke attribute in the Graphics2D context, you call setStroke.

The Graphics2D rendering methods adopt the Stroke attribute which
are draw, drawArc, drawLine, drawOval, drawPolygon, drawPolyline, drawRect, and drawRoundRect.

When one of these methods is called, it renders the outline of the specifiedShape is rendered.
The Stroke attribute defines the line characteristics and the Paint attribute defines the color or pattern of the
mark drawn by the pen.

For example, when draw(myRectangle) is called:

The Stroke is applied to the rectangle’s outline.

The stroked outline is converted to a Shape object.

The Paint is applied to the pixels that lie within the contour of the outline Shape.

Specifying Stroke Attributes

To set the stroke width, you create a BasicStroke object with the desired width and call setStroke.

Page 173 of 362


Introduction to Java programming Language

To set the join and endcap styles, you create a BasicStroke object with the desired attributes.

While creating a BasicStroke object, you can specify two parameters that control the dashing pattern:

Dash: an array that represents the dashing pattern.

dash_phase: an offset that defines where the dashing pattern starts.

Fills

The fill attribute in the Graphics2D context a Paint object represents. Addition can be done paint to
the Graphics2D context by calling setPaint.

When a Shape or glyph is drawn, the Paint is applied to the pixels which lie inside the Shape that can represent the
object’s stroked outline.

The Paint is applied to the pixels that lie within the Shape’s contour. When a Shape is filled (Graphics2D.fill).

Simple solid color fills can be set with the setColor method.

To fill Shapes with more complex paint styles such as gradients and textures, use the Java 2D Paint classes
GradientPaint and TexturePaint.

When fill is called to render a Shape, the system:

Determines what pixels comprise the Shape.

Gets the color of each pixel from the Paint object.

Page 174 of 362


Introduction to Java programming Language

Converts the color to an appropriate pixel value for the output device.

Writes the pixel to that device.

Batch Processing

The Java 2D API processes the pixels in batches to steamline.  A batch can be either a contiguous set of pixels
on a given scanline or a block of pixels. This batch processing is executed in two steps:

To create a PaintContext the Paint object’s createContext method is called The PaintContext stores the
contextual about the current rendering operation and the information necessary to generate the colors. User
space and device space are fulled with the bounding boxes of the graphics object. It passes create context
method.

Colours are generated in the colormodel. Using user space into device space transforms the maps.

To get the ColorModel of the generated paint color from the PaintContext the getColorModel method is called.

The getRaster method is then called repeatedly to get the Raster which contains the actual color data for each
batch.

This information is moved to the next stage in the rendering pipeline, which draws the generated color using the
currentComposite object.

Specifying Fill Attributes

The Paint attribute in the Graphics2D context determines the fill color or pattern that is used when text and Shapes
are rendered.

Filling a Shape with a Gradient:

The GradientPaint class provides an easy way to fill a shape with a gradient of one color to another.

To fill a shape with a gradient of one color to another:

Create a GradientPaint object.

Call Graphics2D.setPaint.

Create the Shape.

Call Graphics2D.fill(shape).

For example, a rectangle is filled with a blue­green gradient.

Filling a Shape with a Texture:
Page 175 of 362
Introduction to Java programming Language

The TexturePaint class provides an easy way to fill a shape with a repeating pattern.

To fill a shape with a texture:

Create a TexturePaint object.

Call Graphics2D.setPaint.

Create the Shape.

Call Graphics2D.fill(shape).

Geometries

The Java 2D™ API provides several classes that define common geometric objects, such as points, lines, curves,
and rectangles as part of java.awt.geom package.

The Java 2D API geometries such as GeneralPath, Arc2D, and Rectangle2D implement the Shape interface
defined in java.awt. Shape.

A new interface, PathIterator, defines methods for retrieving elements from a geometry.

Interfaces and Classes:

Interface:

PathIterator.

Shape (java.awt).

Classes:

Arc2D.

Area.

CubicCurve2D.

Dimension2D.

Ellipse2D.

FlatteningPathIterator.

GeneralPath.

Line2D.

Point2D.

QuadCurve2D.

Rectangle2D.

RectangularShape.

RoundRectangle2D.
Page 176 of 362
Introduction to Java programming Language

Geometry Concepts

An implemented shape class of an instant is the shape interface like GeneralPath or Rectangle2D.Float.

A Shape’s contour (outline) is referred to as its path.

A Shape’s path can be also helpful to define a clipping path.

A GeneralPath is a shape that can be used to represent any two­dimensional object that can be constructed from
lines and quadratic or cubic curves.

Constructive Area Geometry:

Constructive Area Geometry (CAG) is the process of creating new geometric objects by performing boolean
operations on existing objects.

In the Java 2D API, a special type of Shape called an Area supports boolean operations. You can construct
an Area from any Shape.

Areas which are supported by the following Boolean operations:

Union.

Intersection.

Subtraction.

Exclusive OR (XOR).

Bounds and Hit Testing.

A fully enclosed geometry is a bounding. It is a box rectangle.

The Shape interface defines two methods for retrieving a shape’s bounding box
namely, getBounds and getBounds2D.

Shape also provides methods for determining whether do or do not:

A specified point lies within the bounds of the shape (contains).

A specified rectangle lies totally within the bounds of the shape (contains).

A specified rectangle intersects the shape (intersects).

Combining Areas to Create New Shapes:

Construct complex Shapes from simple shapes such as circles and squares areas can acute need. To create a new
Page 177 of 362
Introduction to Java programming Language

complex Shape by combining Areas:

Using Shapes, construct the Areas to be combined.

Call the appropriate Boolean operators: add, subtract, intersect, exclusiveOr.

Pear constructed from circles:

The body of the pear is constructed by performing a union operation on two overlapping Areas: a circle and an
oval.

Each leaves are created by performing an intersection on two overlapping circles and then joined into a
single Shape through a union operation.

Overlapping circles are also used to construct the stem through two subtraction operations.

Fonts and Text Layout

The Java 2D API provides text­related classes (Font & TextLayout) which assist fine­grain font control and
sophisticated text layout.

Interfaces and Classes:

Interfaces:

MultipleMaster.

OpenType.

Classes:

Font.

FontRenderContext.

GlyphJustificationInfo.

GlyphMetrics.

GlyphVector.

GraphicAttribute.

ImageGraphicAttribute.

LineBreakMeasurer.

LineMetrics.

ShapeGraphicAttribute.

TextAttribute.

TextHitInfo.

TextLayout.

Page 178 of 362


Introduction to Java programming Language

Font Concepts

An instance of a font face is represented by a Font object.

This font face are taken from the collection of font face available on the system.

The following are the names associated with a Font.

A Font object’s logical name is a name mapped onto one of the specific fonts available on the platform.

A Font object’s family name is the name of the font family which determines the typographic design across
several faces.

A Font objects’ font face name refers to an actual font installed on the system.

Access information about a Font through the getAttributes method.

A LineMetrics object encapsulates the measurement information associated with a Font, such as its ascent,
descent, and leading:

Ascent means the distance from the baseline to the ascender line. 

Descent indicates the distance from the baseline to the descender line.

Leading expresses the recommended distance from the bottom of the descender line to the top of the next line.

Text Layout Concepts:

It must be properly shaped and positioned using the appropriate glyphs and ligatures. This process is referred
to as text layout. The text layout process involves before a piece of text can be displayed.

Shaping text using the appropriate glyphs and ligatures.

Properly ordering the text.

Measuring and positioning the text.

Shaping Text:

A glyph is the visual representation of one or more characters.

The shape, size, and position of a glyph the content holds the authority of different glyphs can be used to
represent a single character or combination of characters, depending on the font and style.

Ordering Text:
Page 179 of 362
Introduction to Java programming Language

Logical order is the storehouse of encoding. This encoding is used as a Unicode character.

No similarities can be found between the logical order and the visual order. In this visual order the
corresponding glyphs are displayed.

The visual order for glyphs in a particular writing system (script) is called the script order.

Measuring and Positioning Text:

Text is always displayed by using multiple fonts and styles, such as bold or italic.

To properly position, measure, and render text, you need to keep track of each individual character and the
style applied to that character using TextLayout.

Supporting Text Manipulation:

To allow the user to edit the text that is displayed, you must be able to:

Display a caret that indicates where new characters will be inserted when the user enters text.

Move the caret and insertion point in response to user input.

Detect user selections (hit detection).

Highlight selected text.

Managing Text Layout:

The TextLayout class supports text that contains multiple styles and characters from different writing systems,
including Arabic and Hebrew.

TextLayout simplifies the process of displaying and measuring text

TextLayout is designed so that there is no significant performance impact when it’s used to display simple,
monodirectional text.

The TextLayout class manages the positioning and ordering of glyphs for you.

You can use TextLayout to:

Lay out monodirectional and bidirectional text.

Display and move carets.

Perform hit testing on text.

Highlight text selections.

Transformations

The Graphics2D context used to transform objects since it has a transform from user space to device space during
rendering.

Rotation or scaling are the additional transformations Graphics2D context allows other transforms to perform
additional transformations.

Page 180 of 362


Introduction to Java programming Language

Graphics2D provides several different ways to modify the transform.

The simplest is to call one of the Graphics2D transformation methods: rotate, scale, shear, or translate.

An AffineTransform performs a linear transformation such as translation, scaling, rotation, or shearing on a set of
graphics primitives. When a transform is concatenated with an existing transform, the last transform specified is the
first to be applied.

To concatenate a transform with the current transform, you pass an AffineTransform toGraphics2D.transform.

The setTransform method overwrites theGraphics2D object’s current transform, which is needed for other
purposes, such as:

Applying a scaling transform to adjust for printer resolution.

Painting a JComponent at non­zero translation from its parent’s origin.

Scaling up a component for easier viewing.

Any other situation in which the supplier of a Graphics2D object might want to transform the rendering for effect.

Affine Transforms:

When AffineTransforms are rendered, they are used to transform text, shapes, and images, You can also apply
transforms to Font objects to create new font derivations.

An affine transformation performs a linear transformation on a set of graphics primitives.

Affine transformations are based on two­dimensional matrices of the following form:

With the effective creation of series or pipeline of transformation, it can be clubbed to geather. This combination
is referred to as concatenation. 

A transform can also be pre­concatenated with an existing transform.

AffineTransform provides a set of convenience methods for constructing AffineTransform objects:

getTranslateInstance.

getRotateInstance.
Page 181 of 362
Introduction to Java programming Language

getScaleInstance.

getShearInstance.

Using Color

Color imaging is one of the fundamental components of any graphics system.

The key color management classes in the Java 2D API are ColorSpace, Color, ColorModel:

Three separate numerical values or components are used for measuring colors a system. This system is
represented by a color space. The ColorSpace class contains methods for converting between the color space
and two standard color spaces, CIEXYZ and RGB.

A Color defined in terms of its components in a particular ColorSpace. It is a fixed color. To draw a Shape in a
color, such as red, you pass a Color object representing that color to the Graphics2D context. Coloris defined in
the java.awt package.

A ColorModel describes a particular way that pixel values are mapped to colors. It is typically associated with
an Image or BufferedImage and provides the information necessary to correctly interpret the pixel
values. ColorModel is defined in the java.awt.image package.

Classes:

ColorSpace.

ICC_ColorSpace.

ICC_Profile.

ICC_ProfileGray.

ICC_ProfileRGB.

Color Concepts

A ColorModel is used for interpreting pixel data in an image.

The ColorModel is associated with an image it encapsulates the data and methods necessary for translating a pixel
value to and from its constituent color components.

Color:

The Java 2D™ API provides two color models in addition to the DirectColorModel and IndexColorModel.

ComponentColorModel can handle an arbitrary ColorSpace and an array of color components to match
the ColorSpace. This model can be used to represent most color models on most types of GraphicsDevices.

PackedColorModel is a base class for models, these models represent pixel values that have their color
components embedded directly in the bits of an integer pixel.

ColorSpace:

A ColorSpace object represents a system for measuring colors, typically using three separate numeric values.

Page 182 of 362


Introduction to Java programming Language

ColorSpace provides methods that transform Colors in a specific color space to and from sRGB and to and from a
well­defined CIEXYZ color space.

All ColorSpace objects must be able to map a color from the represented color space into sRGB and transform
an sRGB color into the represented color space.

The methods used for this process are toRGB and fromRGB:

toRGB transforms a Color in the represented color space to a Color in sRGB.

fromRGB takes a Color in sRGB and transforms it into the represented color space.

Describing Colors:

A description of a color is provided by the color class in a particular color space.

The value of the color components and a ColorSpace object are the integrate part of an instance of Color.

The Color class has a number of methods it supports a proposed standard RGB color space called sRGB.

The ColorSpace class defines the methods toRGB and fromRGB so that developers can easily retrieve colors in
this standard space.

By combining different amounts of red, green, and blue light colors on a computer screen are generated.
Therefore, using an RGB color space is a standard for imaging on computer monitors.

Color Matching:

The API has an accurately specified color At once it must being out that color on an output device as a monitor
or printer. 

Achieving consistent and accurate color requires not only input colors but also output devices be profiled
against a standard color space.

Mapping Colors through sRGB and CIEXYZ:

The Java 2D API speaks of to RGB and CMYK as color space types. A particular model of monitor combined
with its particular phosphors defines its own RGB color space.

The international commission on illumination has determined standards for the device independent specification
of color.

Attaching information to the space is one way to map between color space. This attaching information elobrates

Page 183 of 362


Introduction to Java programming Language

how the device­dependent space relates to the device­ independent space. This additional information is called
a profile.

A commonly used type of color profile is the ICC Color Profile, as defined by the International Color Consortium.

Hardware Acceleration and Active Rendering Techniques

The JDK 1.4 provides access to hardware acceleration for offscreen images, resulting in better performance of
rendering to and copying from these images.

The VolatileImage class allows you to create a hardware­accelerated offscreen image and manage the contents of
that image.

The drawing surface of an image (the memory where the image contents actually reside) can be lost or
invalidated, causing the contents of that memory to go away. The drawing surface thus needs to be restored or
recreated and the contents of that surface need to be re­rendered.

VolatileImage provides an interface for allowing the user to detect these problems and fix them when they occur.

The Component.createVolatileImage or GraphicsConfiguration.createCompatibleVolatileImage(int, int) methods is
useful for creating the image.

Example:

Page 184 of 362


Introduction to Java programming Language

Graphics2D provides rendering methods for Shapes, Text, and Images:

draw—strokes a Shape’s path using the Stroke and Paint objects in the Graphics2D context.

fill—fills a Shape using the Paint in the Graphics2D context.

drawString—renders the specified text string using the Paint in the Graphics2D context.

drawImage—renders the specified image.

Drawing a Shape

The outline of any Shape can be rendered by the Graphics2D.draw method.

When a Shape is drawn, its path is stroked by the Stroke object in the Graphics2D context.

To render outline of shape:

Create a BasicStroke object.

Call Graphics2D.setStroke.

Create the Shape.

Call Graphics2D.draw(shape).

Filling a Shape

The Graphics2D.fill method can be recycled to fill any Shape. When a Shape is filled, the area within its path is
rendered with the Graphics2D context’s current Paint attribute— a Color, TexturePaint, orGradientPaint.

To fill a Shape:

Set the fill color or pattern on the graphics context using Graphics2D.setColor or Graphics2D.setPaint.

Page 185 of 362


Introduction to Java programming Language

Create the Shape.

Call Graphics2D.fill to render the Shape.

Example:

Rendering Text: To render a text string, you call Graphics2D.drawString, passing in the string that you want to
render.

Rendering Images: To render an Image, you create the Image and call Graphics2D.drawImage.

Page 186 of 362


Introduction to Java programming Language

User Interface Components with Swing

Introduction

In this chapter, we will discuss the following topics:

Swing and the Model­View­Controller Design Pattern

Design Patterns

The Model­View­Controller Pattern

A Model­View­Controller Analysis of Swing Buttons

Introduction to Layout Management

Border Layout

Grid Layout

Text Input

Text Fields

Labels and Labeling Components

Password Fields

Text Areas

Scroll Panes

Choice Components

Checkboxes

Radio Buttons

Borders

Combo Boxes

Sliders

Menus

Menu Building

Icons in Menu Items

Checkbox and Radio Button Menu Items

Pop­Up Menus

Keyboard Mnemonics and Accelerators

Page 187 of 362


Introduction to Java programming Language

Enabling and Disabling Menu Items

Toolbars

Tooltips

Sophisticated Layout Management

The Grid Bag Layout

Group Layout

Using No Layout Manager

Custom Layout Managers

Traversal Order

Dialog Boxes

Option Dialogs

Creating Dialogs

Data Exchange

File Dialogs

Color Choosers

The Model­View­Controller Design Pattern

Design Patterns:

Past experience would be a source of inspiration to solve a present problem or you may depend on experts for
advice on what has guided them.

Design patterns are a method for presenting this expertise in a structured way.

The model­view­controller pattern is not the only pattern used in the design of AWT and Swing.

Here are several additional examples:

Containers and components are examples of the “composite” pattern.

The scroll pane is a “decorator.”

Layout managers follow the “strategy” pattern.

One important aspect of design patterns is that they become part of the culture.

Patterns become an efficient way of talking about design problems.

The Model­View­Controller Pattern:

Every component has three characteristics:

Page 188 of 362


Introduction to Java programming Language

Its content, such as the state of a button (pushed in or not), or the text in a text field.

Its visual appearance (color, size, and so on).

Its behavior (reaction to events).

The MVC pattern accomplishes the following principles of object oriented design:

Don´t make one object responsible for too much.

Don’t execute everything by a single button class.

Have the look­and­feel of the component associated with one object and store the content in another object.

Implement three separate classes:

The model, which stores the content.

The view, which displays the content.

The controller, which handles user input.

The pattern specifies precisely how these three objects interact.

The model stores the content and has no user interface.

The model must implement methods to change the content and to explore what the content is.

The controller handles the user­input events, such as mouse clicks and keystrokes. It then decides whether to
translate these events into changes in the model or the view.

A model can have multiple views each shows a different part or aspect of the full content.

In Swing, each user interface component has a wrapper class such as JButton or JTextField that stores the

Page 189 of 362


Introduction to Java programming Language

model and the view.

When you inquiry about the content (the text in a text field), the wrapper class puts forth the model and returns
the answer to you.

When you need to change the view (move the caret position in a text field), the wrapper class forwards that
request to the view.

The model­view­controller pattern is attractive for the Swing designers because it allows them to implement
pluggable look­and­feel implementations.

The model of a button or text field is independent of the look­and­feel—but, the visual representation is
completely dependent on the user interface design of a particular look­and­feel.

The controller can vary as well.

Patterns are only intended as guidance, not as religion. No pattern is applicable in all situations.

A Model­View­Controller Analysis of Swing Buttons:

Interface is called ButtonModel since most components, the model class implements an interface whose name
ends in Model.

Classes implementing that interface can define the state of the various kinds of buttons.

The Swing library contains a single class, called DefaultButtonModel that implements this interface.

Each JButton object stores a button model object which you can retrieve.

There is no way to find out what’s on the face of a button just by looking at its model since the model does not
store the button label or icon.

Page 190 of 362


Introduction to Java programming Language

The same model (namely, DefaultButtonModel) is used for push buttons, radio buttons, checkboxes, and even
menu items, but they have different views and controllers.

Each Swing component has an associated view object that ends in UI.

Introduction to Layout Management:

A Java­enabled development environment will have a layout tool that automates the task of arranging
components inside a frame.

Components are placed inside containers, and a layout manager determines the positions and sizes of the
components in the container.

Buttons, text fields, and other user interface elements extend the class Component. Components can be placed
inside containers, containers such as panels.

Extenton of Component deals with Containers’ placing themselves inside other containers.

Example, the buttons are contained in a JPanel object and are managed by the flow layout manager, the default
layout manager for a panel.

Figure shows what happens when you add more buttons to the panel. A new row is started when there is no more
room. The buttons stay centered in the panel, even when the user resizes the frame.

Page 191 of 362


Introduction to Java programming Language

Though each container has a default layout manager you can always set your own.

For example, the following statement uses the GridLayout class to lay out the components in the panel.
panel.setLayout(new GridLayout(4, 4));

When you add components to the container, the add method of the container licenses the component and any
placement directions to the layout manager.

java.awt.Container 1.0:

void setLayout(LayoutManager m) ­ Sets the layout manager for this container.

Component add(Component c).

Component add(Component c, Object constraints) ­ Adds a component to this container and returns the
component reference.

java.awt.FlowLayout 1.0:

FlowLayout()

FlowLayout(int align)

FlowLayout(int align, int hgap, int vgap) ­ constructs a new FlowLayout.

Border Layout:

The border layout manager is the default layout manager of the content pane of every JFrame.

The border layout manager lets you choose where you want to place each component.

For example: frame.add(component, BorderLayout.SOUTH);

Page 192 of 362


Introduction to Java programming Language

After the edge components are laid out, the remaining available space is occupied by center.

When the container is resized, the dimensions of the edge components remains unchanged, but the center
component changes its size. Add components by specifying a constant CENTER, NORTH, SOUTH, EAST, or
WEST of the BorderLayout class.

The border layout grows all components to fill the available space.

This is a problem when you add a button since it would fill the entire southern region of the frame:
frame.add(yellowButton, BorderLayout.SOUTH);

Use Panels to overcome this problem as:

The output would be:

Page 193 of 362


Introduction to Java programming Language

Grid Layout:

The grid layout arranges all components in rows and columns like a spreadsheet.

All components are given the same size.

In the constructor of the grid layout object, you specify how many rows and columns you need
panel.setLayout(new GridLayout(4, 4));

Add the components, starting with the first entry in the first row, then the second entry in the first row, and so on.

The calculator program in Figure uses a grid layout to arrange the calculator buttons.

When you resize the window, the buttons grow and shrink, but all buttons have identical sizes.

java.awt.GridLayout 1.0

GridLayout(int rows, int columns)

GridLayout(int rows, int columns, int hgap, int vgap) ­ constructs a new GridLayout. One of rows and columns
(but not both) may be zero, denoting an arbitrary number of components per row or column.

Text Input:

Use the JTextField and JTextArea components for text input.

Page 194 of 362


Introduction to Java programming Language

A text field can accept only one line of text; a text area can accept multiple lines of text.

A JPasswordField accepts one line of text without displaying the contents.

All these classes inherit from a class called JTextComponent.

The methods that get or set the text in a text field or text area are actually in JTextComponent.

javax.swing.text.JTextComponent

String getText()

void setText(String text) ­ Gets or sets the text of this text component.

boolean isEditable()

void setEditable(boolean b) ­ Gets or sets the editable property that determines whether the user can edit the
content of this text component.

Text Fields

The usual way to add a text field to a window is to add it to a panel or other container.

This code improves a text field and prepares it by placing the string "Default input" inside it.

The second parameter of this constructor sets the width.

If you expect the inputs to be n characters or less, you are supposed to specify n as the column width.

The number of columns is only an indication to the AWT that gives the desireable size. If the layout manager
needs either to grow or shrink the text field, it can automatically adapt its size.

The column width that you set in the JTextField constructor is not an excessive limit on the number of characters
the user can enter.In spite of typing in a longer strings, the input scrolls when the text exceeds the length of the
field.

To reset the number of columns at runtime, you can do that with the setColumns method.

To make a blank text field, just leave out the string as a parameter for the JTextField constructor: JTextField
textField = new JTextField(20);
Page 195 of 362
Introduction to Java programming Language

Change the content of the text field at any time by using the setText method: textField.setText("Hello!");

To trim any extraneous leading and trailing spaces from the data in a text field, apply the trim method to the return
value of getText: String text = textField.getText().trim();

To change the font in which the user text appears, use the setFont method.

Labels and Labeling Components:

Labels are components that hold text.

They have no decorations (for example, no boundaries).

They also do not react to user input.

Labels can be used to identify components.

To label a component which does not come with an identifier:

Construct a JLabel component with the correct text.

Place it closely to the component you want to identify so that the user can see that the label identifies the
correct component.

The constructor for a JLabel lets you specify the initial text or icon and, optionally, the alignment of the content.

Specify a right­aligned label either as,

The setText and setIcon methods let you set the text and icon of the label at runtime.

Labels can be positioned inside a container like any other component.

Password Fields:

Password fields are a special kind of text field.

Restricting nosy bystanders from seeing your password needs the characters that the user enters are
represented by an echo character, typically an asterisk (*).

Swing supplies a JPasswordField class that implements such a text field.

Is another example of the power of the model­view­controller architecture pattern.

Does the same model to store the data as a regular text field, but its view have been changed to display all
characters as echo characters?

javax.swing.JPasswordField:

JPasswordField(String text, int columns) ­ Constructs a new password field.
Page 196 of 362
Introduction to Java programming Language

void setEchoChar(char echo) ­ Sets the echo character for this password field. A value of 0 resets the
echo character to the default.

char[] getPassword() ­ Returns the text contained in this password field.

Text Areas:

You can use the JTextArea component to collect user input that is more than one line long.

When you place a text area component in your program, a user can enter any number of lines of text, using the
Enter key to separate them. Each line ends with a ´\n´.

In the constructor for the JTextArea component, specify the number of rows and columns for the text area.

For example: textArea = new JTextArea(8, 40); // 8 lines of 40 columns each.

You can also use the setColumns method to change the number of columns, and the setRows method to change
the number of rows.

Scroll Panes:

If you want scrollbars in a text area, you have to place the text area inside a scroll pane.

The scroll pane now manages the view of the text area.

Scrollbars automatically appear if there is more text than the text area can display, and they vanish again if text is
deleted and the remaining text fits inside the area.

Choice Components: Checkboxes

If you want to collect just a "yes" or "no" input, use a checkbox component.

Checkboxes automatically come with labels that identify them.

The user can check the box by clicking inside it and turn off the checkmark by clicking inside the box again.

Pressing the space bar while the focus is in the checkbox also toggles the checkmark.

Page 197 of 362


Introduction to Java programming Language

Give the label text in the constructor: bold = new JCheckBox("Bold");

Use the setSelected method to turn a checkbox on or off: bold.setSelected(true);

The isSelected method then retrieves the current state of each checkbox.

It is false if unchecked, true if checked.

When the user clicks on a checkbox, this triggers an action event. You attach an action listener to the checkbox.

Radio Buttons:

Most situations we ask the user to check only one of several boxes.

When another box is checked, the previous box is automatically unchecked. Such a group of boxes is often called
a radio button group.

When you push in one button, the previously depressed button pops out.

To implement radio buttons, you construct one object of type ButtonGroup for every group of buttons and add
objects of type JRadioButton to the button group.

When a new button is clicked, the button group object is responsible for turning off the previously set button when
a new button is clicked.

The button group controls only the behaviour of the buttons; grouping the buttons for layout purposes needs to be
added them to a container such as a JPanel.

Page 198 of 362


Introduction to Java programming Language

When the user checks a radio button, the button generates an action event.

Borders:

You wish to visually indicate which buttons are grouped among multiple groups of radio buttons in a window.
Swing provides a set of useful borders for this purpose.

You can apply a border to any component that extends JComponent.

Steps to implement borders:

Call a static method of the BorderFactory to create a border. You can choose among the following styles:

Lowered bevel:

Raised bevel

Etched

Line

Matte

Empty (just to create some blank space around the component)

Page 199 of 362


Introduction to Java programming Language

Add a title to your border by passing your border to BorderFactory.createTitledBorder.

Combine several borders with a call to BorderFactory.createCompoundBorder.

Add the resulting border to your component by calling the setBorder method of the JComponent class.

Combo Boxes:

Radio buttons are not a good choice for many alternatines because they occupy too much screen space. Instead,
you can use a combo box.

When the user clicks on this component, a list of choices drops down, and the user can then select one of them.

If the drop­down list box is set to be editable, then you can edit the current selection as if it were a text field.

The JComboBox class provides a combo box component.

The JComboBox class is a generic class.

Call the setEditable method to make the combo box editable.

Obtain the current selection by calling the getSelectedItem method.

Page 200 of 362


Introduction to Java programming Language

To add a string to the end of the list,

You can add new items anywhere in the list with the insertItemAt method:

To remove items,

The removeAllItems method removes all items at once.

Sliders

Sliders offer a choice from a continuum of values.

For example, any number between 1 and 100.

The most common way of constructing a slider is given below:

Page 201 of 362


Introduction to Java programming Language

If you want the slider to be vertical, use the following constructor call:

As the user slides the slider bar, the value of the slider moves between the minimum and the maximum values.
When the value changes, a ChangeEvent is sent to all change listeners.

Call the addChangeListener method to be noted on the change and install an object that implements the
ChangeListener interface that has a single method, stateChanged.

Menus:

Page 202 of 362


Introduction to Java programming Language

Swing also supports another type of user interface element—the pull­down menus that are familiar from GUI
applications.

A menu bar at the top of a window contains the names of the pull­down menus. Clicking on a name opens the
menu containing menu items and submenus. When the user clicks on a menu item, all menus are closed and a
message is sent to the program.

Menu Building: Building menus is certainly straightforward.

Create a menu bar:

For each menu, you create a menu object:

Add the top­level menus to the menu bar:

Add menu items, separators, and submenus to the menu object:

Page 203 of 362


Introduction to Java programming Language

When the user selects a menu, an action event is triggered. You need to install an action listener for each
menu item:

The add method returns the created menu item, you can capture it and then add the listener, as follows:

For example:

You can then add the action to the menu:

Icons in Menu Items:

Menu items are very similar to buttons.

Just like buttons, menus can have just a text label, just an icon, or both respectively.

Page 204 of 362


Introduction to Java programming Language

You can specify the icon either with the JMenuItem(String, Icon) or JMenuItem(Icon) constructor, or you can set it
with the setIcon method that the JMenuItem class inherits from the AbstractButton class.

By default, the menu item text is placed to the right of the icon.

To place the text on the left, call the setHorizontalTextPosition method that the JMenuItem class inherits from the
AbstractButton class:

To add an icon to an action:

To set the icon in the AbstractAction constructor:

Checkbox and Radio Button Menu Items:

Checkbox and radio button menu items pageant a checkbox or radio button next to the name.

When the user selects the menu item, the item automatically toggles between checked and unchecked.

To create a checkbox menu item:

Automatic deselection of radio button is resulted when one of the radio button is selected.

Page 205 of 362


Introduction to Java programming Language

Use the isSelected method to test the current state of the menu item.

Pop­Up Menus:

A pop­up menu is a menu that is not attached to a menu bar but floats somewhere.

Create a pop­up menu just as you create a regular menu, except that a pop­up menu has no title:

Add your menu items as usual:

You must explicitly display a pop­up menu by using the show method. Specify the parent component and the
location of the pop­up, using the coordinate system of the parent.

To pop up a menu when the user clicks on a component, using the pop­up trigger, simply call the method

Page 206 of 362


Introduction to Java programming Language

Keyboard Mnemonics and Accelerators:

It is a real convenience for the experienced user to select menu items by keyboard mnemonics. You can create a
keyboard mnemonic for a menu item by specifying a mnemonic letter in the menu item constructor: JMenuItem
aboutItem = new JMenuItem("About", ´A´);

The keyboard mnemonic is displayed automatically in the menu, with the mnemonic letter Underlined.

For example, the items of the last example the label will be displayed as “About” with an underlined letter
“A”.When the menu is displayed, the user just needs to press the A key, and the menu item is selected.

You can specify which character you want to have underlined by calling the setDisplayedMnemonicIndex method.

To attach a mnemonic to a menu, call the setMnemonic method:

Accelerators are keyboard shortcuts that let you select menu items without even opening a menu.

Use the setAccelerator method to attach an accelerator key to a menu item.

The setAccelerator method takes an object of type Keystroke.

For example, the following call attaches the accelerator Ctrl+O to the openItem menu item:

Page 207 of 362


Introduction to Java programming Language

openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));

Accelerator keys directly fire the action event associated with a menu.

Enabling and Disabling Menu Items:

Occasionally, a particular menu item should be selected only in certain contexts.

It is better to deactivate the menu items that lead to temporarily inappropriate commands.

A deactivated menu item is shown in gray hence it cannot be selected.

To enable or disable a menu item, use the setEnabled method:saveItem.setEnabled(false);

The javax.swing.event package defines a MenuListener interface with three methods:

void menuSelected(MenuEvent event)

void menuDeselected(MenuEvent event)

void menuCanceled(MenuEvent event)

The menuSelected method is called before the menu is displayed. It can therefore be used to disable or enable
menu items.

Example: The following code shows how to disable the Save and Save As actions whenever the Read Only
checkbox menu item is selected.

Toolbars:

A toolbar is a button bar. It gives quick access to the most commonly used commands in a Program.

You can drag the toolbar to one of the four borders of the frame. When you release the mouse button, the toolbar
is dropped into the new location.
Page 208 of 362
Introduction to Java programming Language

The toolbar can even be completely detached from the frame. A detached toolbar is delimited in its own frame.
When you close the frame having a detached toolbar, the toolbar jumps back into the original frame.

To add components into the toolbar:

To populate the toolbar with Action objects: bar.add(blueAction);

You can separate groups of buttons with a separator: bar.addSeparator();

To have a toolbar start out vertical, use:

Tooltips:

A disadvantage of toolbars is that users are often mystified by the meanings of the tiny icons in toolbars. To solve
this problem, user interface designers invented tooltips.

A tooltip is activated when the cursor rests for a moment over a button.

The tooltip text is displayed inside a coloured rectangle.

When the user moves the mouse away, the tooltip disappears.

Page 209 of 362


Introduction to Java programming Language

You can add tooltips to any JComponent simply by calling the setToolTipText method:
exitButton.setToolTipText("Exit");

In Action objects, you associate the tooltip with the SHORT_DESCRIPTION key:
exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");

Sophisticated Layout Management:

Since Java 1.0, the AWT includes the grid bag layout that lays out components in rows and columns.

The row and column sizes are flexible, and components can span multiple rows and columns. In spite of being
very flexible layout manager is very complex.

In 2005, the NetBeans team invented the Matisse technology, which combines a layout tool and a layout manager.

A user interface designer uses the tool to drop components into a container and to indicate which components
should line up.

The tool translates the designer’s intentions into instructions for the group layout manager. This is much more
convenient than writing the layout management code by hand.

The Grid Bag Layout

The grid bag layout is the pioneer of all layout managers.

In a grid bag layout, the rows and columns can have variable sizes.

You can join adjacent cells to make room for larger components.

The components need not fill the entire cell area, and you can specify their alignment within cells.

Page 210 of 362


Introduction to Java programming Language

To describe the layout to the grid bag manager, use the following procedure:

Create an object of type GridBagLayout.

Set this GridBagLayout object to be the layout manager for the component.

For each component, create an object of type GridBagConstraints. Set field values of the GridBagConstraints
object to specify how the components are laid out within the grid bag.

Finally, add each component with its constraints by using the call add(component,constraints);

Example :

The gridx, gridy, gridwidth, and gridheight Parameters:

The gridx, gridy, gridwidth, and gridheight constraints define where the component is located in the grid.

The gridx and gridy values specify the column and row positions of the upper left corner of the component to
be added.

The gridwidth and gridheight values determine how many columns and rows the component occupies.

The grid coordinates start with 0. gridx = 0 and gridy = 0 denotes the top left corner.

Weight Fields:

Always need to set the weight fields (weightx and weighty) for each area in a grid bag layout.

Page 211 of 362


Introduction to Java programming Language

If you fix the weight as 0, the area never grows or shrinks beyond its initial size in that direction.

If you set the weights for all areas as 0, the container will huddle in the center of its allotted area instead of
stretching to fill it.

The row and column weights are computed as the maxima of the cell weights in each row or column.

The fill and anchor Parameters:

When there is no need for the component to stretch out and fill the entire area, set the fill constraint.

The four possibilities for this parameter are GridBagConstraints.NONE, GridBagConstraints.HORIZONTAL,
GridBagConstraints.VERTICAL, and GridBagConstraints.BOTH.

If the component does not fill the entire area, you can specify where in the area you want it by setting the
anchor field.

The valid values are GridBagConstraints.CENTER (the default), GridBagConstraints.NORTH,
GridBagConstraints.NORTHEAST, GridBagConstraints.EAST, and so on.

Padding:

Set the insets field of GridBagConstraints to surround a component with additional blank space.

The external padding is termed in a such a way while setting the left, top, right and bottom values of the Insets
object to the amount of space that you want to have around the component.

Alternative Method to Specify the gridx, gridy, gridwidth, and gridheight Parameters:

Instead of setting the gridx and gridy values to absolute positions, you set them to the constant
GridBagConstraints.RELATIVE.

Add the components to the grid bag layout in a standardized order, going from left to right in the first row, then
moving along the next row, and so on.

Specify the number of rows and columns spanned, by giving the appropriate gridheight and gridwidth fields.

If the component continues till the last row or column, you don’t need to specify the actual number, but the
constant GridBagConstraints.REMAINDER. This tells the layout manager that the component is the last one in
its row.

A Helper Class to Tame the Grid Bag Constraints:

The most tedious aspect of the grid bag layout is writing the code that sets the constraints.

We can write helper functions or a small helper class for this purpose.

This class has the following features:

Its name is short: GBC instead of GridBagConstraints.

It extends GridBagConstraints, so you can use shorter names such as GBC.EAST for the constants.

Use a GBC object when adding a component, such as: add(component, new GBC(1, 2));

Page 212 of 362


Introduction to Java programming Language

There are two constructors to set the most common parameters: gridx and gridy, or gridx, gridy, gridwidth, and
gridheight: add(component, new GBC(1, 2, 1, 4));

There are convenient setters for the fields that come in x/y pairs: add(component, new GBC(1,
2).setWeight(100, 100));

The setter methods return this, so you can chain them: add(component, new GBC(1,
2).setAnchor(GBC.EAST).setWeight(100, 100));

The setInsets methods construct the Insets object for you. To get one­pixel insets, simply: Call
add(component, new GBC(1, 2).setAnchor(GBC.EAST).setInsets(1));

Group Layout:

Points regarding the Matisse GUI builder in NetBeans.

Start a new project and add a new JFrame form. Drag a label until two guidelines appear that separate it from
the container borders.

Drag a text field so that its baseline lines up with the baseline of the first label.

Line up a password field with the label to the left and the text field above.

Components are systematized by placing them into objects of type GroupLayout.SequentialGroup or
GroupLayout.ParallelGroup.

These classes are subclasses of GroupLayout.Group.

The various add methods of the group classes return the group object, so that method calls can be chained like
this:

Using No Layout Manager:

Many times when you have no botheration with layout managers but still just want to drop a component at a fixed
location.

To place a component at a fixed location follow the below steps:

Set the layout manager to null.

Add the component you want to the container.
Page 213 of 362
Introduction to Java programming Language

Specify the position and size that you want:

Custom Layout Managers:

You can project your own LayoutManager class.That clss manages components in a special way.

The own layout manager must implement the LayoutManager interface and override the following five methods:

Traversal Order:

When a window is first displayed, the first component in the traversal order has the keyboard focus.

Each time the user presses the Tab key, the next component gains attention.

The traversal order is straightforward: first, left to right, and then, top to bottom.

For example, in the font dialog example, the components are traversed in the following :

Face combo box

Sample text area (press Ctrl+Tab to move to the next field; the Tab character is considered text input)

Size combo box

Bold checkbox

Italic checkbox

Page 214 of 362


Introduction to Java programming Language

Dialog Boxes:

Option Dialogs:

Swing has a set of ready­made simple dialogs that suffice to ask the user for a single piece of information.

The JOptionPane has four static methods to show these simple dialogs:

ShowMessageDialog ­ Show a message and wait for the user to click OK

ShowConfirmDialog ­ Show a message and get a confirmation(like OK/Cancel)

ShowOptionDialog ­ Show a message and get a user option from a set of option

ShowInputDialog ­ Show a message and get one line of user input

The input dialog has an additional component for user input. This can be a text field into which the user can
type an arbitrary string, or a combo box from which the user can select one item.

The icon on the left side depends on one of five message types:

ERROR_MESSAGE

INFORMATION_MESSAGE

WARNING_MESSAGE

QUESTION_MESSAGE

PLAIN_MESSAGE ­ Has no icon.

For each dialog type, you can specify a message.

Here is how the message object is displayed:

Page 215 of 362


Introduction to Java programming Language

String ­ Draw the string

Icon ­ Show the icon

Component ­ Show the component

Object[] ­ Shoe all objects in the array,stacked on top of each other

Any other object ­ Apply toString and show the resulting string

The buttons at the bottom depend on the dialog type and the option type.

When calling showMessageDialog and showInputDialog, you get only a standard set of buttons

When calling showConfirmDialog, you can choose among four option types:

DEFAULT_OPTION

YES_NO_OPTION

YES_NO_CANCEL_OPTION

OK_CANCEL_OPTION

The showConfirmDialog and showOptionDialog return integers to indicate which button the user chose.

For the confirmation dialog, the return value can be one of the following:

OK_OPTION

CANCEL_OPTION

YES_OPTION

NO_OPTION

CLOSED_OPTION

Creating Dialogs

To implement a dialog box, you extend the JDialog class.

This is essentially the same process as extending JFrame for the main window for an application.

In the constructor of your dialog box, call the constructor of the superclass JDialog.
Page 216 of 362
Introduction to Java programming Language

Add the user interface components of the dialog box.

Add the event handlers.

Set the size for the dialog box.

When you call the superclass constructor, you will need to supply the owner frame, the title of the dialog, and
the modality.

Where the dialog is displayed is controled by the owner frame .You can supply null as the owner, then, the
dialog is owned by a hidden frame.

Data Exchange:

The most common reason to put up a dialog box is to get information from the user.

The dialog box should provide methods to set default data.

For example, the PasswordChooser class of the example program has a method, setUser, to place default
values into the next fields:

Show the dialog by calling setVisible (true). The dialog is now displayed.

The user then fills in the information and clicks the OK or Cancel button.

The event handlers for both buttons call setVisible (false), which terminates the call to setVisible (true).

The default button is specially marked, often with a thick outline.

Set the default button in the root pane of the dialog: dialog.getRootPane().setDefaultButton(okButton);

File Dialogs:

Page 217 of 362


Introduction to Java programming Language

A JFileChooser is provided by swing class that allows you to display a file dialog box similar to the one that most
native applications use.

JFileChooser dialogs are always modal.

The JFileChooser class is not a subclass of JDialog.

Instead of calling setVisible(true), call showOpenDialog to display a dialog for opening a file, or call
showSaveDialog to display a dialog for saving a file.

The button for accepting a file is then automatically labeled Open or Save. You can also supply your own
button label with the showDialog method.

Steps to put up a file dialog box and recover what the user chooses from the box:

Make a JFileChooser object. Unlike the constructor for the JDialog class, you do not supply the parent
component. This allows you to reuse a file chooser dialog with multiple frames. For example: JFileChooser
chooser = new JFileChooser();

Set the directory by calling the setCurrentDirectory method. For example, to use the current working
directory:chooser.setCurrentDirectory(new File("."));

If you have a default file name to be choosen by the user supply it with the setSelectedFile method:
chooser.setSelectedFile(new File(filename));

To enable the user to select multiple files in the dialog, call the setMultiSelectionEnabled method:
chooser.setMultiSelectionEnabled(true);

If you want to restrict the display of files in the dialog to those of a particular type, you need to set a file filter.

By default, a user can select only files with a file chooser. If you want the user to select directories, use the
Page 218 of 362
Introduction to Java programming Language

setFileSelectionMode method. Call it with JFileChooser.FILES_ONLY (the default),
JFileChooser.DIRECTORIES_ONLY, or JFileChooser.FILES_AND_DIRECTORIES.

Show the dialog box by calling the showOpenDialog or showSaveDialog method. You must supply the parent
component in these calls:int result = chooser.showOpenDialog(parent); or int result =
chooser.showSaveDialog(parent);

Get the selected file or files with the getSelectedFile() or getSelectedFiles() method. These methods return
either a single File object or an array of File objects: String filename = chooser.getSelectedFile().getPath();

Color Choosers:

Swing makes available a chooser, the JColorChooser.

Use it to let users pick a color value.

Like the JFileChooser class, the color chooser is a component, not a dialog, but it contains convenience
methods to create dialogs that contain a color chooser component.

To show a modal dialog with a color chooser:Color selectedColor = JColorChooser.showDialog(parent,title,
initialColor);

Alternatively, you can display a modeless color chooser dialog.

Supply the following:

A parent component

Page 219 of 362


Introduction to Java programming Language

The title of the dialog

A flag to select either a modal or a modeless dialog

A color chooser

Listeners for the “OK” and “Cancel” buttons (or null if you don’t want a listener)

Page 220 of 362


Introduction to Java programming Language

Deploying Applets and Applications

Introduction

The following topics are discussed in this chapter:

Applet Basics

The Applet HTML Tags and Attributes

Multimedia

The Applet Context

Inter­Applet Communication

Displaying Items in the Browser

Java Web Start

The Sandbox

Signed Code

The JNLP API

Storage of Application Preferences

Property Maps

The Preferences API

Applet Basics

Applets are Java programs.

These java programs are included in an HTML page.

The HTML page must tell the browser which applets to load and where to put each applet on the web page.

The tag needed to use an applet must tell the browser where to get the class files, and how the applet is
positioned on the web page.

The browser then retrieves the class files from the Internet (or from a directory on the user’s machine) and
automatically runs the applet.

A Simple Applet:

An applet is simply a Java class that extends the java.applet.Applet class.

All of our applets will extend the Applet class, the superclass for all applets.

Example:

Page 221 of 362


Introduction to Java programming Language

To execute the applet,the following two steps to be followed:

Compile your Java source files into class files.

Create an HTML file that conveys the browser which classfile to be loaded first and how to size the applet.

Here are the contents of an example file:

To use the applet viewer with our example, enter the following on the command line:

If your HTML file contains multiple applet tags, the applet viewer pops up multiple windows.

To properly view the applet, simply load the HTML file into the browser.

Page 222 of 362


Introduction to Java programming Language

The applet HTML Tag and Its Attributes:

Example applet:

The code attribute gives the name of the class file and include the .class extension.

The width and height attributes size the window that will hold the applet.

A matching   tag that marks the end of the HTML tagging needed for an applet.

The text between the   and   tags is displayed only if the browser cannot show


applets.

The code, width, and height attributes are required. If any thing is missing, the browser cannot load your
applet.

You can use the following attributes within the applet tag:

width, height ­ These attributes are required. It gives the width and height of the applet, measured in pixels.

align ­ This attribute specifies the alignment of the applet. The attribute values are the same as for the align
attribute of the HTML img tag.

vspace, hspace ­ These optional attributes specify the number of pixels above and below the applet
(vspace) and on each side of the applet (hspace).

code ­ This attribute gives the name of the applet’s class file. This name is taken relative to the codebase
or relative to the current page if the codebase is not specified. The path name must match the package of
the applet class.

codebase ­ This optional attribute is a URL for locating the class files. You can use an absolute URL, even
to a different server.
Page 223 of 362
Introduction to Java programming Language

archive ­ This optional attribute lists the JAR file or files containing classes and other resources for the
applet. These files are drawn from the web server before the applet is loaded. This technique speeds up
the loading process significantly because only one HTTP request is necessary to load a JAR file containing
many smaller files. The JAR files are separated by commas.

object ­ This tag lets you specify the name of a file that contains the serialized applet object. When you use
this attribute, the init method is not called, but the applet’s start method is called. Before serializing an
applet object, you should call its stop method.

name ­ To access an applet from JavaScript essentially a name has to be given. You can then refer to the
object as document.applets.appletname. The name attribute is also essential when you want two applets
on the same page to communicate with each other directly.

alt ­ Java may be deactivated in the browser, perhaps by a paranoid system administrator. You can then
use the alt attribute to display a message to the user. Unless browser can process applets at all, it ignores
the unknown applet and param tags. All text between the   and   tags is
displayed by the browser.

Multimedia

Applets can handle multimedia objects like images and audio.

Images must be in GIF, PNG, or JPEG form, audio files in AU, AIFF, WAV, or MIDI. Animated GIFs are
supported, and then the animation is displayed.

Specify the locations of image and audio files with relative URLs.

The base URL is usually obtained by calling the getDocumentBase or getCodeBase method. The former gets
the URL of the HTML page in which the applet is contained, the latter the URL of the applet’s codebase
directory.

Give the base URL and the file location to the getImage or getAudioClip method.

For example:

Page 224 of 362


Introduction to Java programming Language

To play an audio clip, simply invoke its play method: play(getCodeBase(), "audio/meow.au");

The Applet Context:

An applet calls the getAppletContext method to communicate with the browser,

It returns an object that implements an interface of type AppletContext.

Inter­Applet Communication:

If a web page contains multiple applets of the same codebase, intercommunication among each applets is
very easily taken place.

You can use the getApplet method of the AppletContext interface to get a reference to the applet.

For example, If your HTML file contains the tag

Then the following call gives you a reference to the applet:

You can also list all applets on a web page, whether or not they have a name at­tribute.

The getApplets method returns an enumeration object.

Displaying Items in the Browser:

You have access to two areas of the ambient browser which are the status line and the web page display
area.

Both use methods of the AppletContext interface.

You can display a string in the status line at the bottom of the browser with the showStatus message.

For example: showStatus("Loading data . . . please wait");

Page 225 of 362


Introduction to Java programming Language

You can tell the browser to show a different web page with the showDocument method.

Opening of a new window with the document by the browser depends on the supplying the special string
“_blank”

Java Web Start:

Java Web Start is coined to term a technology for delivering applications over the Internet.

Java Web Start applications show the following salient features:

They are typically delivered through a browser. Once a Java Web Start application has been downloaded, it
can be started without using a browser.

They do not exist inside a browser window. The application is displayed in its own frame, outside the
browser.

They do not use the Java implementation of the browser. The browser simply launches an external
application whenever it loads a Java Web Start application descriptor. That is the same mechanism used to
launch other helper applications such as Adobe Acrobat or RealAudio.

Digitally signed applications can be given arbitrary access rights on the local machine. Unsigned
applications run in a “sandbox,” which prohibits potentially dangerous operations.

To prepare an application for delivering Java Web Start, pack it in one or more JAR files.

Prepare a descriptor file in the Java Network Launch Protocol (JNLP) format. Place these files on a web
server.

Ensure that your web server reports a MIME type of application/x­java­jnlp­file for files with extension .jnlp.

To use Java Web Start to deliver the calculator application, follow following the steps:

Page 226 of 362


Introduction to Java programming Language

Compile the program:

Produce a JAR file with the command:

Prepare the launch file Calculator.jnlp with the following contents:

If you use Tomcat, make a directory tomcat/webapps/calculator, where tomcat is the base directory of your
Tomcat installation. Make a subdirectory tomcat/webapps/calculator/WEBINF, and place the following
minimal web.xml file inside the WEB­INF subdirectory:

Place the JAR file and the launch file on your web server so that the URL matches the codebase entry in
the JNLP file. If you use Tomcat, put them into the tomcat/webapps/calculator directory.

Make sure that your browser has been configured for Java Web Start by checking that the application/x­

Page 227 of 362


Introduction to Java programming Language

java­jnlp­file MIME type is associated with the javaws application.

Start Tomcat.

Point your browser to the JNLP file. For example, if you use Tomcat, go to
http://localhost:8080/calculator/Calculator.jnlp.

You should see the launch window for Java Web Start.

Soon afterward, the calculator should come up, with a border marking it as a Java Application.

When you access the JNLP file again, the application is retrieved from the cache. You can review the cache
content by using the Java Plug­in control panel.

The Sandbox

A security manager checks access to all system resources. By default, it only allows those operations that
are harmless.

The code must be digitally signed and the user must consent for signing certificate to allow additional
operation.

The restricted execution environment is often called the “sandbox.”

Code that plays in the sandbox cannot alter the user’s system or spy on it.

Programs in the sandbox are restricted with the following

They can never run any local executable program.

They cannot read from or write to the local computer’s file system.

Finding out any information about the local computer is not certainly possible, except for the Java version
used and a few harmless operating system details.

Interiorly loaded programs need user consent to communicate with any host other than the server from

Page 228 of 362


Introduction to Java programming Language

which they were downloaded; that server is called the originating host.

A warning message carried by pop­up windows is a security feature to ensure that users do not mistake
the window for a local application.

Signed Code

The sandbox restrictions are very restrictive that it cannot be used in many situations.

An application can simply request to have all permissions of a desktop application, and quite a few Java
Web Start applications do just that.

This is accomplished by adding the following tags to the JNLP file:

The JAR files of a Java Web Start application must be digitally signed, if one wants to run outside the
sandbox.

Carring JAR file a signed certificate indicates the identity of the signer. Cryptographic techniques ensure
that such a certificate cannot be forged, and that any effort to tamper with the signed file will be detected.

The JNLP API:

The JNLP API allows unsigned applications to run in the sandbox and at the same time access local
resources in a secure way.

The API provides the following services:

Loading and saving files

Accessing the clipboard

Printing

Downloading a file

Displaying a document in the default browser

Storing and retrieving persistent configuration information

Ensuring that only a single instance of an application executes

To access a service, use the ServiceManager, like this:

Page 229 of 362


Introduction to Java programming Language

Non availability of service leads to the call throwing an UnavailableServiceException.

To save a file, one need to provide suggestions for the initial path name and file extensions for the file
dialog, the data to be saved, and a suggested file name.

For example: service.saveFileDialog(".", new String[] { "txt" }, data, "calc.txt");

Storage of Application Preferences:

Expectation of the application users are generally like saving of preferences and customizations and later
restored when the application twitches again.

Property Maps:

A property map is a data structure.It stores key/value pairs.

Property maps are certainly helpful for storing configuration information.

Property maps have three particular characteristics:

The keys and values are strings.

The set can easily be saved to a file and loaded from a file.

There is a secondary table for default values.

The Java class that implements a property map is called Properties. For example:

Use the store method to save this list of properties to a file.

To load the properties from a file, use

Page 230 of 362


Introduction to Java programming Language

The Preferences API:

Usage of property files has these disadvantages:

Having no concept of a home directory makes some operating systems difficult to find a uniform location
for configuration files.

Non standard convention for naming configuration files increase the likelihood of name clashes as users
install multiple Java applications.

The Preferences class provides a central repository for configuration information in a platform­independent
manner.

The Preferences repository has a tree structure, with node path names such as /com/mycompany/myapp.

Each node in the repository has a separate table of key/value pairs that you can use to store numbers,
strings, or byte arrays.

Numbers, strings, or byte arrays.

There are multiple parallel trees.

Each program user has one tree; an additional tree, called the system tree, is available for settings which
are common to all users.

To access a node in the tree, start with the user or system root: Preferences root = Preferences.userRoot();

To access the node, provide a node path name: Preferences node =
root.node("/com/mycompany/myapp");

Once you have a node, you can access the key/value table with methods

Page 231 of 362


Introduction to Java programming Language

Exceptions and Debugging

Introduction

Java uses a form of error trapping called, Exception handling.

Exception handling in Java is similar to that of C++ or Delphi.

The first part of this chapter covers Java exceptions.

The second part of this chapter elaborates how to use the assertion facility for selectively activating checks.

When your program does the wrong thing, requirement may be araised for recording for later analysis.

The third part of this chapter discusses the standard Java logging framework.

To sum up Tips on how to get useful information out of a running Java application, and how to use an IDE
debugger are given priority.

Dealing with Errors:

While a Java program is running if an error occurs which make the java programming as incomplete, the
program ought to either

Return to a safe state and enable the user to execute other commands or

Allow the user to save all work and terminate the program gracefully.

Java consents every method an alternative exit path if it is unable to complete its task in the normal way. In
this situation, the method does not return a value.

Instead, it throws an object that encapsulates the error information.

The mission of exception handling remains to transfer control from where the error occurred to an error
handler that can deal with the situation.

Points to be pondered.

User input errors: Besides the inevitable typos some users like to use their own trail instead of following
directions. For example, If a user asks to connect to a URL which is syntactically wrong. Your code should
check the syntax, but suppose it does not. Then the network layer will complain.

Device errors: Hardware does not always do what you want it to. The printer may be turned off. A web
page may be temporarily unavailable. Devices will often fail in the middle of a task. For example, a printer
may run out of paper during printing.

Physical limitations: Disks can fill up; you can run out of available memory.

Code errors: A method may not perform correctly. For example, it could deliver wrong answers or use other
methods incorrectly. Computing an invalid array index, trying to find a non­existent entry in a hash table, or
trying to pop an empty stack are all examples of a code error.

Page 232 of 362


Introduction to Java programming Language

The Classification of Exceptions:

An exception object is always an instance of a class derived from Throwable.

The Error hierarchy describes internal errors and resource exhaustion situations inside the Java runtime
system.

Any exception that either derives from the class Error or the class RuntimeException is an unchecked
exception.

All other exceptions are called checked exceptions.

When doing Java programming, your focus is on the Exception hierarchy.

The Exception hierarchy also splits into two branches namely Exceptions that derive from Runtime Exception
and those that do not.

The general rule is a RuntimeException happens because you made a programming error. Any other
exception occurs because a bad thing, such as an I/O error, happened to your otherwise good program.

Declaring Checked Exceptions:

A Java method can have an exception if it encounters a situation it cannot handle.

For example, If a code tries to read from a file, the file might not exist or that it might be empty. The code that
tries to process the information in a file therefore will need to notify the compiler that it can throw some sort of
IOException.

Advertising place can throw your method an exception which is the header of the method.

The header changes to reflect the checked exceptions the method can throw.

If a method might throw more than one checked exception type, you must list all exception classes in the
header.

public FileInputStream(String name) throws FileNotFoundException

Page 233 of 362


Introduction to Java programming Language

An exception is thrown in any of the following four situations:

calling a method throws a checked exception—for example, the FileInputStream constructor.

Detecting an error tends to throw a checked exception with the throw statement.

You make a programming error, such as a[­1] = 0 that gives rise to an unchecked exception.

An internal error occurs in the virtual machine or runtime library.

You should not advertise unchecked exceptions inheriting from RuntimeException.

When a method in a class declares that it throws an exception that is an instance of a particular class, then
it may throw an exception of that class or of any of its subclasses.

How to Throw an Exception:

Example, You have a method, readData that is reading in a file whose header promised content­length: 1024.
But you could get an end of file after 733 characters.

You can throw an exception as follows:

In the above program the validate() method is invoked and pass the value as 13. Then if condition is checked
and if the age is less than 18 then it throws ArithmeticException otherwise it will print “Welcome to vote”.

Throwing an exception is easy if one of the existing exception classes works for you. In this case the following
must be done:

Find an appropriate exception class.

Make an object of that class.

Throw it.

Once a method throws an exception, it does not return to its caller.

Page 234 of 362


Introduction to Java programming Language

Creating Exception Classes:

If you are creating your own Exception that is known as custom exception or user­defined exception. Java
custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

In the below given program TestCustomException throws InvalidAgeException and it catch by the catch block
in the main() function.

Example:

Catching Exceptions:

If an exception occurs that is not caught anywhere, the program will terminate and print a message to the
console by giving the type of the exception and a stack trace.

To catch an exception, set up a try/catch block.

Page 235 of 362


Introduction to Java programming Language

The simplest form of the try block is as follow as:

If any code inside the try block throws an exception of the class specified in the catch clause, then

The program capers the remainder of the code in the try block.

The program fulfils the handler code inside the catch clause.

If none of the code inside the try block throws an exception, then the program skips the catch clause.

If any of the code in a method throws an exception of a type other than the one named in the catch clause,
this method exits immediately.

Catching Multiple Exceptions:

You can catch multiple exception types in a try block and handle each type differently.

Use a separate catch clause for each type as in the following example:

Page 236 of 362


Introduction to Java programming Language

The exception object may contain information about the nature of the exception.

Use the e.getMessage() method to find out more about the object.

You can catch multiple exception types in the same catch clause.

Rethrowing and Chaining Exceptions

You can throw an exception in a catch clause, when you need to change the exception type.

It is a better idea to set the original exception as the “cause” of the new exception.

When the exception is caught, the original exception can be retrieved:

This wrapping technique is highly recommended.

It allows you to throw high­level exceptions in subsystems without losing the details of the original failure.

The finally Clause:

Page 237 of 362


Introduction to Java programming Language

When your code throws an exception, it stops processing the remaining code in your method and exits the
method.

The code in the final clause accomplishes whether an exception was caught or not.

Example: This program will display the statement which is included in the finally clause. There is no exception
thrown here so the statement in the finally block will be executed.

Without a catch clause final clause can be used.

Occationally the final clause can also throw an exception. You can handle it by having a try­catch block inside
the finally block.

The Try­with­Resources Statement:

Java affords a useful shortcut to the code pattern, provided the resource belongs to a class that implements
the AutoCloseable interface which has a single method

The try­with­resources statement has the form

Page 238 of 362


Introduction to Java programming Language

When the try block exits, then res.close() is called automatically.

A difficulty arises when the try block throws an exception and the close method also throws an exception.

The try­with­resources statement handles this situation quite elegantly.

The original exception is re­thrown, and any exceptions thrown by close methods are considered
“suppressed”.

Analysing Stack Trace Elements:

A stack trace is a listing of all pending method calls at a particular point in the execution of a program.

You can access the text description of a stack trace by calling the printStackTrace method of the Throwable
class.

A more flexible approach is the getStackTrace method that yields an array of StackTraceElement objects.
The StackTraceElement class has methods to obtain the file name and line number, as well as the class
and method name, of the executing line of code.

The static Thread.getAllStackTraces method yields the stack traces of all threads.

Page 239 of 362


Introduction to Java programming Language

Tips for Using Exceptions:

The following are some tips for using Exceptions:

Exception handling is not supposed to replace a simple test. Use exceptions for exceptional circumstances
only.

Do not micromanage exceptions.

Make good use of the exception hierarchy.

Find an appropriate subclass or create your own.

Find an appropriate subclass or create your own. Don’t just throw a RuntimeException.

Catching Throwable makes your code hard to read and maintain.

Do not squelch exceptions: If you’re writing a method that calls a method it might throw an exception once
in a century, the compiler whines because you have not declared the exception in the throws list of your
method.

Since the compiler will whine about all the methods that call your method You do not want to put it in the
discard list.

Detecting an error like, “tough love” works better than indulgence: It would be better to return a dummy
value rather than throwing an exception when a method is called with invalid parameters.

It is actually better to propagate the exception instead of catching it.

Using Assertions

You can place the assertion mechanism in checks during testing and to have them automatically removed in
the production code.

The Java language contains a keyword assert.

There are two forms:

Page 240 of 362


Introduction to Java programming Language

Both statements evaluate the condition and outcome an AssertionError if it is false.

The expression is passed to the constructor of the AssertionError object and turned into a message string in
the second testimonial.

The whole sole purpose of the expression part is to produce a message string.

The AssertionError object does not store the actual expression value, so you can’t query it later.

For example:

You are certain that x is not negative and compute: double y = Math.sqrt(x);

To assert that x is non­negative, you can simply use the statement assert x >= 0;

Or you can pass the actual value of x into the AssertionError object, so that it gets displayed later: assert x
>= 0 : x;

Assertion Enabling and Disabling

Assertions cannot be enabled by default,

Enable them by running the program with the ­ enableassertions or ­ea option: java ­enableassertions MyApp

Either enabling or disabling assertions is a function of the class loader.

The class loader strips out the assertion code to avoid slow execution When assertions are disabled

You can even turn on assertions in specific classes or in entire packages.

For example: java ­ea:MyClass ­ea:com.mycompany.mylib... MyApp

The option –ea, turns on assertions in all classes of the default package.

Disabling takes place assertions in certain classes and packages with the ­disableassertions or ­da option:
java ­ea:... ­da:MyClass MyApp

Use the ­enablesystemassertions/­esa switch to enable assertions in system.

Using Assertions for Parameter Checking

Java gives you three mechanisms to deal with system failures:

Throwing an exception

Logging
Page 241 of 362
Introduction to Java programming Language

Using assertions

When should you choose assertions?

Assertion failures are intended to be fatal, unrecoverable errors.

Assertion checks are turned on only during development and testing.

You should not use assertions for signalling recoverable conditions to another part of the program or for
communicating problems to the program user.

Assertions should only be used to locate internal program errors during testing.

Using Assertions for Documenting Assumptions:

Consider this example from

In this case, it makes a lot of sense to use an assertion instead.

What are the possible values of i % 3?

If i is positive, the remainders must be 0, 1, or 2.

If i is negative, then the remainders can be ­1 or ­2.

Thus, the real assumption is that i is not negative.

Assertions are a tactical tool for testing and debugging.

Logging is a strategic tool for the entire life cycle of a program.

Debugging Techniques:
Page 242 of 362
Introduction to Java programming Language

Debuggers are available as a part of professional development environments such as Eclipse and NetBeans.

Tips to be followed before launching the debugger.

You can print or log the value of any variable with code like this:

Alloting a separate method in each class is a useful trick. Unit test stub can be put inside of it that lets you
test the class in isolation.

JUnit is a very popular unit testing framework which makes it easy to organize suites of test cases.

A logging proxy is an object of a subclass.It intercepts method calls, logs them, and then calls the
superclass.

You can get a stack trace from any exception object with the printStackTrace method in the Throwable
class.

The stack trace is displayed on System.err. If you have an intention of lgging or displaying the stack trace,
here is a way to capture it into a string:

It is very portable to trap program errors in a file. However, errors are sent to System.err, not System.out.

Having the stack traces of non catchable exceptions show up in system as error which is unavoidable.

The end users are confused with this end if they happen to see them. It is not available for diagnostic
purposes when you need them. A better approach is to log them to a file.

To watch class loading launch the Java virtual machine with the ­verbose flag.

The ­Xlint option tells the compiler to spot common code problems.

The Java VM has support for monitoring and management of Java applications, allowing the installation of
agents in the virtual machine that track memory consumption, thread usage, class loading, and so on.

You can use the jmap utility to get a heap dump which indicates you every object on the heap.

Summary:

In this chapter, we discussed the following:

Page 243 of 362


Introduction to Java programming Language

Dealing with Errors

The Classification of Exceptions

Declaring Checked Exceptions

How to Throw an Exception

Creating Exception Classes

Catching Exceptions

Catching Multiple Exceptions

Rethrowing and Chaining Exceptions

The finally Clause

The Try­with­Resources Statement

Analyzing Stack Trace Elements

Tips for Using Exceptions

Using Assertions

Assertion Enabling and Disabling

Using Assertions for Parameter Checking

Using Assertions for Documenting Assumptions

Debugging Techniques

Page 244 of 362


Introduction to Java programming Language

Streams and Files

Introduction

We will discuss the following topics in this chapter:

The Complete Stream Zoo

ZIP File Streams

Use of Streams

Writing Delimited Output

String Tokenizers and Delimited Text

Reading Delimited Input

Random­Access Streams

Object Streams

Understanding the Object Serialization File Format

Altering the Default Serialization Mechanism

Serializing Singletons and Typesafe Enumerations

Versioning

Using Serialization for Cloning

File Management

Paths

Reading and Writing Files

Copying, Moving, and Deleting Files

Creating Files and Directories

Getting File Information

Iterating over the Files in a Directory

ZIP File Systems

New I/O

Regular Expressions.

The Complete Stream Zoo

Page 245 of 362


Introduction to Java programming Language

Java has a whole zoo of more than 60 (!) different stream types.

Use subclasses of the abstract classes Reader and Writer for Unicode text.

The basic methods of the Reader and Writer classes are similar to those for InputStream and OutputStream.

abstract int read() ­ returns either a Unicode code unit or ­1 when EOF

abstract void write (int c) ­ called with a Unicode code unit.

Closeable, Flushable, Readable, and Appendable are the four additional interfaces.

The classes InputStream, OutputStream, Reader, and Writer implement the Closeable interface.

OutputStream and Writer implement the Flushable interface.

The Readable interface has a single method: int read(CharBuffer cb)

The Appendable interface has two methods for appending single characters and character sequences namely

Appendable append(char c)

Appendable append(CharSequence s)

ZIP File Streams:

ZIP archives store more than one file in compressed format.

Each ZIP archive has a header with information like the name of each file and the compression method that
has been adopted.

Use a ZipInputStream to read a ZIP archive.

The getNextEntry method returns an object of type ZipEntry that describes the entry.

The read method of the ZipInputStream is modified to return ­1 at the end of the current entry.

Call closeEntry to read the next entry.

Example: Code to read through a ZIP file:

Use the following loop to read a text file inside a ZIP file

Page 246 of 362


Introduction to Java programming Language

To write a ZIP file, use a ZipOutputStream.

To place each entry into the ZIP file, create a ZipEntry object.

Pass the file name to the ZipEntry constructor;

Call the putNextEntry method of the ZipOutputStream to begin writing a new file.

Send the file data to the ZIP stream.

Finally, call closeEntry.

Example:

Use of Streams:

The following are some of the uses of streams.

Writing Delimited Output:

Let us form a hypothesis that how to store an array of Employee records in delimited format.

Instance fields are separated from each other by delimiters. We use a vertical bar (|) as our delimiter.

Sample set of records:

Page 247 of 362


Introduction to Java programming Language

To write to a text file, we use the PrintWriter class.

We write all fields, followed by either a | or, for the last field, a \n.

To read records, we read in a line at a time and separate the fields.

Example:

String Tokenizers and Delimited Text:

We need to find the | delimiters to split the read line of input into individual strings and then separate out the
individual pieces, that is, the sequence of characters up to the next delimiter.

The StringTokenizer class in java.util is designed for the above mentioned purpose.

It is an easy way of breaking up a large string that contains delimited text.

While constructing the tokenizer object, specifying which characters are the delimiters is an easy one.

For example, StringTokenizer t = new StringTokenizer(line, "|");

To set up a string tokenizer that would let you search for any delimiter in the set " \t\n\r" , use the following:
StringTokenizer t = new StringTokenizer(line, " \t\n\r");

Reading Delimited Input:

To read one record into a string, use the following code.

To extract the individual tokens, we use the following code.

Page 248 of 362


Introduction to Java programming Language

Random­Access Streams:

If you have a large number of employee records of variable length, it is not possible to read a record in the
middle of the file without leaving the previous records.

If we make the records the same length, we can implement a random­access method for reading back the
information using the RandomAccessFile class.

To store numbers in binary format, we use the writeInt and writeDouble methods of the DataOutput interface.

To string the same size, use the methods writeFixedString and readFixedString.

The writeFixedString method takes the parameter size. Then, it writes the specified number of characters,
starting at the beginning of the string.

The readFixedString method reads characters from the input stream unless or until it has consumed size
characters or until it encounters a character with Unicode 0.

Page 249 of 362


Introduction to Java programming Language

To write a fixed­size record, we simply write all fields in binary.

Reading the data back is just as simple.

Object Streams:

Page 250 of 362


Introduction to Java programming Language

Object serialization, makes it possible to write any object to a stream and read it again later.

To save object data, open an ObjectOutputStream object:

To save an object, use the writeObject method of the ObjectOutputStream class.

To read the objects back in, first get an ObjectInputStream object:

Retrieve the objects in the same order in which they were written, using the readObject method.

The class must also implement the Serializable interface which has no methods:

An ObjectOutputStream monitors all the fields of the objects and saves their contents.

If an object is shared by several objects as a part of its state, it is not possible to save it.

To solve this we use object serialization in which each object is saved with a serial number.

Algorithm for Object serialization:

To write an Object

Associate a serial number with each object reference that you encounter.

Page 251 of 362


Introduction to Java programming Language

When encountering an object reference for the first time, save the object data to the stream.

If it has been saved previously, just write “same as the previously saved object with serial number x.”

When reading back the objects, the procedure is reversed.

When an object is specified in the stream for the first time, construct it, initialize it with the stream data,
and remember the association between the serial number and the object reference.

When the tag “same as the previously saved object with serial number x” is encountered, retrieve the
object reference for the sequence number.

Understanding the Object Serialization File Format

Object serialization saves object data in a particular file format.

Every file begins with the two­byte “magic number” AC ED followed by the version number of the object
serialization format, which is currently 00 05.

It contains a sequence of objects, in the order in which they were saved.

For example, the string “Aravind” is saved as 74 00 05 Aravind

When an object is saved, the class of that object must also be saved.

The class description contains.

The name of the class.

The serial version unique ID, which is a fingerprint of the data field types and method signatures.

A set of flags describing the serialization method.

A description of the data fields.

SHA is a fast algorithm that gives a “fingerprint” to a larger block of information.

This fingerprint is always a 20­byte data packet.

The serialization mechanism uses only the first eight bytes of the SHA code as a class fingerprint.

When reading an object, its fingerprint is compared with the current fingerprint of the class. If they don’t match
it means the class definition has changed after the object has been written, and an exception is generated.

Here is how a class identifier is stored:

Page 252 of 362


Introduction to Java programming Language

The flag byte is composed of three bit masks, defined in java.io.ObjectStreamConstants:

Each data field descriptor has the format:

Modifying the Default Serialization Mechanism:

At any cost certain data fields like integer values that store file handles should never be serialized.

In order to prevent such fields from ever being serialized, mark them with the keyword transient.

If they belong to nonserializable classes, tag fields as transient.

Transient fields are always emancipated when objects are serialized.

A serializable class can define methods with the signature.

Page 253 of 362


Introduction to Java programming Language

The data fields are no longer automatically serialized, and these methods are called instead.

A class can define its own serialization mechanism saved and restored object data by implementing the
Externalizable interface.

It has two methods:

The object stream creates an object with the no­argument constructor while reading an externalizable object
and then allows the readExternal method.

Serializing Singletons and Typesafe Enumerations:

When a typesafe enumeration implements the Serializable interface the default serialization mechanism is not
appropriate.

To solve this problem, you need to generate another special serialization method known as readResolve.

If the readResolve method is defined, it is called after the object is deserialized.

It must return an object which then becomes the return value of the readObject method.

Example:

Versioning:

Changes in a class definition leads to changes in its SHA fingerprint, in turn it results object streams will refuse
to read in objects with different fingerprints.

However, a class indication is there that it is compatible with an earlier version of itself.

To do this, you must first obtain the fingerprint of the earlier version of the class.

Use the stand­alone serialver program that is part of the JDK to obtain this number.

Example, running
Page 254 of 362
Introduction to Java programming Language

serialver Employee

prints

Employee: static final long serialVersionUID = ­1814239825517340645L;

All later versions of the class must define the serialVersionUID constant to the same fingerprint as the original.

When a class has a static data member named serialVersionUID, it will not compute the fingerprint manually
but will use that value instead.

Using Serialization for Cloning:

Serialization mechanism renders you an easy way to clone an object, provided the class is serializable.

Serialization of an output stream helps in reading it back.

The result is a new object that is a deep copy of the existing object.

You can use a ByteArrayOutputStream to save the data into a byte array.

File Management:

The Path and Files classes encapsulate the functionality required to work with the file system on the user’s
machine.

The stream classes consider the contents of files whereas the classes that we discuss here are concerned
with the storage of files on a disk.

Paths:

A Path contextually means a sequence of directory names, optionally followed by a file name.

The first component of a path may be a root component such as / or C:\.

The permissible root components depend on the file system.

A path that starts with a root component is absolute. Otherwise, it is relative.

Page 255 of 362


Introduction to Java programming Language

The static Paths.get method receives one or more strings, which it joins with the path separator of default, file
system (/ for a UNIX­like file system, \ for Windows). It then parses the result, throwing an
InvalidPathException if the result is not a valid path in the given file system. The result is a Path object.

It is very common to combine or resolve paths. The call p.resolve(q) returns a path according to these rules:

If q is absolute, then the result is q.

Otherwise, the result is “p then q”, according to the rules of the file system.

The opposite of resolve is relativizing. The call p.relativize(r) yields the path q which, when resolved with q,
yields r.

The normalize method removes any redundant . and .. components.

The toAbsolutePath method yields the absolute path of a given path, starting at a root component.

Reading and Writing Files:

The Files class makes quick work of common file operations.

For example, you can easily read the entire contents of a file:

If you want to read the file as a string, call readAllBytes followed by:

But if you want the file as a sequence of lines, call:

Vise versa, if you want to write a string, call

To append to a given file, use:

Page 256 of 362


Introduction to Java programming Language

You can also write a collection of lines with:

For large or binary files, use:

These convenience methods save you from dealing with FileInputStream, FileOutputStream, BufferedReader,
or BufferedWriter.

Copying, Moving, and Deleting Files:

To copy a file from one location to another, simply call:

To move the file (that is, copy and delete the original), call:

Unless the target does not exist the copy or move will fail

If you want to overwrite an existing target, use the REPLACE_EXISTING option.

If you want to copy all file attributes, use the COPY_ATTRIBUTES option.

Use the ATOMIC_MOVE option to assure that either the move completed successfully, or the source continues
to be present:

Page 257 of 362


Introduction to Java programming Language

To delete a file, simply call:

This method throws an exception if the file doesn´t exist, so instead use:

The deletion methods can also be used to remove an empty directory.

Creating Files and Directories:

To create a new directory, call:

To create intermediate directories as well, use:

You can create an empty file with:

There are convenience methods for creating a temporary file or directory in a given or system­specific
location.

Page 258 of 362


Introduction to Java programming Language

dir is a Path, and prefix/suffix are strings which may be null.

For example, the call Files.createTempFile(null, ".txt") might return a path such as
tmp/1234405522364837194.txt.

Getting File Information:

The following static methods return a boolean value to check a property of a path:

exists

isHidden

isReadable, isWritable, isExecutable

isRegularFile, isDirectory, isSymbolicLink

The size method returns the number of bytes in a file:

The getOwner method returns the owner of the file as an instance of java.nio.file.attribute.UserPrincipal.

All file systems deploy a set of basic attributes, encapsulated by the BasicFileAttributes interface.

The basic file attributes are given as below:

The times at which the file was created, last accessed, and last modified, as instances of the class
java.nio.file.attribute.FileTime

Whether the file is a regular file, a directory, a symbolic link, or none of these

The size of the file.

The file key—an object of some class, specific to the file system that may or may not uniquely identify a file.

To get these attributes, call: BasicFileAttributes attributes = files.readAttributes(path, BasicFileAttributes.class);

Iterating over the Files in a Directory:

The Files class has a method that results an iterable object.

Page 259 of 362


Introduction to Java programming Language

The try­with­resources block assures that the directory stream is effectively and properly closed.

There is no specific order for the visiting of directory entries.

You can filter the files with a glob pattern:

In order to visit all descendants of a directory, instead call the walkFileTree method and supply an object of
type FileVisitor.

That object gets notified:

When a file or directory is encountered: FileVisitResult visitFile(T path, BasicFileAttributes attrs)

Before a directory is processed: FileVisitResult preVisitDirectory(T dir,IOException ex)

After a directory is processed: FileVisitResult postVisitDirectory(T dir, IOException ex)

When an error occurred trying to visit a file or directory, such as trying to open a directory without the
necessary permissions: FileVisitResult visitFileFailed(T path, IOException ex)

Page 260 of 362


Introduction to Java programming Language

In each case, you can specify whether you want to:

Continue visiting the next file: FileVisitResult.CONTINUE

Continue the walk, but without visiting the entries in this directory: FileVisitResult.SKIP_SUBTREE

Continue the walk, but without visiting the siblings of this file: FileVisitResult.SKIP_SIBLINGS

Terminate the walk: FileVisitResult.TERMINATE

If any of the methods throws an exception, the walk is also terminated, and that exception is thrown from the
walkFileTree method.

ZIP File Systems:

The Paths class looks up paths in the default file system ­ the files on the user´s local disk.

If zipname is the name of a ZIP file, then the call

Establishes a file system that contains all files in the ZIP archive.

To copy a file out of that archive using its name:

To list all files in a ZIP archive, walk the file tree:

Regular Expressions:

Regular expressions are used to specify string patterns.

Use regular expressions to locate strings that match a particular pattern.

Page 261 of 362


Introduction to Java programming Language

You need to specify exactly what sequence of characters is a legal match, using a special syntax to describe a
pattern.

Example: The regular expression [Jj]ava.+ matches any string of the following form:

The first letter is a J or j.

The next three letters are ava.

The remainder of the string consists of one or more arbitrary characters.

Understanding the syntax:

A character class is a set of character alternatives, enclosed in brackets, such as [Jj], [0­9], [A­Za­z], or [^0­9].
The ­ denotes a, and ^ denotes the complement (all characters except those specified).

To include a ­ inside a character class, make it the first or last item. To include a [, make it the first item. To
include a ^, put it anywhere but the beginning. You only need to escape [ and \.

There are many predefined character classes such as \d (digits) or \p{Sc}.

Most characters match themselves, such as the ava characters in the preceding example.

The . symbol matches any character.

Use \ as an escape character, for example, \. matches a period and \\ matches a backslash.

^ and $ match the beginning and end of a line, respectively.

If X and Y are regular expressions, then XY means “any match for X followed by a match for Y”. X | Y means
“any match for X or Y”.

You can apply quantifiers X+ (1 or more), X* (0 or more), and X? (0 or 1) to an expression X.

By default, a quantifier matches the largest possible repetition that makes the overall match succeed. You can
modify that behaviour with suffixes ? (reluctant, or stingy, match: match the smallest repetition count) and +
(possessive, or greedy, match: match the largest count even if that makes the overall match fail).

You can use groups to define subexpressions. Enclose the groups in ( ), for example, ([+­]?)([0­9]+).

Page 262 of 362


Introduction to Java programming Language

Page 263 of 362


Introduction to Java programming Language

The simplest use for a regular expression is to test whether a particular string matches it or not.

The following are the steps:

Construct a Pattern object from a string containing the regular expression.

Get a Matcher object from the pattern and call its matches method.

Example:

Page 264 of 362


Introduction to Java programming Language

The input of the matcher is an object of any class that implements the CharSequence interface, such as a
String, StringBuilder, or CharBuffer.

When compiling the pattern, you can set one or more flags.

Example:

The following six flags are supported:

CASE_INSENSITIVE: Match characters independently of the letter case. By default, this flag takes only US
ASCII characters into account.

UNICODE_CASE: When used in combination with CASE_INSENSITIVE, use Unicode letter case for
matching.

MULTILINE: ^ and $ match the beginning and end of a line, not the entire input.

UNIX_LINES: Only recognize ′\n′ as a line terminator when matching ^ and $ in multiline mode.

DOTALL: Make the . symbol match all characters, including line terminators.

CANON_EQ: Take canonical equivalence of Unicode characters into account.

Page 265 of 362


Introduction to Java programming Language

Database Programming

Introduction

We will discuss the following topics in this chapter:

The Design of JDBC

The Structured Query Language

JDBC Installation

Basic JDBC Programming Concepts

Query Execution

Scrollable and Updatable Result Sets

Metadata

Row Sets

Transactions

The classification of JDBC Driver:

The JDBC specification classifies drivers into the following types:

A type 1 driver translates JDBC to ODBC and depends on an ODBC driver to communicate with the database.

Half of A type 2 driver is written in Java and rest in native code; it communicates with the client API of a
database.

A type 3 driver is a pure Java client library. It uses a database­independent protocol to communicate database
requests to a server component which translates the requests into a database­specific protocol.

A type 4 driver is a pure Java library that translates JDBC requests directly to a database­specific protocol.

Goal of JDBC:

Programmers can pen down applications in the Java programming language to access any database, using
standard SQL statements (or even specialized extensions of SQL) while still following Java language conventions.

Database vendors and database tool vendors can supply the low­level drivers. Thus, they can optimize their
drivers for their specific products.

Typical Uses of JDBC:

The traditional client/server model has a rich GUI on the client and a database on the server.

Page 266 of 362


Introduction to Java programming Language

In the three­tier model, the client never makes database calls.

It calls on a middleware layer on the server that in turn makes the database queries.

It separates visual presentation (on the client) from the business logic (in the middle tier) and the raw data (in the
database).

Communication between the client and the middle tier can occur through HTTP (when you use a web browser as
the client) or another mechanism such as remote method invocation.

The Java Enterprise Edition defines a structure for application servers. These application servers manage code
modules called Enterprise JavaBeans. It provides valuable services such as load balancing, request caching,
security, and object­relational mapping.

The Structured Query Language:

JDBC allows communication with databases using SQL which is the command language for essentially all modern
relational databases.

The JDBC package is an API for communicating SQL statements to databases.

A database is a bunch of named tables with rows and columns.

Each column has a column name. Each row contains a set of related data.

Example:

Page 267 of 362


Introduction to Java programming Language

Figure the result of joining this table with the Publishers’ table.

Not only the Books but also the Publishers tables contain an identifier for the publisher.

When we combine both tables on the publisher code we obtain a query result made up of values from the
joined tables.

Each row in the result contains the information about a book which possesses the details about the publisher
name and web page URL.

One must be aware of the publisher names. URLs are duplicated across several rows because we have
several rows with the same publisher.

Joining tables has a benefit of avoiding unnecessary duplication of data in the database tables.

SQL usage of query is written out in text by using SQL syntax, for instance,
Page 268 of 362
Introduction to Java programming Language

To select all rows in the Books table:

The FROM clause tells the database which table to examine to find the data.

Restrict the rows in the answer with the WHERE clause:

The WHERE clause can also use pattern matching by means of the LIKE operator.

Use a % for zero or more characters and an underscore for a single character.

Excludes books with titles that contain words such as Unix or Linux.

A pair of single quotes represents single quote inside a string quotes.

To select data from multiple tables:

Page 269 of 362


Introduction to Java programming Language

To constrain the query to say that we are only interested in matching books with their publishers:

To change the data inside a database:

To delete, use a DELETE query:

To insert values into a table, you can use the INSERT statement:

To create a new table:

Page 270 of 362


Introduction to Java programming Language

JDBC Installation:

Discussion is demanded to configure the JDBC before writing the database program.

Database URLs:

When connecting to a database, you must use various database­specific parameters such as host names, port
numbers, and database names.

JDBC uses syntax similar to that of ordinary URLs to describe data sources.

The general syntax is:

When a subprotocol selects the specific driver for connecting to the database.

The format for the other stuff parameter depends on the subprotocol used.

Page 271 of 362


Introduction to Java programming Language

Driver JAR Files:

JAR file has the driver for database hence you need to obtain it.

While running a program that accesses the database include the driver JAR file on the class path.

When you launch programs from the command line, simply use the command java ­classpath driverPath:
ProgramName

Starting the Database:

The database server needs to be started before you can connect to it. The details depend on your database.

With the Derby database adapt these steps:

Open a command shell and change to a directory that has the database files.

With some versions of the JDK locate the file derbyrun.jar which is contained in the jdk /db/lib directory, with
others in a separate JavaDB installation directory.

We denote the directory containing lib/derbyrun.jar with derby.

Run the command:

Double­check whether the database is working correctly or not. Create a file ij.properties that contains these
lines:

From another command shell, run Derby’s interactive scripting tool (called ij) by executing java ­jar
derby/lib/derbyrun.jar ij ­p ij.properties

Issuing of SQL commands such as is made possible:

Page 272 of 362


Introduction to Java programming Language

Note that each command must be terminated by a semicolon. To exit, type EXIT;

When you are done using the database, stop the server with the command:

Registering the Driver Class:

Many JDBC JAR files (such as the Derby driver included with Java SE 7) automatically register the driver class.

A JAR file can automatically register the driver class if it contains a file META­INF/services/java.sql.Driver.

The following given are the two ways to register the driver with the DriverManager.

Load the driver class in your Java program. For example,

Set the jdbc.drivers property with a command­line argument, such as,

Application can set the system property with a call such as,

Multiple drivers can be supplied; separate them with colons, such as

How to connect the Database:

Open a database connection like this:

Page 273 of 362


Introduction to Java programming Language

The driver manager iterates through the registered drivers to find a driver that can use the subprotocol
specified in the database URL.

The getConnection method returns a Connection object.

In order to connect to the database user name and password are very much essential.

Sample database.properties:

After connecting to the database, the test program in next slide executes the following SQL statements:

The result of the SELECT statement is printed

Then the table is removed by executing the statement:

To run this test, start your database, as described previously, and launch the program as

Page 274 of 362


Introduction to Java programming Language

Example program:

Page 275 of 362


Introduction to Java programming Language

Query Execution

Prepared Statements:

The user launches such a query for building a separate query statement every time we can prepare a query
with a host variable and use it many times, each time filling in a different string for the variable.

Whenever the database executes a query, it first computes a strategy of how to do it efficiently. By preparing
the query and reusing it, you ensure that the planning step is done only once.

Each host variable in a prepared query is indicated with a?

The SQL query:

Page 276 of 362


Introduction to Java programming Language

To set a string to a publisher name:

The first argument is the position number of the host variable which we want to set. The position 1 denotes the
first?

The second argument is the value that we want to assign to the host variable.

To execute the prepared statement:

Reading and Writing LOBs

Besides numbers, strings, and dates, many databases can store large objects (LOBs) like images or other
data.

In SQL binary large objects are called BLOBs, and character large objects are called CLOBs.

To read a LOB, execute a SELECT statement and call the getBlob or getClob method on the ResultSet.

You will get an object of type Blob or Clob.

To get the binary data from a Blob, call the getBytes or getBinaryStream.

In Clob object, we can get character data by calling the getSubString or getCharacterStream method.

To keep a LOB into a database, call createBlob or createClob on your Connection object, get an output stream
or writer to the LOB, write the data, and store the object in the database.

Page 277 of 362


Introduction to Java programming Language

SQL Escapes:

It is the job of the JDBC driver to translate the escape syntax to the syntax of a particular database.

Escapes are provided for the following features:

Date and time literals

Calling scalar functions

Calling stored procedures

Outer joins

The escape character in LIKE clauses

A scalar function is a function that returns a single value.

To call a function, embed the standard function name and arguments like this:

When a procedure executes in the database is known as a stored procedure written in a database­specific
language.

To call a stored procedure, use the call escape.

Use = to capture a return value:

Multiple Results:

Possiblities lies for a query results in multiple.

Page 278 of 362


Introduction to Java programming Language

To retrieve all result sets:

Use the execute method to execute the SQL statement.

Retrieve the first result or update count.

Repeatedly call the getMoreResults method to move on to the next result set.

Finish when there is no more result sets or update counts.

The execute and getMoreResults methods return true if the next item in the chain is a result set.

The getUpdateCount method returns ­1 if the next item in the chain is not an update count.

Retrieving Autogenerated Keys:

Some mechanisms are supported by most databases for autonumbering rows in a database.

These automatic numbers are often used as primary keys.

While inserting a new row into a table a key is automatically generated, you can retrieve it with the following
code:

Scrollable and Updatable Result Sets:

The next method of the ResultSet interface iterates over the rows in a result set.

In a scrollable result, you can move front and back through a result set and even jumps to any position.

You can programmatically update entries which in turn automatical updatation of database in an updatable result
set.

Scrollable Result Sets:

Due to its default, result sets are not scrollable or updatable.

To obtain scrollable result sets from your queries, you must obtain a different Statement object with the
method:

For a prepared statement, use the call:

Page 279 of 362


Introduction to Java programming Language

For example, if one is particular in scrolling through a result set without editing its data, the following can be
used:

Method calls return all result sets ResultSet rs = stat.executeQuery(query) are now scrollable.

A scrollable result set has a cursor which indicates the current position.

To scroll backward: if (rs.previous()) . . .

To move the cursor backward or forward by a number of rows with the call: rs.relative(n); If n is positive, the
cursor moves forward. If n is negative, it moves backward. If n is zero, the call has no effect.

To set the cursor to a particular row number: rs.absolute(n);

To get the current row number, call: int currentRow = rs.getRow();

The first row in the result set has number 1. If the return value is 0, the cursor is not currently on a row.

The methods first, last, beforeFirst, and afterLast move the cursor to the first, to the last, before the first, or
after the last position.

Finally, the methods isFirst, isLast, isBeforeFirst, and isAfterLast test whether the cursor is at one of these
special positions.

Updatable Result Sets:

To edit the result set data and have the alteration automatically reflected in the database, creation of an updatable
Page 280 of 362
Introduction to Java programming Language

result set ought to be done.

The result sets returned by a call to executeQuery are then updatable.

The updateXxx method changes only the row values, not the database.

The updateRow method sends all updates in the current row to the database.

The call the cancelRowUpdates method to cancel the updates to the current row.

Example, to modify an existing row:

To delete the row under the cursor: rs.deleteRow();

The deleteRow method immediately removes the row from both the result set and the database.

The updateRow, insertRow, and deleteRow methods of the ResultSet interface give you the same power as
executing UPDATE, INSERT, and DELETE SQL statements.

Row Sets:

Though the RowSet interface extends the ResultSet interface, row sets don′t have to be necessarily tied to a
database connection.

Row sets are also suitable if you need to move a query result to a different tier of a complex application, or to
another device such as a cell phone.

Constructing Row Sets:

The javax.sql.rowset package provides the following interfaces that extend the RowSet interface:

A CachedRowSet permits disconnected operation.

A WebRowSet is a cached row set. It can be saved to an XML file. The XML file can be transferred to
another tier of a web application where it is opened by another WebRowSet object.

The FilteredRowSet and JoinRowSet interfaces join together to support lightweight operations on row sets
that are equivalent to SQL SELECT and JOIN operations. These operations are performed on the data
stored in row sets without having to make a database connection.

A JdbcRowSet is a thin wrapper layer lying around a ResultSet. It serves useful getters and setters from the
Page 281 of 362
Introduction to Java programming Language

RowSet interface, turning a result set into a “bean.”

The standard way for obtaining a row set:

Cached Row Sets:

A cached row set incubes all data from a result set.

In cached row sets we can close the connection and continue to use the row set.

To populate a CachedRowSet from a result set:

To set up the database parameters:

Set the query statement and any parameters.

Populate the row set with the query result: crs.execute();

This call establishes a database connection, issues the query, populates the row set, and disconnects.

Metadata:

JDBC offers an additional information about the structure of a database and its tables.

Structural information is who listically useful for programmers who write tools which work with any database.

In SQL, data that describe the database or one of its parts are called metadata.

To find out more about the database, one must request an object of type DatabaseMetaData from the database
connection.

Page 282 of 362


Introduction to Java programming Language

Example:

Returns a result set that contains information about all tables in the database.

The DatabaseMetaData interface gives data about the database.

ResultSetMetaData reports information about a result set.

Transactions:

One can combine a set of statements to form a transaction. The transaction can be committed when everything
functions well orelse if an error occurrs in one of them, it can be rolled back as if none of the statements has been
issued.

The major reason for grouping statements into transactions is database integrity.

If you group update statements into a transaction, the transaction either succeeds in its entirety or it fails
somewhere in the mid.

In such case one can carry out a rollback. Then the database automatically goes back to the effect of all updates
that has occurred since the last committed transaction.

If a database connection is in autocommit mode by default each SQL statement is committed to the database as
soon as it is executed.

Having committed a statement you cannot roll it back.

To Turn off this default: conn.setAutoCommit(false);

To Commit: conn.commit();

To Rollback: conn.rollback();

Save Points:

Creation of saving point marks a point to which you can later return without having to leave the whole
transaction.

Page 283 of 362


Introduction to Java programming Language

Example:

When you no longer need a save point, you should release it: conn.releaseSavepoint(svpt);

Batch Updates:

A sequence of statements is collected and submitted as a batch in a batch update.

The statements in a batch can do actions not only INSERT, UPDATE, or DELETE but also data definition
statements such as CREATE TABLE or DROP TABLE.

An exception is thrown if you add a SELECT statement to a batch.

To execute a batch, first create a Statement object in the usual way:

Finally, submit the entire batch:

Treat the batch as a single transaction.

First, turn the autocommit mode off, then collect the batch, execute it, commit it, and finally restore the original
autocommit mode:

Page 284 of 362


Introduction to Java programming Language

Advanced SQL Types:

A SQL ARRAY is a series and sequence of values.

ROWID ­ describes the location of a row so that it can be retrieved very rapidly.

A national character string (NCHAR and its variants) stores strings in a local character encoding and sorts
them using a local sorting convention.

Some databases provide native storage for XML data.

Page 285 of 362


Introduction to Java programming Language

Assignments

1. Write a Java program to sum the elements of an array

2. Write a Java Program to find duplicate Characters in a String

Page 286 of 362


Introduction to Java programming Language

3. Write a Java Program to get input from user

Page 287 of 362


Introduction to Java programming Language

4. Write a Java Program to check Even or Odd number

Page 288 of 362


Introduction to Java programming Language

Page 289 of 362


Introduction to Java programming Language

5. Write a Java program to perform binary search

Page 290 of 362


Introduction to Java programming Language

Page 291 of 362


Introduction to Java programming Language

Page 292 of 362


Introduction to Java programming Language

Page 293 of 362


Introduction to Java programming Language

Output

Page 294 of 362


Unit - 3
Introduction to UML

Page 295 of 362


Introduction to UML

Introduction, An outline Development Process and Use cases

Introduction

Following topics are thrown importance in this chapter:

What Is the UML?

How We Got Here

Notations and Meta­Models

Why Do Analysis and Design?

Overview of the Process

Inception

Elaboration

Planning the Construction Phase

Construction

Transition

When to Use Iterative Development

Use Case Diagrams

Business and System Use Cases

When to Use Cases.

What is the UML?

The Unified Modeling Language (UML) is a family of graphical notations. It is backed by single meta­model which
the UML helps in describing and designing software systems, particularly software systems built using the object­
oriented (00) style.

The UML is controlled by the Object Management Group (OMG), an open consortium of companies. The UML is a
relatively open standard.

The OMG is originated to build standards that supported interoperability exclusively the interoperability of object­
oriented systems.

The OMG is best known for the CORBA (Common Object Request Broker Architecture) standards.

Unification of many object­oriented graphical modeling languages is the ancestors of the UML. This unification
thrived between in the late 1980s and early 1990s.

How We Got Here:

Literature of the subject ­ In the 1980s, objects shifted to be away from the research labs and took their maiden
stride towards the "real" world.
Page 296 of 362
Introduction to UML

C++ was born due to the Smalltalk stabilization into a platform.

Meantime, various people started to work on object­oriented graphical design languages.

The key books about object­oriented graphical modeling languages appeared between 1988 and 1992.

In spite of being very similar methods in these books contained a number of often annoying minor differences
among them. The same basic concepts would appear in a disagreed way created confusion to my clients.

Grady and Jim had prepared their first public description of their merged method by OOPSLA ′95: version 0.8 of
the Unified Method documentation.

The next year saw the shift from passive position of OMG to be an active, which had mostly stood on the
sidelines.

The vendors energized the OMG to do something about it, under the Banner of CASE tool interoperability.

The idea was to create a UML that would allow CASE tools for free exchange models.

Various organizations submitted proposals for a methods standard to facilitate the interchange of models in
January 1997,

Rational collaborated with a number of other organizations and released version 1.0 of the UML documentation.

The OMG adopted the resulting 1.1 as an official OMG standard.

Revision 1.2 was entirely cosmetic.

Revision 1.3 was more significant.

Revision 1.4 added a number of detailed concepts around components and profiles.

Revision 1.5 added action semantics.

Notations and Meta­Models:

The UML, in its current state, defines a notation and a meta­model.

The notation is the graphically stuffed in models for it is the graphical Syntax of the modeling language.

The idea of rigorous specification and design languages is most predominant in the field of formal methods.

Most graphical modeling languages have no rigor­ their notation appeals to intuition rather than to formal definition.

To improve the rigor of methods without sacrificing their usefulness, we can define a meta­model: a diagram,
usually a class diagram that defines the concepts of the language.

Page 297 of 362


Introduction to UML

Why Do Analysis and Design?:

Software development holds its real point in cutting the code.

We will discuss the reasons for using UML and let’s see how it reflects in writing the code.

Communication:

The fundamental reason to use the UML involves communication.

Use the UML when you want a certain amount of precision but you don′t want to get lost in details.

Use it to highlight important details.

It helps to acquire an overall view of the system.

A class diagram can tell what kinds of abstractions are present in the system and where the questionable parts
need further work.

Interaction diagrams illustrate key behaviors in the system.

To build a road map of a large system, use package diagrams to show the major parts of a system and their
interdependencies.

For each package, draw a class diagram.

Use patterns to describe the important ideas in the system that appears in multiple places.

Learning OO:

Though the techniques in the UML were designed to help people do good OO, different techniques have
different advantages.
Page 298 of 362
Introduction to UML

One of the most valuable techniques for learning OO is CRC cards. They were designed primarily for
teaching people to work with objects. As such, CRC cards are deliberately different from traditional design
techniques.

CRC cards become particularly valuable when their emphasis on responsibilities and their lack of complex
notation.

As interaction diagrams make the message structure very explicit they are useful for highlighting over­
centralized designs, in which single object is doing the whole work.

Class diagrams are both good and bad for learning models. They are used to illustrate class models. It is
easy to develop a class model that is data oriented rather than being responsibility oriented which is a major
problem of using it.

The concept of patterns has become vital to learning OO because using patterns gets you to concentrate on
good OO designs and to learn by following an example.

Another important technique is iterative development. This technique does not help you learn OO in any
direct way, but it is the key to exploiting OO effectively. If you do iterative development from the start, you will
learn, in context, the right kind of process and begin to see why designers suggest doing things the way they
do.

Communicating with Domain Experts:

The biggest challenge faced in development is that of building the right system­one that meets users′ needs at
a reasonable cost.

The technique to be used to address this issue is use cases.

A use case is a snapshot of one of the aspects of your system.

The sum of all use cases is the external picture of your system which will explain what the system will do.

A good collection of use cases is central to understand what your users want.

As use cases control iterative development which is a valuable technique they present a good vehicle for project
planning.

Class diagrams can be used to look at the deeper things.

Activity diagrams are very useful in cases in which workflow processes are an important part of the users′ world.

These diagrams deemphasize the links to classes.

Though deemphasizing can be a problem in later design, it becomes an advantage during this more conceptual
stage of the development process.

Overview of the Process:

This process is an iterative and incremental development process, in which the software is developed and released
in pieces.

The construction phase consists of many iterations in which each iteration builds production­quality software,
tested and integrated, that satisfies a subset of the requirements of the project.

Page 299 of 362


Introduction to UML

Each iteration contains all the usual life­cycle phases of analysis, design, implementation, and testing.

During inception, you establish the business rationale for the project and decide on the scope of the project.

In elaboration, you collect more detailed requirements, do high­level analysis and design to establish baseline
architecture, and create the plan for construction.

The transition phase includes beta testing, performance tuning, and user training.

Inception, Elaboration:

Inception:

During the inception phase, you work out the business case for the project­roughly how much it will cost and
how much it will bring in and get a sense of the project′s scope.

Inception should be a few days’ work to consider whether worth of a few months’ work in deeper investigation
during elaboration.

Elaboration:

At this point, you want to get a better understanding of the problem.

What is it you are actually going to build?

How are you going to build it?

While deciding what issues to be given priority in this phase, you must be aware of the risks.

Risks can usefully be classified into four categories:

Requirements risks: What are the requirements of the system? The big danger is that building the wrong
system does not fulfill the customer needs.

Technological risks: What are the technological risks one has to face? Do you select technology that will
actually work for you? Will the various pieces fit together?

Skills risks: Are the sources like the staff and expertise available?

Political risks: Are there political forces that can interfere in the way and seriously affect your project?

Dealing with Requirements Risks:

Page 300 of 362


Introduction to UML

A use case is a typical interaction. In order to achieve a goal, a user has with the system.

Use cases provide the basis of communication between customers and developers in planning the project.

An essential part is to discover all the potential use cases for the system you are building in the elaboration
phase.

Another important task is to come up with the skeleton of a conceptual model of the domain.

Techniques in building conceptual domain models.

Use class diagram, drawn from a conceptual perspective.

Class diagrams are about defining a rigorous vocabulary to talk about the domain.

Describe a domain with strong workflow element using activity diagrams.

Interaction diagrams are used to explore how various roles interact in the business.

Prototyping is a valuable technique for getting a better understanding of how more dynamic situations work.

Dealing with Technological Risks:

Addressing technological risks is to build prototypes that try out the pieces of technology you have an idea of
using.

The biggest technological risks are inherent and how the components of a design fit together rather than being
present in any of the components themselves.

It is very important to get all the components you intend to use and fit them together at this early stage of the
process.

Address any architectural design decisions during the technological stage.

Focus on any areas that look If an issue seems to be difficult to change later, focus on those areas.

As with the domain model, you should look at the use cases as they appear in order to assess whether they
contain anything that could cripple your design.

Use a number of UML techniques to jot down your ideas and document the things you try.

Class diagrams and interaction diagrams are useful in showing how components communicate.

Package diagrams can show a high­level picture of the components at this stage.

Deployment diagrams can provide an overview of how pieces are distributed.

Dealing with Skills Risks:

Since instructors have already made those mistakes, training is a way to avoid making mistakes.

Though an overview of people’s need is meted out, they don′t really pass on the core skills that you need to do
a serious project.

Get your training in small chunks, when you need it.

Page 301 of 362


Introduction to UML

Acquiring OO skills through mentoring is the best way, in which you have an experienced developer work with your
project for an extended period of time.

The mentor shows you how to do things, watches what you do, and passes on tips and short bits of training.

A mentor will work with the specifics of your project and knows which bits of expertise to apply at the right time.

You can also supplement your skills by reading a solid technical book at least once every other month.

Planning the Construction Phase:

The essence of building a plan involves setting up a series of iterations for construction and defining the
functionality of delivering each iteration.

Consider the following two groups of people

Customers: people who are going to use the system for an in­house development.

Developers: people who are going to build the system.

The first step is to categorize the use cases:

According to their business value the customer divides the use cases into three piles: high, medium, and low.

Afterwards the developers divide the use cases according to the development risk.

The developers should estimate the length of time each use case will require, to the nearest person week.

Determination of your iteration length is long enough to do a handful of use cases.

project velocity = number of developers* iteration length/load factor.

The next step is to assign the use cases to iterations:

You can have less work to do than the effort in the iteration, but you should never schedule more than your
effort allows.

For transition, allocate from 10 percent to 35 percent of the construction time for tuning and packaging for the
delivery.

Add a contingency factor: 10 percent to 20 percent of the construction time.

You should have a release plan that shows the use cases that will be done during each iteration.

Construction:

Construction builds the system in a series of iterations.

Each iteration is a mini­project.

The iterations within construction are both incremental and iterative.

The iterations are incremental in function. Each iteration builds on the use cases based on the development of
the previous iterations.

The iterations are iterative in terms of the code base. Iteration each involves rewriting some existing code to

Page 302 of 362


Introduction to UML

make it more flexible.

Refactoring is a highly useful technique in iterating the code.

You do not need to change the functionality of your program while refactoring,

Instead you change its internal structure in order to make it easier to understand and work with.

It′s a good idea to keep an eye on the amount of code thrown away in iteration.

A developer should integrate after every significant piece of work. Integration should be a consistent process.

Iterative development is time­boxed­ which is its key factor that you are not allowed to slip any dates.

But, use cases can be moved to a later iteration via negotiation and agreement with the customer.

Using the UML in Construction:

All UML techniques are useful during this stage:

A conceptual class diagram can be useful to figure out some concepts for the use case and see how these
concepts fit with the already existing software.

CRC cards and interaction diagrams are useful in exploring how the classes will collaborate to implement the
functionality required by each use case.

What you have done can be documented with the help of UML.

Use a package diagram as logical road map of the system.

A deployment diagram shows the high­level physical picture.

Use a specification­perspective class diagram within each package.

A class with complex lifecycle behavior can be better described by drawing a state diagram.

If a particularly complex algorithm is involve, use an activity diagram.

Use patterns to capture the basic ideas.

Transition

In order to improve performance the clarity and extensibility of the system are reduced by Optimization in order to
improve performance.

On the other hand earlier optimizing makes development tougher, so this is one thing that needs to be left to the
end.

During transition, there is no development to add functionality, unless it is small and absolutely essential.

There is development to fix bugs.

Example: Time between the beta release and the final release of a product.

When to Use Iterative Development:

Page 303 of 362


Introduction to UML

We can use iterative model in the following cases:

Requirements of the complete system are clearly defined and understood.

When the project is big.

Though some details can evolve with time, major requirements must be defined some details can evolve with
time.

Advantages of Iterative model:

We can only create a high­level design of the application prior to build the product and define the design
solution for the entire product.

In the later period we can design and built a skeleton version of that, and evolve the design based on what had
already been built.

As we are building and improving the product gradually, we can track the defects in the earlier stages. This
avoids the downward flow of the defects.

We can get the reliable user feedback When presenting sketches and blueprints of the product to users for their
feedback, we are effectively asking them to imagine how the product will work.

Less time is spent on documenting and more time is given for designing.

Disadvantages of Iterative model:

Each phase of iteration is rigid with no overlaps.

Costly system architecture or design issues may arise because not all requirements are gathered up front for
the entire lifecycle.

Use Case Diagrams

Page 304 of 362


Introduction to UML

Actors

An actor is a role played by a user with respect to the system.

There are four actors in previous figure namely: Trading Manager, Trader, Salesperson, and Accounting
System.

Though there are many traders in the given organization, they all play the same role. A user may also play
more than one role.

It is important to think about roles rather than people or job title, while dealing with actors.

Actors carry out use cases. A single actor may perform many use cases; a use case may have several actors
performing it.

An actor can also be an external system that needs some information from the current system.

There are some situations in which it can be worth tracking the actors later.

The system may need configuring for various kinds of users. In this case, each kind of user is an actor, and
the use cases show you what each actor needs to do.

Tracking who wants use cases can help you negotiate priorities among various actors.

A good source for identifying use cases is external events.

Use Case Relationships:

There are several kinds of relationships between use cases:

The include relationship occurs when you have a chunk of behaviour that is similar across more than one use
case and you don´t want to keep copying the description of that behaviour.

Page 305 of 362


Introduction to UML

When you have one use case that is similar to another use case but does a bit more than the other, use use
case generalization. This gives us another way of capturing alternative scenarios.

There are more rules in Extend, however it is similar to generalization.

A use case may have many extension points, and an extending use case may extend one or more of these
extension points.

If you want to avoid repetition, use include

Use generalization when you are describing a variation on normal behaviour and you wish to describe it
casually.

Use extend when describing a variation on normal behaviour in the meantime use the more controlled form,
declaring your extension points in your base use case.

Business and System Use Cases:

A common problem that can happen with use cases is that by focusing on the interaction between a user and the
system, you can neglect situations in which a change to a business process may be the best way to deal with the
problem.

A system use case has an interaction with the software.

How a business responds to a customer or an event is discussed by a business use case.

System use cases are more useful for planning.

Business use cases are used to consider other ways to meet an actor′s goal.

You need at least one set of system use cases for each business use case by end of elaboration phase

When to Use Cases:

Use cases are an essential tool for the requirement of capturing, planning and controlling an iterative project.

Capturing use cases is one of the primary tasks of the elaboration phase.

Every use case is a potential requirement. Until you have captured a requirement, you cannot have a plan to deal
with it.

Conceptual modelling with users helps uncover use cases.

Page 306 of 362


Introduction to UML

An external view of the system is represented by use cases.

Don′t expect any correlations between use cases and the classes inside the system.

Page 307 of 362


Introduction to UML

Class Diagrams and Advance Concepts

Introduction

We will discuss the following topics in this chapter:

Perspectives

Associations

Attributes

Operations

Generalization

Constraint Rules

When to Use Class Diagrams

Stereotypes

Object Diagram

Class Scope Operations and Attributes

Multiple and Dynamic Classification

Aggregation and Composition

Derived Associations and Attributes

Interfaces and Abstract Classes

Reference Objects and Value Objects

Collections for Multivalued Association Ends

Frozen

Classification and Generalization

Qualified Associations

Association Class

Parameterized Class

Visibility.

Perspectives

This diagram describes the types of objects in the system and various kinds of static relationships which exist
between them.

Page 308 of 362


Introduction to UML

There are two principal kinds of static relationships:

Associations (for example, a customer may rent a number of videos).

Subtypes (a nurse is a kind of person).

There are three perspectives you can use in drawing class diagrams:

Conceptual:

Though drawing a diagram that represents the concepts in the domain under study which will naturally
relate to the classes that implement them, there is no direct mapping.

This can be considered language­independent.

Specification:

Here attention falls on the interfaces of the software, not the implementation.

In spite of the emphasis of Object­Oriented development greatly on the difference between interface and
implementation, the notion of class in an OO language combines both interface and Implementation.

The key to effective OO programming is to program to a class´s interface rather than to its
implementation.

Implementation:

In this view, we have classes and we are laying the implementation bare.

This is probably the perspective used most often, but in many ways the specification perspective is often
a better one to take.

The UML can be used with all three perspectives.

Mark classes with   to show the implementation perspective, and with 
 for the specification and conceptual perspectives.

Associations:

Relationships between instances and classes are well represented by Associations.

From the conceptual perspective, associations represent conceptual relationships among classes.

As each association has two association ends, each end is attached to one of the classes in the association.

An end can be explicitly named with a label called role name.

Unless there is label, name can be given at the end after the target class­so.

An association end also has multiplicity which is an indication of how many objects may participate in the given
relationship.

The multiplicity indicates lower and upper bounds for the participating objects.

Page 309 of 362


Introduction to UML

The * represents the range 0..infinity.

The 1 stands for 1..1.

The most common multiplicities in practice are 1,*, and 0..1.

Associations represent responsibilities within the specification perspective.

For updating the relationship an association also implies some responsibility.

These responsibilities do not imply data structure.

Imply pointers in both directions between the related classes in an implementation model,

We have arrows on the association lines which indicate navigability.

Navigability is an important part of implementation and specification diagrams.

If navigability exists in only one direction, we call the association a unidirectional association.

A bidirectional association contains navigability in both directions.

Bidirectional associations include an extra constraint, which is that the two navigations are inverses of each
other.

Although the instances connected may change over time, an association represents a permanent link between
two objects and the link continues to exist the whole lives of the objects.

Page 310 of 362


Introduction to UML

Attributes:

Attributes are likely to be similar to associations.

A Customer′s name attribute indicates that Customers have names. At the conceptual level.

Attribute indicates that a Customer object can tell you its name and has a way of setting a name at the
specification level.

A Customer has a field for its name at the implementation level.

The UML syntax is visibility name: type = defaultValue, where visibility is the same as for operations.

Difference between an attribute and an association:

From the conceptual perspective: No difference.

At the specification and implementation levels:

Attributes imply navigability from the type to the attribute only.

The type contains solely its own copy of the attribute object, i.e., any type used as an attribute has value
rather than reference semantics.

Operations:

Operations are the processes that a class knows to carry out.

They correspond to the methods on a class.

At the specification level, operations correspond to public methods on a type.

Private and protected operations are shown in the implementation model.

The full UML syntax for operations is: visibility name (parameter­list):return­type­expression {property­string}.
where:

visibility is + (public), # (protected), or ­ (private)

Page 311 of 362


Introduction to UML

name is a string

parameter­list contains comma­separated parameters whose syntax is similar to that for attributes:
direction name: type = default value.

The only extra element is direction, which is used to show whether the parameter is used for input (in),
output (out), or both ( inout).

If there is no direction value, it′s assumed to be in.

return­type­expression is a comma­separated list of return types. Most people use only one return type, but
multiple return types are allowed.

property­string indicates property values that apply to the given operation

An example operation on account might be: + balanceOn (date: Date): Money.

Within conceptual models:

Don’t use operations to specify the interface of a class.

Use them to indicate the principal responsibilities of that class, using a couple of words summarizing a CRC
responsibility.

UML defines a query as an operation that gets a value from a class without changing the system state.

Operations that do change state are modifiers.

Queries can be executed in any order, but the sequence of modifiers is more important.

A getting method returns a value from a field.

A setting method puts a value into a field.

An operation is something that is invoked on an object.

A method is the body of procedure.

UML uses the term feature to mean either an attribute or an operation.

Generalization:

In a specification model:

The interface of the subtype must include all elements from the interface of the super type. It is called as
Generalization.

The subtype′s interface is said to conform to the super­type′s interface.

In implementation perspective:

It is associated with inheritance in programming languages.

The subclass inherits all the methods and fields of the superclass and may override inherited methods.

Page 312 of 362


Introduction to UML

Sub classing is one of the ways to implement subtyping.

You can also implement subtyping through delegation.

With either of these forms of generalization, you should always ensure that the conceptual generalization
also applies.

The subtype implements operations in a different way, you may choose not to show the subtype on a
specification perspective diagram, if there are cases in which a subtype has the same interface as its
supertype.

Constraint Rules:

Activities in drawing a class diagram indicate constraints.

Though the basic constructs of association, attribute, and generalization do much to specify important
constraints, they cannot indicate every constraint.

The class diagram is a good place for capturing constraints.

Anything which can be allowed by the UML to describe constraints.

The only rule is that you put them inside braces ({}).

Rules should be implemented as assertions in your programming language.

When to Use Class Diagrams:

Class diagrams are the backbone of almost all OO methods.

Tips to use class diagram:

Though all the notations available to you, don’t try to use all.

Start with the simple stuff in this chapter: classes, associations, attributes, generalization, and constraints.

From the perspectives you are drawing fit the models to the stage of the project.

If you are in analysis, draw conceptual models.

While working with software, concentrate on specification models.

When you are illustrating a particular implementation technique, draw implementation models only.

Instead of drawing models for everything, concentrate on the key areas. Because it is better to concentrate
on a few diagrams that you use and keep up to date rather than to have many forgotten and obsolete
models.

Focus on the conceptual and specification perspectives to avoid from getting blogged down in system
implementation details too early.

Stereotypes:

Page 313 of 362


Introduction to UML

Stereotypes are the core extension mechanism of the UML.

Even though you need a modeling construct which isn′t in the UML, it is similar to something that, you treat
your construct as a stereotype of the UML construct.

Example:

If a class has only public operations excluding method bodies or attributes is termed as a UML interface.

This corresponds to interfaces in Java, COM, and CORBA.

Hence, interface is defined as a stereotype of class.

Stereotypes are usually shown in text between guillemets (for example, «interface»).

Many extensions to the core UML can be described as a collection of stereotypes. Within class diagrams,
these might be stereotypes of classes, associations, or generalizations.

Stereo­types are subtypes of the meta­model types Class, Association, and Generalization.

A profile takes a part of the UML and extends it with stereotypes for a particular purpose.

Object Diagram:

An object diagram is a snapshot of the objects in a system at a particular point of time.

Since it shows instances rather than classes, it is also called an instance diagrams.

Use an instance diagram to show an example configuration of objects.

An object diagram is a collaboration diagram without messages.

Use an instance diagram to show an example configuration of objects.

Each name takes the form instance name : class name. Both parts of the name are optional.

Page 314 of 362


Introduction to UML

Class Scope Operations and Attributes:

As UML has class scope UML refers to an operation or an attribute that applies to a class, rather than an
instance.

This is equivalent to static members in C++ or Java and to class variables and methods in Smalltalk.

Class scope features are underlined on a class diagram.

Multiple and Dynamic Classification

Classification refers to the relationship between an object and its type.

Single classification refers to an object belongs to a single type, which may inherit from supertypes.

Multiple classification indicates that an object may be described by several types that are not necessarily
connected by inheritance.

Multiple classification is different from multiple inheritance:

Page 315 of 362


Introduction to UML

Multiple inheritances: a type may have many supertypes, but a single type must be defined for each object.

Multiple classifications: Allows multiple types for an object without defining a specific type for the purpose.

Make it very obvious which combinations are legal in multiple classifications by labeling a generalization line
with a discriminator.

A useful constraint intends to mean that any instance of the superclass must be an instance of one of the
subtypes of a group.

Dynamic classification allows objects to change type within the subtyping structure whereas static classification
does not do what dynamic classification does.

A separation is made between types and states with the help of static classification dynamic classification
combines these notions.

Page 316 of 362


Introduction to UML

Figure shows an example of using dynamic classification for a person´s job, which, of course, can change.

Aggregation and Composition:

Aggregation is the part­of relationship. It′s like a car has an engine and wheels as its components.

UML offers a stronger variety of aggregation, called composition.

In composition part object may belong to only whole.

In spite of a class component of many other classes, any instance must be a component of only one owner.

The class diagram may Show multiple classes of potential owners, but any instance has only a single object as
its owner.

Example: The figure in next slide shows examples of these constructs.

The compositions to Point indicate that any instance of Point may be in either a Polygon or a Circle, but not
both.

An instance of Style, however, may be shared by many Polygons and Circles.

Furthermore, this implies that deleting a Polygon would cause its associated Points to be deleted, but not
the associated Style.

Figure shows another notation for composition.

Page 317 of 362


Introduction to UML

In this case, you put the component inside the whole.

The component class´s name is not bold, and you write it in the form rolename:Class name.

You can also use an attribute for a single­valued component.

Derived Associations and Attributes:

Derived associations and derived attributes can be calculated from other associations and attributes,
respectively, on a class diagram.

For example, if you know that Person′s date of birth, an age attribute of a Person can be derived.

Derived features indicate a constraint between values, but not a statement of what is calculated and what is
stored.

Page 318 of 362


Introduction to UML

Note:

Detail Accounts have the attachment with Entry objects.

The balance of an Account is calculated as the sum of Entry amounts.

A Summary Account´s entries are the entries of its components, determined recursively.

Figure shows a hierarchical structure of accounts drawn from a specification perspective.

The model uses the Composite pattern.

To illustrate how derived elements indicate constraints we use a class named Time Period.

Page 319 of 362


Introduction to UML

If this is a specification diagram, (although it suggests that start and end are stored and duration of it is
calculated), a programmer can implement this class in any fashion that maintains that external behavior.

Derived values are valuable for annotating fields on implementation diagrams. Those annotated fields are
used as caches for performance reasons.

Use derived markers to remind where these derivations exist and to confirm with the domain experts on
conceptual diagrams. Derivations exist with the domain experts.

Interfaces and Abstract Classes:

An abstract class is a class that cannot be directly instantiated.

It has one or more operations that are abstract.

An abstract operation has no implementation; it is pure declaration so that clients can bind to the abstract
class.

The most common way to indicate an abstract class or operation in the UML is to italicize the name.

You can also use the label: {abstract}.

All features of interface are abstract hence an interface is a class that has no implementation You mark an
interface with the keyword «interface».

Classes have two kinds of relationships with interfaces: providing and requiring.

A class provides an interface if it is substitutable for the interface.

A class requires an interface if it needs an instance of that interface in order to work.

Figure shows the relationships in action, based on a few collection Classes from Java.

Page 320 of 362


Introduction to UML

There is an Order class that has a list of line items.

Since there is a list, the Order class is dependent on the List interface.

The ArrayList itself is a subclass of the AbstractList class.

AbstractList provides some, but not all, the implementation of the List behavior.

ArrayList implements List and Collection is shown by ball icons, often referred to as lollipops. The fact that
Order requires a List interface is shown by the socket icon.

Any class is a combination of not only an interface but also an implementation.

A problem with interaction diagrams don′t provide a very good visualization for polymorphic behavior.
Generally it is considered as a serious issue.

Page 321 of 362


Introduction to UML

Reference Objects and Value Objects:

Reference objects are such things like Customer.

For finding out software object to designate a Customer in the real world, identity is very important.

Any object refers a Customer object, will do so through a reference, or pointer.

Changes to a Customer are available to all users of the Customer.

If you have two references to a Customer and wish to see whether they are the same, you usually compare
their identities.

Reference objects are such things like Customer.

For finding out software object to designate a Customer in the real world, identity is very important.

Any object refers a Customer object, will do so through a reference, or pointer.

Changes to a Customer are available to all users of the Customer.

If you have two references to a Customer and wish to see whether they are the same, you usually compare
their identities.

Value objects are such things as Date.

You often have multiple value objects representing the same object in the real world.

If you have two dates and wish to find out whether they are the same or not, you look at the values they
represent.

Value objects should be immutable.

Collections for Multivalued Association Ends:

A multivalued end is one whose multiplicity′s upper bound is greater than 1 (for instance, *).

The usual convention is that multivalued ends are thought of as sets.

There is no ordering for the target objects, and no object appears in the set more than once.

These assumptions can be changed by attaching a constraint.

The {ordered} constraint implies that there is an ordering to the target objects­that is, the target objects form a
list.

Use the {bag} constraint to indicate that target objects may appear more than once, without ordering.

Use the {hierarchy} constraint to indicate that the target objects form a hierarchy.

Use the {dag} constraint to indicate a directed acyclic graph.

Frozen

Page 322 of 362


Introduction to UML

Frozen is a constraint that is applicable to an attribute or an association end.

Frozen indicates that the value of attribute or association end may not change during the lifetime of the source
object.

The initial value may be null.

Frozen indicates that all association ends and attributes associated with that class are frozen in a class.

Since Read­only implies that a value cannot be changed directly but may change due to a change in some
other value. Frozen is not the same as read­only.

Mark "freezing" using the {frozen} constraint.

Mark read­only values with {read only}.

Classification and Generalization

Consider the following phrases.

Sheep is a Border collie.

A Border collie is a Dog.

Dogs are Animals.

A Border collie is a Breed.

Dog is a Species

If we combine phrases 1 and 2,we get "Sheep is a Dog"; When 2 and 3 taken together yield "Border Collies
are Animals." ­ Good

1 and 4 gives as "Sheep is a Breed." The combination of 2 and 5 is "A Border Collie is a Species." – Not good.

Why can’t we combine some of these phrases and not others?

The reason is that some are classification, and some are generalization.

Generalization is transitive; classification is intransitive.

We can combine a classification followed by a generalization, but not vice versa.

Qualified Associations:

A qualified association is the UML equivalent of a programming concept variously known as associative arrays,
maps, and dictionaries.

Page 323 of 362


Introduction to UML

From a Software perspective, this qualified association would imply an Interface as:

All access to a given Order Line requires a Product as an argument, suggesting an implementation of using a
key and value data structure.

Use the qualifier construct only to show constraints along the lines of "single Order Line per Product on Order."
in conceptual modeling.

In specification models, use it to show a keyed lookup interface.

In implementation models, use it to show uses of a map, dictionary, associative array, or similar data structure.

Association class:

Association classes allow you to add attributes, operations, and other features to associations.

The association class adds an extra constraint, in that there can be only one instance of the association class
between any two participating objects.

Page 324 of 362


Introduction to UML

We can see from the diagram that a person may attend many meetings.

We need to keep information about how awake that person was ; we can do this by adding the attribute
attentiveness to the association.

Association class subtleties (Role should probably not be an association class).

Page 325 of 362


Introduction to UML

These diagrams have relatively the same form.

However, we can imagine one Company playing different roles in the same Contract, but it´s harder to imagine
a Person having multiple competencies in the same skill;

In the UML, only the latter case is legal. You can have only one competency for each combination of Person
and Skill.

Implement an association class as if it were a full class, but provide methods that get information to the
classes linked by the association class.

You can use a «temporal» keyword on the association.

Parameterized Class:

Several languages, particularly C++, have the notion of a parameterized class, or template.

Page 326 of 362


Introduction to UML

It is useful for working with collections in a strongly typed language.

You can define behavior for sets in general by defining a template class Set.

Use the general definition to make set classes for more specific elements: Set employeeSet;

The T in the diagram is a placeholder for the type parameter.

A use of a parameterized class, such as Set, is called a bound element.

You can show a bound element in two ways.

The first way mirrors the C++ syntax.

The alternative notation reinforces the link to the template and allows you to rename the bound element.

The «bind» stereotype is a stereotype on the refinement relationship.
Page 327 of 362
Introduction to UML

Using a bound element is not the same as subtyping.

Parameterized classes allow you to use a derived typing.

When you write the body of the template, you may invoke operations on the parameter.

Later declaring a bound element, the compiler tries to ensure that the supplied parameter supports the
operations required by the template.

Visibility:

Visibility is simple in principle but has complex subtleties.

A class has public and private elements.

Any class can use public elements.

private elements can be used only by the owning class.

Within the UML, you can tag any attribute or operation with a visibility indicator.

You can use any marker you like, and meaning of the marker is language dependent.

The UML provides three abbreviations for visibility: + (public), ­(private), and # (protected).

In C++:

A public member is visible anywhere in the program and may be called by any object within the system.

A private member may be used only by the class that defines it.

Page 328 of 362


Introduction to UML

A protected member may be used only by (a) the class that defines it or (b) a subclass of that class.

In Smalltalk, all instance variables are private, and all operations are public.

Private in Smalltalk is similar to protected in C++.

Though Java is similar to C++, it adds a new visibility level, called package.

A member with package visibility may be accessed only by instances of other classes within the same
package.

A protected member may be accessed by subclasses but also by any other class in the same package as the
owning class.

Java also allows classes to be marked public or package.

Public members of a public class may be used by any class that imports the package to which the class
belongs.

When you are using visibility, use the rules of the language in which you are working.

Page 329 of 362


Introduction to UML

Interaction Diagrams, Packages and Collaborations

Introduction

We will discuss the following topics in this chapter:

Sequence Diagrams

Collaboration Diagrams

Comparing Sequence and Collaboration Diagrams

When to Use Interaction Diagrams

Packages

Collaborations

When to Use Package Diagrams and Collaborations.

Sequence Diagrams

Interaction diagrams describe how groups of objects collaborate in some behaviour. They are models.

An object is shown as a box at the top of a dashed vertical line within a sequence diagram.

This vertical line is called the object′s lifeline and represents the object′s life during the interaction.

Each message is represented by an arrow between the lifelines of two objects. Occurrence of the message order
is indicated top to bottom on the page.

Each message is labelled at minimum with the message name;

Self­ call: a message that an object sends to itself, by sending the message arrow goes back to the same lifeline.

When an object is active, include an activation box to show.

Condition: indicates when a message is sent only if a condition is true.

The iteration marker ­ shows that a message is sent many times to multiple receiver objects, as would happen
when you are iterating over a collection.

Return: Indicates only a return from a message but not a new message.

Sequence diagrams are also valuable for concurrent processes.

Page 330 of 362


Introduction to UML

We see some objects that are checking a bank transaction.

When a Transaction is created, it creates a Transaction Coordinator to coordinate the checking of the Transaction.

In turn this coordinator creates a number (in this case, two) of transaction Checker objects, each of which is
responsible for a particular check.

Page 331 of 362


Introduction to UML

Since each checker is called asynchronously and proceeds in parallel, this process would make it easy to add different
checking processes.

When a Transaction Checker completes, it gives notification to the Transaction Coordinator.

The coordinator looks to see whether all the checkers called back. If they haven′t, the coordinator does nothing. If
they have, and if all of them are successful, the coordinator notifies the transaction that all is well.

The half­arrowheads indicate an asynchronous message. As an asynchronous message does not block the caller,
it can carry on with its own processing.

An asynchronous message can do one of the following three things:

Create a new thread, in which case it links to the top of an activation.

Create a new object.

Communicate with a thread that is already running.

Object deletion is shown with a large X.

Collaboration Diagrams:

The second form of the interaction diagram is the collaboration diagram.

The example objects are shown as icons.

Arrows indicate the messages sent within the given use case.

The sequence is indicated by numbering the messages.

The spatial layout allows you to show how the objects are linked together.

You can use one of several numbering schemes for collaboration diagrams.

Page 332 of 362


Introduction to UML

Comparing Sequence and Collaboration Diagrams:

Sequence diagram: helps to see the order in which things occur.

Collaboration diagram: use the layout to indicate how objects are statically connected.

Both are simple ­ You can easily see the messages by looking at the diagram.

The technique begins to break down once you try to represent something other than a single sequential process
without much conditional or looping behaviour, the technique begins to break down.

They can be awkward to use when exploring alternatives.

Trying out alternatives leads to too much rubbing out and redrawing.

When to Use Interaction Diagrams:

At the time of looking at the behaviour of several objects within a single use case.

While good at showing collaborations among the objects;

Not so good at precise definition of the behaviour.

To look at the behaviour of a single object across many use cases, use a state diagram.

To look at behaviour across many use cases or many threads, consider an activity diagram.

Packages:

The idea of a package can be applied to any model element, not just classes.

Page 333 of 362


Introduction to UML

Package diagram: diagram that shows packages of classes and the dependencies among them.

A dependency exists between two elements if changes to the definition of one element may cause changes to the
other.

With classes, dependencies exist for various reasons:

One class sends a message to another;

One class has another as part of its data;

One class mentions another as a parameter to an operation.

If a class changes its interface, any message it sends may no longer be valid.

The UML has many varieties of dependency, each with particular semantics and stereotype.

Any dependency exists between any two classes in the packages leads to a dependency between two packages
exists.

The dependencies are intransitives with packages.

A transitive dependency makes it difficult to limit the scope of changes with compilation.

Package diagrams are a key tool in maintaining control over a system´s overall structure.

Collaborations:

Besides containing classes, a package can contain collaborations.

Collaboration is a name given to the interaction between two or more classes.

Collaboration can be elaborated with more than one interaction diagram, but each diagram shows a different path.

Page 334 of 362


Introduction to UML

It can also add a class diagram to show the classes that participate in the collaboration.

Use them to show common behaviour across packages.

Show those aspects of the classes that are relevant.

Interaction diagrams show how they work.

Most of the same collaboration is used by different classes in the system.

Each time, the basic way the classes work is the same, but classes and operations are named differently, and
there may be minor differences in the implementation.

You can illustrate this by parameterizing the collaboration.

First, you draw a diagram which shows the various roles that various objects play in the collaboration.

Next, you show how a set of classes participate in the collaboration.

Page 335 of 362


Introduction to UML

The UML also uses the term pattern as a synonym for parameterized collaboration.

When to Use Package Diagrams and Collaborations:

Packages are an important tool for large projects.

Use packages whenever a class diagram encompasses the whole system which is no longer legible on a single
letter­size (or A4) sheet of paper.

Packages are particularly useful for testing.

Each package should have one or more test classes.

The test the behaviour of the package.

Collaborations are useful for referring a particular interaction.

Parameterized collaborations are useful when you have several as well as similar collaborations in your system.

Page 336 of 362


Introduction to UML

State and Activity Diagrams

Introduction

We will discuss the following topics in this chapter:

Concurrent State Diagrams

When to Use State Diagrams

Decomposing an Activity

Dynamic Concurrency

Swimlanes

When to Use Activity Diagrams

State Diagrams

In order to describe the behaviour of a system State diagrams are a helpful technique.

They describe all the possible states that a particular object can get into and how the object′s state changes as
a result of events that reach the object.

State diagrams are drawn for a single class to show the lifetime behaviour of a single object.

Figure shows a UML state diagram for an order in the order processing system.

The diagram indicates the various states of an order.

Begun from the start point show an initial transition into the Checking state.

Page 337 of 362


Introduction to UML

This transition is labelled "/get first item."

The syntax for a transition label has three parts, all of which are optional: Event [Guard] / Action.

We have only the action "get first item." Once we perform that action, we enter the Checking state.

This state has an activity associated with it which is indicated by a label with the syntax do/activity. The activity
is called "check item."

Actions are associated with transitions. They are considered to be processes that occur quickly and are not
interruptible.

Activities are associated with states and can take longer. An activity may be interrupted by some event.

A guard is a logical condition that will return only "true" or "false."

A guarded transition occurs only if the guard resolves to "true."

Sometimes cancelling an order may take place at any point before it is delivered.

We could do this by drawing separate transitions from each of the Checking, Waiting, and Dispatching states.

The best alternative is to create a superstate of all three states and then draw a single transition from that.
The substates simply inherit any transitions on the superstate.

Concurrent State Diagrams:

The concurrent sections of the state diagram are places in which at any point, the given order is in two
different states, which are totally different from one another.
Page 338 of 362
Introduction to UML

When the order leaves the concurrent states, it is in only a single state.

When a given object has sets of independent behaviours. Concurrent state diagrams are useful.

You should not get too many concurrent sets of behaviours occurring in a single object.

If you have so many complicated concurrent state diagrams for a single object, you should consider splitting
the object into separate objects.

An order starts off in both the Checking and Authorizing states.

If the "check payment" activity of the Authorizing state completes successfully first, the order will be in the
Checking and Authorized states.

If the "cancel" event occurs, the order will be in only the Cancelled state.

When to Use State Diagrams:

The behaviour of an object across several use cases are well described by State diagrams.

It is not applicable for describing behaviour involves a number of objects collaborating.

Combining state diagrams with other techniques is a useful one.

The behaviour of several objects in a single use case can better be described by Interaction diagrams.

Activity diagrams are good at showing the general sequence of actions for several objects and use cases.

Use state diagrams only for those classes that exhibit interesting behaviour, where building the state diagram
helps you understand what is going on.
Page 339 of 362
Introduction to UML

Decomposing an Activity

The activity diagram combines ideas from several techniques: the event diagrams of Jim Odell, SDL state
modelling techniques, workflow modelling, and Petri nets.

An activity can be narrowed down into sub activities.

As a superstate and substates do on a state diagram, this works out.

Either you can just show the superstate on the parent diagram or you can show the superstate and its internal
behaviour inside of it.

The delivery activity can be used in other contexts, the advantages of the explicit start and end states.

The parent diagram is decoupled from the contents of the subsidiary diagram.

Dynamic Concurrency

Page 340 of 362


Introduction to UML

Dynamic concurrency allows you to show iterations without having to construct a loop.

In the below figure, the activity Fill Line Item is executed once for each line item on the order.

The execution of the activity (many times) is indicated by the multiplicity marker (*).

when all the line items have been filled, the transition to Deliver Order is triggered.

If several activities need to be executed together in the same manner, you can show this by making Fill Line
Item a composite activity.

Swimlanes:

Activity diagrams do not convey which class is responsible for which activity.

In domain modelling, this doesn’t mean that the diagram conveys which people or departments are
responsible for each activity.

Swimlanes are a way around this.

Arranging your activity diagrams into vertical zones separated by lines need for using swimlanes.

Each zone represents the responsibilities of a particular class.

They combine the activity diagram′s depiction of logic with the interaction diagram′s depiction of responsibility.

They are difficult to draw on a complex diagram.

You need to assign activities to classes before you are done.

Page 341 of 362


Introduction to UML

When to Use Activity Diagrams:

When to use activity diagrams:

Analyzing a use case.

Understanding workflow.

Describing a complicated sequential algorithm.

Dealing with multithreaded applications.

When not to use activity diagrams:

Trying to see how objects collaborate.

Trying to see how an object behaves over its lifetime.

Representing complex conditional logic.

Page 342 of 362


Introduction to UML

Physical Diagrams

Introduction

We will discuss the following topics in this chapter:

Deployment Diagrams

Component Diagrams

Combining Component and Deployment Diagrams

When to Use Physical Diagrams.

Deployment Diagrams

A deployment diagram expresses the physical relationships between software and hardware components in
the delivered system.

A deployment diagram is good at showing how components and objects are routed and move around a
distributed system.

Each node represents some kind of computational unit­in most cases, a piece of hardware on a deployment
diagram.

The hardware is either a simple device of sensor or it could be a mainframe.

Connections among nodes show the communication paths over which the system will interact.

An efficient deployment diagram controls the following parameters, it is very important.

Performance.

Scalability.

Maintainability.

Portability.

The following deployment diagram is a sample to give an idea of the deployment view of order management
system.

Page 343 of 362


Introduction to UML

Here we have shown nodes as:

Monitor.

Modem.

Caching server.

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.

Component Diagrams:

A component diagram shows the various components in a system and their dependencies.

A component represents a physical module of code.

It is often the same as a package; sometimes it may be different, since components represent the physical
packaging of code.

Though a single class is present in multiple components, that class can be defined in only one package.

For example, the Java string class is part of the java.lang package, but it turns up in lots of components.

The dependencies among the components show how changes of one component cause other components to
change.

Component diagrams are used during the implementation phase of an application. Hence the purpose of the
component diagram can be summarized as:

Page 344 of 362


Introduction to UML

Visualize the components of a system.

Construct executable by using forward and reverse engineering.

Describe the organization and relationships of the components.

The following is a component diagram for order management system. Here the artifacts are files.

The diagram shows the files in the application and their relationships.

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.

Combining Component and Deployment Diagrams:

You can place the component diagram on the deployment diagram.

This indicates which components run on which nodes.

When a component has more than one interface, you can see which components communicate with each
interface.

In the example figure the server application has two interfaces.

One interface is used by the application façade running on a PC; whereas the other interface is used by a
configuration component running on the server.

Page 345 of 362


Introduction to UML

In the diagram, the Liver Unit UI and the Liver Unit Client Facade both run on a Windows PC.

The Liver Unit UI is dependent on the Liver Unit Client Facade, since it calls specific methods on the facade.

Although the communication is two­way, in the sense that the Facade returns data, the Facade is not aware of

Page 346 of 362


Introduction to UML

who is calling it and is thus not dependent on the UI.

In the communication between the two Health Care Domain components, both are aware that they are talking
to another Health Care Domain component, so the communication dependency is two­way.

The two domain components run on separate nodes.

When to Use Physical Diagrams:

Where to use Deployment Diagrams?

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.

Where to use Component Diagrams?

Model the components of a system.

Model database schema.

Model executables of an application.

Model system´s source code.

Page 347 of 362


Introduction to UML

Case Studies

Introduction: UML includes the following 9 diagrams

Class diagram: These diagrams depict the behavioral pattern of the system, i.e. how each and every class is inter­
related to the other one, what sort of a relationship exists among each of the classes, etc. There would be only
one class diagram possible for a single system. If there is a multi­system requirement, Class diagrams of one
system can be connected to the class diagrams of another system.

Object diagram: It is similar to class diagram and is said to be a real entity or an instance of the Class used to be
mentioned the extra properties of an entity besides the properties depicted by the class.

Use case diagram: Use case diagram comprises of use cases and actors such. Here also relationship between
the use cases and the actors is numerous. A use case diagram shows all the actions that a particular actor needs
to perform throughout the system at any point of time. There would be only one use case diagram each system.

Sequence diagram: This diagram, as the name suggests, contains the flow of actions which is in a sequence way.
Those actions are processed through a system and the life lines of the entities, when and how are they accessed.
It has the security for which entity can process which entity and which one is visible, etc. There can be many
number of sequence diagrams per each activity being done. 

Collaboration diagram: It is a polymorphic form of the sequence diagram. It has the different representation but
same application. To create one sequence diagram, it′s very simple to create its collaboration diagram with a
single key click that varies from to software to software. There can be numerous collaboration diagrams per each
activity being done because there can be many number of sequence diagrams.

Activity diagram: It denotes the structural flow of the activities like a flow chart with decision boxes enhanced and
hence is useful for troubleshooting like raising exceptions when a particular action is done and the alternative to
be done when something abnormally occurs. There can be only one activity diagram for the entire system
including total performance of the system.

Statechart diagram: This diagram is a polymorphic form of the activity diagram. It is different in representation but
same in application. It looks similar to a finite state machine state transition diagrams.

Deployment diagram: Deployment diagram is employed when we need to deploy development of the application.
A single deployment diagram is possible for a single system.

Component diagram: Component diagram represents the components in which the particular application needs to
be installed or implemented on. It also shows the type of relation that exists among the various components that
are represented. Hence, only a single component diagram representing all the components and their relations is
needed for the entire system.

Library Management System:

Problem Statement:

The case study titled Library Management System is library management software for the purpose of
monitoring and controlling the transactions in a library.

This case study library gets us to know the complete information about the library and the daily transactions
taken place in a Library.

Page 348 of 362


Introduction to UML

We need to maintain the record of new books and retrieve the details of books available in the library which mainly
focuses on basic operations in a library like adding new member, new books, and update new information,
searching books and members and facility to borrow and return books.

It features a familiar and well thought­out, an attractive user interface, combined with strong searching,
insertion and reporting capabilities.

The report generation facility of library system helps to get a good idea of which are the books borrowed by the
members, makes users possible to generate hard copy.

The following is a brief description on the functions achieved by this case study:

End­Users:

Librarian: To maintain and update the records and also to cater the needs of the users.

Reader: Need books to read and also places various requests to the librarian.

Vendor: To provide and meet the requirement of the prescribed books.

Class Diagram:

Classes identified:

Library.

Librarian.

Books Database.

User.

Page 349 of 362


Introduction to UML

Vendor.

Use­case Diagram:

Librarian: Issue a book, Update and maintain records, Request the vendor for a book, Track complaints.

User: Register, Login, Search a book, Request for issue, View history, Request to the Librarian, Unregister.

Books Database: Update records, Show books status.

Vendors: Provide books to the library, Payment acknowledgement.

Sequence Diagram:

Sequence diagram indicates searching for a book and issuing it as per the request by the user from the
librarian.

Page 350 of 362


Introduction to UML

Collaboration Diagram:

Collaboration Diagram shows searching for a book and issuing it as per the request by the user from the
librarian:

Activity Diagram:

Page 351 of 362


Introduction to UML

Activities:

User Login and Authentication.

Search book operation for Reader.

Acknowledge and Issue books to the users by the Librarian.

Provide books requested by the Librarian from the Vendor.

Bill payment from the Librarian to the Vendor.

Status of the books updated in the Books Database.

State Chart Diagram:

States:

Authentication.

Successfully logged on or re­login.

Search for a book (user) / request the vendor (librarian) / provide the requested book (vendor).

Receive acknowledgement.

Logged off / re­search / new function.

Transitions:

Authenticate ­­­> Logged in.

Logged in ­­­> Search <­­­> Acknowledgement.
Page 352 of 362
Introduction to UML

Logged in ­­­> Request Vendor <­­­> Provide Book <­­­> Acknowledgement.

Logged in ­­­> Provide Book <­­­> Acknowledgement.

Acknowledgement ­­­> Logged off.

Component Diagram:

Components:

Register Page (visitor / vendor).

Login Page (user / librarian / vendor).

Search Page (user / librarian / vendor).

Request Vendor Page (librarian).

Request Book Issue Page (user / vendor).

Issue Status Page (librarian).

Make Payment Page (librarian / vendor).

Provide Books Page (librarian).

Logout Page (user / librarian / vendor).

Page 353 of 362


Introduction to UML

Deployment Diagram:

Systems Used by/for

Local Consoles / Computers for login and search purposes by users, librarian and vendors.

Library LAN Server interconnecting all the systems to the Database.

Internet to provide access to Vendors to supply the requested books by the Librarian.

Vendor Server to maintain the records of the requests made by the librarian and books equipped with the
library.

Online Mobile Recharge:

Problem Statement:

Page 354 of 362


Introduction to UML

The case study ´Online Mobile Recharge´ gives us the information about all the mobile service providers. It
provides us the complete information regarding any mobile service provider in terms of their plans, options,
benefits, etc.

Suppose, any Airtel customer wants to have the information of all the schemes and services provided by the
company, he/she can have the information and according to his convenience he can recharge the mobile from
the same application. The major advantage of this proposed system is to have the recharging facility of any
service provider under same roof.

End users:

Service Provider: Service Provider is the one who is nothing but the mobile service provider like all the
companies who are giving the mobile connections come under this module.

Functionality of this module is to make the mobile recharging of their company basing on the availability of
balance in the admin account.

Request comes from the user and it is going to be verified at the admin for the availability of balance and then
the request is forwarded to the service provided to make the mobile recharge.

Third party System Administrator:

Administrator is the one who monitors all users and user transactions.

Admin also monitors all the Service Providers, all the user accounts, and amounts paid by the user and
amounts paid to Service providers.

When the request given by the user admin checks the available balance in the user account then request is
forwarded to the Service Provider from there user request gets processed.

Admin has the complete information related to user and all the information related to the schemes and other
information of different recharge coupons provided by the Service Providers.

All the data is maintained at the Admin level. Admin is having the rights to restrict any user.

User:

There are 2 categories in the user Module:

Registered User

Visitor.

Any person who wants to utilize the services of Online Mobile Recharge at anytime from anywhere they should get
registered in this application.

After getting registered user can recharge the mobile at any time and from anywhere.

Visitor is the one who visits the Online Mobile Recharge application and have the complete information related to
the Service Providers and can make the mobile recharge by entering the bank details or by giving the credit card
details.

Class Diagram:

Page 355 of 362


Introduction to UML

Classes Identified:

User: Registered, Visitor.

Third Party System Administrator.

Third Party Server/ Database.

Service Provider.

Direct or Non­ Third Party User (Direct access through Service Provider Site).

Use­Case Diagram:

User: Register, Recharge, Select Payment Gateway, Select service Provider, Make payment.

Third Party Administrator: Forward User request to Service Provider, Track Complaints.

Third Party Server/ Database: Authenticate the Registered users, Maintain the Log.

Service Provider: Recharge the user requested either directly or through the third party system, Provide
various plans to the user.

Sequence Diagram:

Sequence Diagram for a user to recharge his account through third party site:

Collaboration Diagram:

Collaboration diagram for a user to recharge his account through third party site:

Activity Diagram:

Activities:

User login and authentication for registered user.

Forward the request to service provider if logged in as an Administrator.

Enter service provider site for a direct user.

Enter recharge amount.

Select Payment Gateway.

Login and authenticate Bank Account.

Make payment.

Check for the recharge processed successfully or not.

State Chart Diagram:

States:

Authentication for registered users / Registration for unregistered users.

Page 356 of 362


Introduction to UML

Successfully logged on or re­login.

Operator Selection.

Show the tariff plans available and applicable.

Request recharge.

Go through Payment Gateway Transaction process.

Authentication to enter the gateway site.

Successfully logged on or re­login.

Payment made.

Logged off.

Transitions:

Registration ­­­> Authenticate ­­­> Logged in

Logged in ­­­> Operator Selection ­­­> Tariff Plans <­­­> Request Recharge.

Operator Selection ­­­> Request Recharge ­­­> Payment Gateway Transaction.

Payment Gateway Transaction ­­­> Operator Selection.

Payment Gateway Transaction ­­­> Logged off.

Component Diagram:

Components:

Third Party Home Page (visitor / registered user / admin / service provider).

Third Party Register Page (visitor).

Third Party Login Page (registered user).

Third Party User History Page (registered user).

Request Recharge Page (registered user).

Third Party Logout Page (registered user).

Online Payment Transaction Gateway Page (direct user / registered user).

Service Provider Home Page (visitor / registered user / admin / service provider).

Tariff Plans Page (visitor / registered user / admin / service provider).

Deployment Diagram:

Systems Used:

Consoles / Computers for registration, login purposes by third party users and for quick recharge by direct

Page 357 of 362


Introduction to UML

users.

Third Party Server to receive and respond to all the requests from various users.

Internet to provide access to users to recharge their accounts through payment gateways by placing
requests through Third Party Sites and Service Providers sites.

Payment Gateway Server like Bank´s server to provide online payment through their personal accounts to
meet the requirements of the users.

Service Provider Server to maintain the records of the requests made by the users.

Page 358 of 362


Introduction to UML

Assignments

Create 2 UML Use Case Diagrams for describing the use cases for ATM
functions:

An automated teller machine (ATM) or the automatic banking machine (ABM) is a banking subsystem (subject)
that provides bank customers with access to financial transactions in a public space without the need for a
cashier, clerk, or bank teller.

Customer (actor) uses bank ATM to Check Balances of his/her bank accounts, Deposit Funds, Withdraw Cash
and/or Transfer Funds (use cases). ATM Technician provides Maintenance and Repairs. All these use cases
also involve Bank actor whether it is related to customer transactions or to the ATM servicing.

In many bank ATMs, the customer is authenticated by inserting a plastic ATM card and entering a personal
identification number (PIN).

Customer Authentication use case is required for every ATM transaction so we show it as include relationship.

Besides including this use case transaction generalizations make the ATM Transaction an non concrete use
case.

Page 359 of 362


Introduction to UML

Create an activity diagram for online shopping:

Online customer can browse or search items, view specific item, add it to shopping cart, view and update
shopping cart, checkout.

User can view shopping cart at any time. Checkout is assumed to include user registration and login.

Create a UML class diagram which shows a domain model for online
shopping

Each customer has unique id and is linked to exactly one account. Account owns shopping cart and orders. As
a web user to be able to buy items online Customer could register.

Customer need not to be a web user because purchases could also be made by phone or by ordering from

Page 360 of 362


Introduction to UML

catalogues. Web user has login name which also serves as unique id.

Web user could be in several states ­ new, active, temporary blocked, or banned, and be linked to a shopping
cart. Shopping cart belongs to account. Account owns customer orders.

Customer may have no orders. Customer orders are sorted and unique. Each order could refer to
several payments, possibly none. Every payment has unique id and is related to exactly one account.

Each order has current order status. Both order and shopping cart have line items linked to a specific product.
Each line item is related to exactly one product. A product could be associated to many line items or no item at
all.

Create a UML sequence diagram which shows how Facebook (FB) user
could be authenticated in a web application to allow access to his/her FB
resources

Facebook uses OAuth 2.0 protocol framework which enables web application (called "client"), which is usually
not the FB resource owner but is acting on the FB user´s behalf, to request access to resources controlled by
the FB user and hosted by the FB server. Instead of using the FB user credentials to access protected
resources, the web application obtains an access token.

Web application should be registered by Facebook to have an application ID (client_id) and secret
(client_secret). When request to some protected Facebook resources is received, web browser ("user agent")

Page 361 of 362


Introduction to UML

is redirected to Facebook´s authorization server with application ID and the URL the user should be redirected
back to after the authorization process.

User receives back Request for Permission form. If the user authorizes the application to get his/her data,
Facebook authorization server redirects back to the URI that was specified before together with authorization
code ("verification string"). The authorization code can be exchanged by web application for an OAuth access
token.

If web application obtains the access token for a FB user, it can perform authorized requests on behalf of that
FB user by including the access token in the Facebook Graph API requests. If the user did not authorize web
application, Facebook issues redirect request to the URI specified before, and adds the error_reason
parameter to notify the web application that authorization request was denied.

Page 362 of 362

You might also like