164 - CS6456 Object Oriented Programming - Notes 1 | PDF | Queue (Abstract Data Type) | Class (Computer Programming)
0% found this document useful (0 votes)
5 views179 pages

164 - CS6456 Object Oriented Programming - Notes 1

The document provides a comprehensive lesson plan for Object Oriented Programming (OOP) in C++, covering key concepts, skills, objectives, and outcomes. It explains the differences between object-oriented and procedure-oriented programming, introduces fundamental OOP concepts such as classes, objects, inheritance, and polymorphism, and includes examples and applications. Additionally, it outlines the structure of C++ programs, data types, variable scopes, and modifiers.

Uploaded by

chaitra3029
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views179 pages

164 - CS6456 Object Oriented Programming - Notes 1

The document provides a comprehensive lesson plan for Object Oriented Programming (OOP) in C++, covering key concepts, skills, objectives, and outcomes. It explains the differences between object-oriented and procedure-oriented programming, introduces fundamental OOP concepts such as classes, objects, inheritance, and polymorphism, and includes examples and applications. Additionally, it outlines the structure of C++ programs, data types, variable scopes, and modifiers.

Uploaded by

chaitra3029
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 179

Click Here for Object Oriented Programming full study material.

CS6456 - Object Oriented Programming

1. CONTENT LIST:
Why Object-Oriented Programming in C++

2. SKILLS ADDRESSED:
Learning

3. OBJECTIVE OF THIS LESSON PLAN:


i. To facilitate students understand the basics of C++.
ii. To enable students understand the various Object Oriented Concepts .

4. OUTCOMES:
i. Explain the various Object Oriented concepts.
ii. Explain the difference between object oriented and procedure oriented concepts.

5. LINK SHEET:
i. What is Object oriented programming?
ii. List the Object Oriented concepts

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)

Object Oriented Programming is a method of visualizing and programming the


problem in a global way. Object oriented programming is a technique to envision the problem as
a collection of objects that represents real world entities
Features :
 Emphasis is on data rather than procedure
 Programs are divided into objects
 Functions that operate on the data of the object are tied together in data structure
 Data is hidden and cannot be accessed by external functions
 Objects may communicate with each other usibg functions

INTRODUCTION TO C++:
Difference between Procedure oriented programming and Object oriented programming.

POP OOP
1) Emphasis on non-real item Emphasis on real item
2) Programs are divided into Programs are divided into Objects
functions Data are not sharable
3) Data are sharable Object Oriented Programming
4) Structured Programming Bottom-Up Approach
5) Top-Down Approach

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Tokens
Smallest individual unit in a program. C++ tokens are Keywords, Identifiers, Constants,
Strings, Operators.

Data Types in C++


 Built-in Data types
 User Defined Data types
 Derived Data Types

Block Structure of C++


Include Files
Class Declaration
Member Function Defintions
Main Function Program

Operators in C++
 :: Scope Resolution Operator
 : :* Member pointer operator
 ->* Pointer-to-Pointer Member using pointer to object Operator
 .* Pointer-to-Pointer Member using object Operator
 delete Memory Release Operator
 endl Line feed operator
 new Memory allocation operator
 Setw Memory width operator
 Casting operator for C-style casting from any type to any other irrelevant type
reinterpret_cast
 const_cast Removing the const nature of a variable while casting.
 dynamic_cast casting operator that can be used to safeguard against irrelevant
casting ,used in case of polymorphic classes.
 typeid used to find type of an object at run time
 throw useful for throwing an exception at the time of an error.

Expressions in C++
Constant Expressions
Integral Expressions
Float Expressions
Pointer Expressions
Relational Expressions
Logical Expressions
Bitwise Expressions

OBJECT ORIENTED PROGRAMMING CONCEPTS :


 Objects
 Classes
 Data Abstraction and Encapsulation

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

 Inheritance
 Polymorphism
 Dynamic binding
 Message passing

OBJECTS :
Objects are the basic run-time entities in an object – oriented system. They represent a
person,place,a bank account or a table of data or item that a program has to handle.When
a program is executed,the objects interact by passing messages to each other.
Eg: Customer and account are two objects. The customer object may send a
message to the account object requesting for bank balance.
CLASSES :
A Class is collection of objects of similar type. Objects are variables of the type class.
Classes are user defined data-types and behave like a built in type of a programming
language.
Eg: Apple, Mango, Orange are members of the class fruits.
Syntax : fruit mango ; Fruits

Apple Mango Orange

METHODS AND MESSAGES :


Objects communicate with each other by passing messages to each other. The
code for providing response to the message is known as method.
Eg :
Teacher SomeTeacher;
SomeTeacher = RollCall6030903.getTeacher();
The first statement defines an object SomeTeacher of class Teacher. Here,Teacher
is known as userdefined type and SomeTeacher is a variable of that type. The call to the
function is defined inside the class RollCall.The statement RollCall6030903.getTeacher()
calls the function getTeacher() which works on the object RollCall6030903 and get the
Teacher associated with that roll call. In the statement SomeTeacher =
RollCall6030903.getTeacher(), wec assign the Teacher object returned by that function to
SomeTeacher.
Here, getTeacher() is known as a message being passed to an object
RollCall6030903.The object executes the body of the function getTeacher() and returns
with the response,the Teacher object. The code for providing response to the message,
i.e,. body of the function getTeacher() is known as method.

ABSTRACTION AND ENCAPSULATION :


Abstraction refers to the act of representing the essential features without
including the background details or explanation. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size,weight,cost and functions to operate on these

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

attributes. The attributes are called members and functions as methods or member functions. The
classes use Data abstraction and are called Abstract Data Types(ADT).
Eg: Abstraction example: ATM is a good example of abstraction, we doesn't know what
are all the internal processes that are going when we access it..instead we know only the
inquiries, deposit, withdrawal etc.
The wrapping up of data and functions into a single unit(class) is called Encapsulation.
The data is not accessible to the outside world ,and those functions that are wrapped in the class
can access it. This insulation of program by direct access of program is called data hiding or
Information hiding.
Eg: Ink is the important component in pen but it is hiding by some other material.
you don't "need to know the internal working of the mobile phone to operate" with it.
You have an interface to use the device behaviour without knowing implementation details.

INHERITANCE :
Inheritance is the processs by which the object of one class acquire the properties
of objects of another class.
Eg: class Bird-> class flying bird ->class robin

ABSTRACT CLASSES:
Abstract class is the class with no objects. The abstract classes does not represent any
real-world entity. The purpose of an abstract class (often referred to as an ABC) is to provide an
appropriate base class from which other classes can inherit. Abstract classes cannot be used to
instantiate objects and serves only as an interface.
Consider the following example where parent class provides an interface to the base class to
implement a function called getArea():
#include <iostream>

using namespace std;

// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};

int main(void)
{
Rectangle Rect;
Triangle Tri;

Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;

Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result:

Total Rectangle area: 35


Total Triangle area: 17

ABSTRACT CLASSES:
Abstract class is the class with no objects. The abstract classes does not represent any
real-world entity. The purpose of an abstract class (often referred to as an ABC) is to provide an

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

appropriate base class from which other classes can inherit. Abstract classes cannot be used to
instantiate objects and serves only as an interface.
Consider the following example where parent class provides an interface to the base class to
implement a function called getArea():
#include <iostream>

using namespace std;

// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};

// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};

int main(void)
{

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Rectangle Rect;
Triangle Tri;

Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;

Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result:

Total Rectangle area: 35


Total Triangle area: 17

POLYMORPHISM:
Polymorphism is a concept in which the operation may exhibit different behaviour in
different instances.
Eg: addition will sum two numbers in case of numerical operands. In case of
string , it will form a third string by concatenation.

An example C++ program :


Adding two number using class (C++)
#include<iostream.h>
#include<conio.h>
class add
{
private:
int a,b,c;
public:
void read()
{
cout<<"enter Two Number "<<endl;
cin>>a>>b;
}
void display()
{
cout<<" A = "<<a<<endl;
cout<<" B = "<<b<<endl;

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

cout<<"Sum = "<<c<<endl;
}
void sum()
{
c= a+b;
}
};
void main()
{
add x; // x is a object off add
clrscr();
x.read();
x.sum();
x. display();
getch();
}

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Real time applications
 Neural networks and parallel processing
 Object oriented systems

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
Native Types and Statements

2. SKILLS ADDRESSED:
Learning

3. OBJECTIVE OF THIS LESSON PLAN:


iii. To facilitate students understand the basics of C++.
iv. To enable students understand the various Object Oriented Concepts .

4. OUTCOMES:
iii. Explain the various Object Oriented concepts.
iv. Explain the difference between object oriented and procedure oriented concepts.

5. LINK SHEET:
iii. What is Object oriented programming?
iv. List the Object Oriented concepts

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)

C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming


language that supports procedural, object-oriented, and generic programming.

C++ is regarded as a middle-level language, as it comprises a combination of both high-level


and low-level language features.
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New
Jersey, as an enhancement to the C language and originally named C with Classes but later it was
renamed C++ in 1983.

C++ is a superset of C, and that virtually any legal C program is a legal C++ program.

C++ Compiler:
This is actual C++ compiler, which will be used to compile your source code into final
executable program.

Most C++ compilers don't care what extension you give your source code, but if you don't
specify otherwise, many will use .cpp by default

Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can
have compilers either from HP or Solaris if you have respective Operating Systems.

C++ Program Structure:


Let us look at a simple code that would print the words Hello World.
#include <iostream>
using namespace std;

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

// main() is where program execution begins.

int main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
Comments in C++
C++ supports single line and multi-line comments. All characters available inside any comment
are ignored by C++ compiler.

C++ comments start with /* and end with */. For example:

/* This is a comment */

/* C++ comments can also


* span multiple lines
*/

A comment can also start with //, extending to the end of the line. For example:

#include <iostream>
using namespace std;

main()
{
cout << "Hello World"; // prints Hello World

return 0;
}
C++ Primitive Built-in Types:
C++ offer the programmer a rich assortment of built-in as well as user-defined data types.
Following table list down seven basic C++ data types:

Type Keyword
Boolean bool
Character char
Integer int
Floating point float

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Double floating point double


Valueless void
Wide character wchar_t

Variable Definition & Initialization in C++:


Some examples are:

extern int d, f // declaration of d and f


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
C++ Variable Scope:
A scope is a region of the program and broadly speaking there are three places where variables
can be declared:

 Inside a function or a block which is called local variables,

 In the definition of function parameters which is called formal parameters.

 Outside of all functions which is called global variables.

C++ Constants/Literals:
Constants refer to fixed values that the program may not alter and they are called literals.
Constants can be of any of the basic data types and can be divided in Integer Numerals, Floating-
Point Numerals, Characters, Strings and Boolean Values.

Again, constants are treated just like regular variables except that their values cannot be modified
after their definition.

C++ Modifier Types:


C++ allows the char, int, and double data types to have modifiers preceding them. A modifier is
used to alter the meaning of the base type so that it more precisely fits the needs of various
situations.
The data type modifiers are listed here:

 signed
 unsigned
 long
 short

The modifiers signed, unsigned, long, and short can be applied to integer base types. In
addition,signed and unsigned can be applied to char, and long can be applied to double.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For
exampleunsigned long int.
C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can simply
use the word unsigned, short, or long, without the int. The int is implied. For example, the
following two statements both declare unsigned integer variables.
unsigned x;
unsigned int y;

Storage Classes in C++:


A storage class defines the scope (visibility) and life time of variables and/or functions within a
C++ Program. These specifiers precede the type that they modify. There are following storage
classes which can be used in a C++ Program

 auto

 register

 static

 extern

 mutable

C++ Operators:
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provides following type of operators:

 Arithmetic Operators ( +, -, \, *, ++, --)

 Relational Operators (==, !=, >. <, >=, <=)

 Logical Operators (&&, ||, ! )

 Bitwise Operators (& |, ^, ~, <<, >>)

 Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=)

 Misc Operators ( sizeof, & cast, comma, conditional etc.)

C++ Loop Types:


C++ programming language provides the following types of loops to handle looping
requirements. Click the following links to check their detail.

Loop Type Description


while loop Repeats a statement or group of statements while a given

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

condition is true. It tests the condition before executing the loop


body.
Execute a sequence of statements multiple times and abbreviates
for loop
the code that manages the loop variable.
Like a while statement, except that it tests the condition at the end
do...while loop
of the loop body
You can use one or more loop inside any another while, for or
nested loops
do..while loop.

C++ Decision Making:


C++ programming language provides following types of decision making statements. Click the
following links to check their detail.

Statement Description
An if statement consists of a boolean expression followed by
if statement
one or more statements.
An if statement can be followed by an optional else statement,
if...else statement
which executes when the boolean expression is false.
A switch statement allows a variable to be tested for equality
switch statement
against a list of values.
You can use one if or else if statement inside another if or
nested if statements
else if statement(s).
You can use one swicth statement inside another switch
nested switch statements
statement(s).

C++ Functions:
The general form of a C++ function definition is as follows:

return_type function_name( parameter list )


{
body of the function
}

A C++ function definition consists of a function header and a function body. Here are all the
parts of a function:

 Return Type: A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.
 Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

 Parameters: A parameter is like a placeholder. When a function is invoked, you pass a


value to the parameter. This value is referred to as actual parameter or argument. The parameter
list refers to the type, order, and number of the parameters of a function. Parameters are optional;
that is, a function may contain no parameters.
 Function Body: The function body contains a collection of statements that define what
the function does.

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Real time applications
 Neural networks and parallel processing
 Object oriented systems

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
Functions and Pointers

2. SKILLS ADDRESSED:
Learning

3. OBJECTIVE OF THIS LESSON PLAN:


v. To facilitate students understand the basics Functions and Pointers

4. OUTCOMES:
v. Explain the various Functions.
vi. Explain in detail about pointers.

5. LINK SHEET:
v. What is Friend Functions
vi. Illustrate Arrays and pointers

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)

FRIEND FUNCTIONS
The non-member functions are not allowed to access an object’s private and protected
members.
C++ allows the non-member functions to access the private members by using friend functions.
The functions that are declared with the keyword friend are called friend functions.

Characteristics:
 The scope of the friend function is not limited to the class in which it has been declared.
 A friend function can not be called using the object of that class.
 It can not access the class members directly.
 It can be declared either in private or in public.

Bridging classes with friend functions

Syntax: friend returntype functionname(classname object);


friend: keyword
returntype: return type of the function
functionname: name of the function
classname: name of the class in which it is declared

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Example
class student
{
private:
int number;
int total;
public:
void getdata(int n, int t)
{
number = n;
total = t;
}
friend void display(student s); // The non-member function display is declared as friend
};
void display(student s) // non-member function accesses the private members because it is
friend.
{
cout<<”Roll number is:”<<s.number;
cout<<”Total is:”<<s.total;
}

void main() Output:


{ Roll number is: 5
student s; Total is: 800
s.getdata(5,800);
cout<<”result=”<<display(s);
}

Example
class one
{
private:
int n1;
public:
void getdata(int num1)
{
n1=num1;
}
friend int add(one o, two t); // The non-member function add is declared as friend
};
class two
{
private:
int n2;
public:
void getdata(int num2)

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

{
n2=num2;
{
friend int add(one o, two t); // The non-member function add is declared as friend
};

int add(one o, two t) // non-member function accesses the private members n1& n2. because it
is friend
{
return(o.n1 + t.n2);
}

void main()
{
one o;
two t;
o.getdata(5);
t.getdata(10);
cout<<”result=”<<add(o,t);
}

Friend functions are special functions. The class grants these functions a special
privilege to access private variables of the class. It is given by writing the specific function’s
prototype in the class definition precedes with word friend.

Eg : friend somefunction(list of arguments)

Eg: program:
#include<iostream.h>
#include<conio.h>
class base
{
int val1,val2;
public:
void get()
{
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(base ob);
};
float mean(base ob)
{
return float(ob.val1+ob.val2)/2;
}

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

void main()
{
clrscr();
base obj;
obj.get();
cout<<"\n Mean value is : "<<mean(obj);
getch();
}

Output:

Enter two values: 10, 20


Mean Value is: 15

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Real time applications
 Neural networks and parallel processing
 Object oriented systems

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
Implementing ADTs in the Base Language

2. SKILLS ADDRESSED:
Learning

3. OBJECTIVE OF THIS LESSON PLAN:


To facilitate students understand the Implementation of ADT’s

4. OUTCOMES:
Explain with an example about Stack.

5. LINK SHEET:
Illustrate Stack.

6. EVOCATION: (10 Minutes)

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

7. LECTURE NOTES: (40 Minutes)

Object-Oriented Programming: Stacks and Queues


Abstract

This reading reviews strategies of problem solving discussed in this class. Then, building on
recent work, the reading introduces stacks and queues as examples of useful classes.

Handling Complexity:

Since many computer applications address complex problems, problem-solving with computers
must include a consideration of the handling of complexity. Already in this course, we have seen
several such strategies and use a variety of language capabilities.

 Solutions can be built up using a sequence of procedures, where each procedure


accomplishes a relatively simple task.
 Local variables and parameters allow work within a procedure to focus on a narrow,
tightly controlled task even if the procedure will be used within a more complex problem.
 Using recursion, processing can focus on relatively simple base cases and the reduction
of complex cases to simpler ones.
 Data abstraction allows data to be viewed in logical groups and structures, such as lists,
vectors, association lists, and records.
 Procedural abstraction allows general procedures to be defined abstractly to cover many
types of cases; mechanisms for variable arity procedures, procedure parameters, and
currying give flexibility and allow general procedures to be tailored to specific needs.
 Libraries allow commonly used operations to be developed once and reused in other
applications.
 Classes and objects package data and operations together in a convenient package that
can be used in various applications.

Each of these topics allow us to organize a complex problem or task into relatively manageable
parts and then to focus on those parts. Note that several of the items lists involve abstraction: we
think of processing at a relatively high level, with details pushed aside to a separate procedure,
structure, or file.

For example, association lists allow a natural matching of keyword and data, so we can focus
upon the storage and retrieval of these information pairs. The assoc procedure retrieves relevant
data, and we need not be bothered about the details of this retrieval.

Stacks as ADTs:

Stacks provide a common and useful example of classes and objects.

Conceptually, the stack class or abstract data type mimics the information kept in a pile on a
desk. Informally, we first consider materials on a desk, where we may keep separate piles for
bills that need paying, magazines that we plan to read, and notes we have taken. These piles of

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

materials have several properties. Each pile contains some papers (information). In addition, for
each pile, we can do several tasks:

 Start a new pile,


 Place new information on the top of a pile,
 Take the top item off of the pile,
 Read the item on the top, and
 Determine whether a pile is empty. (There may be nothing at the spot where the pile
should be.)

These operations allow us to do all the normal processing of data at a desk. For example, when
we receive bills in the mail, we add them to the pile of bills until payday comes. We then take the
bills, one at a time, off the top of the pile and pay them until the money runs out.

When discussing these operations it is customary to call the addition of an item to the top of the
pile a Push operation and the deletion of an item from the top a Pop operation.

More formally, a stack is defined as a class that can store data and that has the following
operations:

 Make-Stack
Create a new, empty stack object.
 Empty
Empty returns true or false (#t or #f), depending upon whether the stack contains any
items or not.
 Push
Push adds the specified item to the top of the stack.
 Pop
If the stack is not empty, Pop removes the top item from the stack, and this item is
returned.
If the stack is empty, nothing is returned, and an error is reported.
 Top
If the stack is not empty, the top item is returned, but the contents of the stack are not
changed.
If the stack is empty, nothing is returned, and an error is reported.

This specification says nothing about how we will program the various stack operations; rather,
it tells us how stacks can be used. We can also infer some limitations on how we can use the
data. For example, stack operations allow us to work with only the top item on the stack. We
cannot look at other pieces of data lower down in the stack without first using Pop operations to
clear away items above the desired one.

A Push operation always puts the new item on top of the stack, and this is the first item returned
by a Pop operation. Thus, the last piece of data added to the stack will be the first item removed.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Classes, Objects, and Messages

One approach to problem solving involves an initial focus on data elements, operations on those
elements, and relationships among data. Within computer science, such an approach motivates
the viewpoint ofobject-oriented programming or OOP. When working within an OOP
framework, it is useful to distinguish between the general notion of a class and specific uses of
the class with definite data values, which constitutes an object.

Utilizing the notion of abstraction, we think of objects as self-contained entities, just as we might
consider each pile on a desk as an separate, independent collection of material. To support this
image, processing involving objects consists of sending messages to the objects, letting the
object react to the object in an appropriate way, and receiving responses back. Within an OOP
context, a mechanism for interpreting messages is called a method. For example, if our desk had
two piles -- one for magazines and one for bills, we might have the following interaction:

> (define mag-pile ... ) ; make stack for magazines


; (details of call dependent on implementation)
> (define bill-pile ... ) ; make stack for bills
; (details of call dependent on implementation)
> (bill-pile 'push! "mortgage") ; send push message to bill-pile
> (bill-pile 'push! "doctor's bill")
> (bill-pile 'push! "credit card")
> (bill-pile 'empty?) ; send empty? message to bill-pile
#f ; response from empty? message
> (mag-pile 'empty?)
#t
> (mag-pile 'push! "Communications of the ACM - April 1997")
> (mag-pile 'push! "CS Education Bulletin - Spring 1998")
> (bill-pile 'top) ; send top message to bill-pile
"credit card" ; data returned as message response
> (mag-pile 'top)
"CS Education Bulletin - Spring 1988"
> (bill-pile 'pop!)
"credit card"
> (bill-pile 'top)
"doctor's bill"

Stacks in Scheme

To implement a class within Scheme, we may proceed following the recent reading on Abstract
Data Types. The simplest approach is to maintain an internal list within the abstract data type or
class. With this approach, push and pop operations insert or delete an item from the front of the
list, the empty operation tests if the list is empty, and the top operation returns the head of the list.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

The Queue Abstract Data Type

Sometimes we want a data structure that provides access to its elements on "first-in, first-out"
basis, rather than the "last-in, first-out" constraint that a stack imposes. (For example, it might be
prudent to treat that pile of unpaid bills a little differently, adding new elements at the bottom of
the pile rather than the top, Paying off the most recent bill first, as in a stack, can make one's
other, older creditors a little testy.)

Such a structure is called a queue. Like a line of people waiting for some service, a queue
acquires new elements at one end (the rear of the queue) and releases old elements at the other
(the front). Here is the abstract data type definition for queues, with the conventional names for
the operations:

 create
Create a new, empty queue object.
 empty
Determine whether the queue is empty; return true if it is and false if it is not.
 enqueue
Add a new element at the rear of a queue.
 dequeue
Remove an element from the front of the queue and return it. (This operation cannot be
performed if the queue is empty.)
 front
Return the element at the front of the queue (without removing it from the queue).
(Again, this operation cannot be performed if the queue is empty.)

Queues in Scheme

The implementation of queues in Scheme is somewhat trickier than the implementation of stacks.
Again, we'll keep the elements of the queue in a list. However, it turns out that
the enqueue operation can be slightly faster if we represent an empty queue by a list containing
one element, a "dummy header," and store the actual queue elements after this header, oldest
first. The dummy header is not inserted byenqueue and cannot be removed by the dequeue. It is
not there to provide a value, but just to keep the list from becoming null, so that one can always
apply the set-cdr! procedure to it without first testing to see whether it is null. The fact that the
underlying list never becomes completely null is an invariant of this implementation of queues.

The other novel feature of this implementation is that we'll actually be accessing the list through
two different fields, front and rear. The front field always contains the entire list structure,
beginning with the dummy header; (cdr front) is the list of the actual elements of the queue,
and (cadr front) is the first element of the queue (when it is not empty). The rear field, on the
other hand, is always a one-element list; it contains the last element of the queue, except when
the queue is empty, in which case the rear field contains the dummy header.

The following box-and-pointer diagram shows a queue into which the symbols a, b, and c have
been enqueued, in that order:

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Here is the constructor for queue objects:

(define queue-class
(lambda ()
(let* ((front (list 'dummy-header))
(rear front))
(lambda (message . arguments)
(case message
((empty?) (null? (cdr front)))

((enqueue!)
(if (null? arguments)
(error 'queue-class "method ENQUEUE!: An argument is required")
(begin

; Attach a new cons cell behind the current rear


; element.

(set-cdr! rear (list (car arguments)))

; Advance REAR so that it is once more a list


; containing only the last element.

(set! rear (cdr rear)))))

((dequeue!)
(if (null? (cdr front))
(error 'queue-class "method DEQUEUE!: The queue is empty")

; Recover the first element of the queue (not including


; the dummy header).

(let ((removed (cadr front)))

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

; Splice out the element to be dequeued.

(set-cdr! front (cddr front))

; If you just spliced out the last element of the


; queue, reset REAR so that it holds the dummy
; header.

(if (null? (cdr front))


(set! rear front))
removed)))

((front)
(if (null? (cdr front))
(error 'queue "method FRONT: The queue is empty")
(cadr front)))

(else (error 'queue-class "unrecognized message")))))))

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Real time applications
 Neural networks and parallel processing
 Object oriented systems

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
Data Hiding and Member Functions

2. SKILLS ADDRESSED:
Learning

3. OBJECTIVE OF THIS LESSON PLAN:


i. To facilitate students understand the basics of Data hiding.
ii. To enable students understand the member functions .

4. OUTCOMES:
i. Explain Data hiding.
ii. Explain member function.

5. LINK SHEET:
i. What is Data hiding?
ii. Illustrate member function

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)

Encapsulation is an Object Oriented Programming concept that binds together the data and
functions that manipulate the data, and that keeps both safe from outside interference and misuse.
Data encapsulation led to the important OOP concept of data hiding.

Data encapsulation is a mechanism of bundling the data, and the functions that use them
and data abstraction is a mechanism of exposing only the interfaces and hiding the
implementation details from the user.

C++ supports the properties of encapsulation and data hiding through the creation of user-
defined types, called classes. We already have studied that a class can contain private,
protected and publicmembers. By default, all items defined in a class are private. For example:

class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

The variables length, breadth, and height are private. This means that they can be
accessed only by other members of the Box class, and not by any other part of your program.
This is one way encapsulation is achieved.
To make parts of a class public (i.e., accessible to other parts of your program), you must declare
them after the public keyword. All variables or functions defined after the public specifier are
accessible by all other functions in your program.
Making one class a friend of another exposes the implementation details and reduces
encapsulation. The ideal is to keep as many of the details of each class hidden from all other
classes as possible.

Data Encapsulation Example:

Any C++ program where you implement a class with public and private members is an
example of data encapsulation and data abstraction. Consider the following example:

#include <iostream>
using namespace std;

class Adder{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;

a.addNum(10);
a.addNum(20);
a.addNum(30);

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

cout << "Total " << a.getTotal() <<endl;


return 0;
}

When the above code is compiled and executed, it produces the following result:

Total 60

Above class adds numbers together, and returns the sum. The public
members addNum and getTotalare the interfaces to the outside world and a user needs to know
them to use the class. The private member total is something that is hidden from the outside
world, but is needed for the class to operate properly.

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Real time applications
 Neural networks and parallel processing
 Object oriented systems

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
Object Creation and Destruction

2. SKILLS ADDRESSED:
Learning

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students understand the concept of constructor .
 To enable the students to understand about copy constructor and constructor with
default arguments using programs
 To enable the students to understand about destructors.

4. OUTCOMES:
 Explain the concept of constructor.
 Explain copy constructor.
 Illustrate constructor with default arguments.
 Explain how objects can be initialized dynamically.
 Explain about default constructor.
 Explain about destructors.
 Explain the difference between constructors and destructors

5. LINK SHEET:
 What is a constructor ?
 Give the syntax for constructor.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

 What is a copy constructor. Explain with example program.


 Give a C++ program for constructor with default arguments.
 Illustrate dynamic initialization of objects .
 What is a default constructor?
 Explain constructors with an example program.
 What is a destructor ?
 Illustrate destructor with an example program.
 Write a program using both constructor and destructor

6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)

CONSTRUCTORS :
Constructor is a special member function whose task is to initialize object of its class. It is
special because its name is same as that of class name. The constructor is invoked when an
object of its associated class is created. It is called constructor because it constructs the values of
data members of its class.
Eg : Program

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Integer int1; creates an object int1.


A constructor that accepts no parameter is called Default constructor.
Eg: The default constructor for class A is A:A() ;
If no such constructor is defined, then the compiler supplies a default constructor and the
statement
A a; invokes a default constructor of the compiler to create the object a.
Characteristics of constructor function :
 They should be declared in the public section
 They are invoked automatically when the objects are created.
 They donot have return types,not even void
 They cannot be inherited.
 They have default arguments
 They cannot be virtual
 We cannot refer to their address
 An object with a constructor cannot be used as a member of union
 They make implicit calls to the operators „new‟ and „delete‟ when memory allocation is
required.

PARAMETERIZED CONSTRUCTORS :
The constructors that take arguments are called Parameterized constructors.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

The object declaration is done by 2 ways:


1 : By calling the constructor explicitly
Integer int1 = integer(0,100) ;
2: By calling the constructor implicitly
Integer int1(0,100);
The parameter of the constructor can be of any type.

Eg : Program

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Output:

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

The constructor function can also be defined as inline function

The constructor can accept a reference to its class as a parameter and the constructor is called
copy constructor.

MULTIPLE CONSTRUCTORS IN A CLASS :[OVERLOADED CONSTRUCTOR]


We can use more than one constructor in a same class .

Eg : Program

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

This declares three constructors for integer object.


1st constructor receives no arguments
2nd constructor receives 2 integer arguments
3rd constructor receives one integer object as an argument
If more than one constructor is used in a class, it is known as overloaded constructor.
Eg : Program

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

OUTPUT:

COPY CONSTRUCTOR :
A copy constructor takes a reference to an object of the same class as itself as an
argument.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

OUTPUT :

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

CONSTRUCTOR WITH DEFAULT ARGUMENTS :


Constructor with default argument argument can be declared as:

Here, the value of real is 5.0 and imag takes the value 0.0

Here, real takes the value 2.0 to real and 3.0 to imag.

DYNAMIC INITIALIZATION OF OBJECTS :


Class objects can be initialized dynamically. That means, the initial value of an object can
be provided at run time.
Advantage : various initialization formats can be provided using overloaded operators.
Eg: Program :

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

OUTPUT :

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

The parameters for the program are given at run time and the inputs can be:
 Amount, period and interest in decimal form

 Amount , period and interest in percent form

 Amount and period

DYNAMIC CONSTRUCTOR:
Allocation of memory to objects at the time of their construction is called
dynamic construction of objects. The memory is allocated with the help of new operator.
Eg : Program

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

OUTPUT :

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

DESTRUCTORS :
When we define a variable in C++, it continues to be in effect until its scope is over. If a
variable is defined as global variable, it remains in effect throughout the execution of the
program. If a variable is defined as a local variable, it remains in effect till the function exits.
Destructors are opposites to constructors. They come into effect when objects goes out of scope.
Like constructors, they are automatically applied and calling them explicitly is also possible. The
main use of destructor is to return the memory that is dynamically allocated. They also providing
terminating effects.
A destructor is a special member function of a class that is executed whenever an object
of it's class goes out of scope or whenever the delete expression is applied to a pointer to the
object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither
return a value nor can it take any parameters. Destructor can be very useful for releasing
resources before coming out of the program like closing files, releasing memories etc.

Following example explains the concept of destructor:

#include <iostream>

using namespace std;

class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration

private:
double length;
};

// Member functions definitions including constructor


Line::Line(void)
{
cout << "Object is being created" << endl;
}
Line::~Line(void)
{
cout << "Object is being deleted" << endl;
}

void Line::setLength( double len )


{
length = len;
}

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

double Line::getLength( void )


{
return length;
}
// Main function for the program
int main( )
{
Line line;

// set line length


line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;
}

When the above code is compiled and executed, it produces the following result:

Object is being created


Length of line : 6
Object is being deleted

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Real time applications
 Neural networks and parallel processing
 Object oriented systems

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
 Iterators and Containers

2. SKILLS ADDRESSED:
 Learning

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students understand the basics of Iterators and Containers

4. OUTCOMES:
i. Explain Iterators.
ii. Explain Containers.

5. LINK SHEET:
i. What Iterators
ii. Illustrate Containers

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)

STL Containers & Iterators

Container classes are the solution to a specific kind of code reuse problem. They are building
blocks used to create object-oriented programs – they make the internals of a program much
easier to construct.

A container class describes an object that holds other objects. Container classes are so important
that they were considered fundamental to early object-oriented languages. In Smalltalk, for
example, programmers think of the language as the program translator together with the class
library, and a critical part of that library is the container classes. So it became natural that C++
compiler vendors also include a container class library. You‟ll note that the vector was so useful
that it was introduced in its simplest form very early in this book.

Like many other early C++ libraries, early container class libraries followed Smalltalk‟s object-
based hierarchy, which worked well for Smalltalk, but turned out to be awkward and difficult to
use in C++. Another approach was required.

This chapter attempts to slowly work you into the concepts of the C++ Standard Template
Library (STL), which is a powerful library of containers (as well as algorithms, but these are
covered in the following chapter). In the past, I have taught that there is a relatively small subset
of elements and ideas that you need to understand in order to get much of the usefulness from the
STL. Although this can be true it turns out that understanding the STL more deeply is important
to gain the full power of the library. This chapter and the next probe into the STL containers and
algorithms.

Containers and iterators

If you don‟t know how many objects you‟re going to need to solve a particular problem, or how
long they will last, you also don‟t know how to store those objects. How can you know how
much space to create? You can‟t, since that information isn‟t known until run time.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

The solution to most problems in object-oriented design seems flippant: you create another type
of object. For the storage problem, the new type of object holds other objects, or pointers to
objects. Of course, you can do the same thing with an array, but there‟s more. This new type of
object, which is typically referred to in C++ as a container (also called a collection in some
languages), will expand itself whenever necessary to accommodate everything you place inside
it. So you don‟t need to know how many objects you‟re going to hold in a collection. You just
create a collection object and let it take care of the details.

Fortunately, a good OOP language comes with a set of containers as part of the package. In C++,
it‟s the Standard Template Library (STL). In some libraries, a generic container is considered
good enough for all needs, and in others (C++ in particular) the library has different types of
containers for different needs: a vector for consistent access to all elements, and a linked list for
consistent insertion at all elements, for example, so you can choose the particular type that fits
your needs. These may include sets, queues, hash tables, trees, stacks, etc.

All containers have some way to put things in and get things out. The way that you place
something into a container is fairly obvious. There‟s a function called “push” or “add” or a
similar name. Fetching things out of a container is not always as apparent; if it‟s an array-like
entity such as a vector, you might be able to use an indexing operator or function. But in many
situations this doesn‟t make sense. Also, a single-selection function is restrictive. What if you
want to manipulate or compare a group of elements in the container?

The solution is an iterator, which is an object whose job is to select the elements within a
container and present them to the user of the iterator. As a class, it also provides a level of
abstraction. This abstraction can be used to separate the details of the container from the code
that‟s accessing that container. The container, via the iterator, is abstracted to be simply a
sequence. The iterator allows you to traverse that sequence without worrying about the
underlying structure – that is, whether it‟s a vector, a linked list, a stack or something else. This
gives you the flexibility to easily change the underlying data structure without disturbing the
code in your program.

From the design standpoint, all you really want is a sequence that can be manipulated to solve
your problem. If a single type of sequence satisfied all of your needs, there‟d be no reason to
have different kinds. There are two reasons that you need a choice of containers. First, containers
provide different types of interfaces and external behavior. A stack has a different interface and
behavior than that of a queue, which is different than that of a set or a list. One of these might
provide a more flexible solution to your problem than the other. Second, different containers
have different efficiencies for certain operations. The best example is a vector and a list. Both are
simple sequences that can have identical interfaces and external behaviors. But certain operations
can have radically different costs. Randomly accessing elements in a vector is a constant-time
operation; it takes the same amount of time regardless of the element you select. However, in a
linked list it is expensive to move through the list to randomly select an element, and it takes
longer to find an element if it is further down the list. On the other hand, if you want to insert an
element in the middle of a sequence, it‟s much cheaper in a list than in a vector. These and other
operations have different efficiencies depending upon the underlying structure of the sequence.
In the design phase, you might start with a list and, when tuning for performance, change to a

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

vector. Because of the abstraction via iterators, you can change from one to the other with
minimal impact on your code.

In the end, remember that a container is only a storage cabinet to put objects in. If that cabinet
solves all of your needs, it doesn‟t really matter how it is implemented (a basic concept with
most types of objects). If you‟re working in a programming environment that has built-in
overhead due to other factors, then the cost difference between a vector and a linked list might
not matter. You might need only one type of sequence. You can even imagine the “perfect”
container abstraction, which can automatically change its underlying implementation according
to the way it is used.

STL reference documentation

You will notice that this chapter does not contain exhaustive documentation describing each of
the member functions in each STL container. Although I describe the member functions that I
use, I‟ve left the full descriptions to others: there are at least two very good on-line sources of
STL documentation in HTML format that you can keep resident on your computer and view with
a Web browser whenever you need to look something up. The first is the Dinkumware library
(which covers the entire Standard C and C++ library) mentioned at the beginning of this book
section (page XXX). The second is the freely-downloadable SGI STL and documentation, freely
downloadable at http://www.sgi.com/Technology/STL/. These should provide complete
references when you‟re writing code. In addition, the STL books listed in Appendix XX will
provide you with other resources.

The Standard Template Library

The C++ STL[16] is a powerful library intended to satisfy the vast bulk of your needs for
containers and algorithms, but in a completely portable fashion. This means that not only are
your programs easier to port to other platforms, but that your knowledge itself does not depend
on the libraries provided by a particular compiler vendor (and the STL is likely to be more tested
and scrutinized than a particular vendor‟s library). Thus, it will benefit you greatly to look first to
the STL for containers and algorithms, before looking at vendor-specific solutions.

A fundamental principle of software design is that all problems can be simplified by introducing
an extra level of indirection. This simplicity is achieved in the STL using iterators to perform
operations on a data structure while knowing as little as possible about that structure, thus
producing data structure independence. With the STL, this means that any operation that can be
performed on an array of objects can also be performed on an STL container of objects and vice
versa. The STL containers work just as easily with built-in types as they do with user-defined
types. If you learn the library, it will work on everything.

The drawback to this independence is that you‟ll have to take a little time at first getting used to
the way things are done in the STL. However, the STL uses a consistent pattern, so once you fit
your mind around it, it doesn‟t change from one STL tool to another.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Consider an example using the STL set class. A set will allow only one of each object value to
be inserted into itself. Here is a simple set created to work with ints by providing int as the
template argument toset:

//: C04:Intset.cpp
// Simple use of STL set
#include <set>
#include <iostream>
using namespace std;

int main() {
set<int> intset;
for(int i = 0; i < 25; i++)
for(int j = 0; j < 10; j++)
// Try to insert multiple copies:
intset.insert(j);
// Print to output:
copy(intset.begin(), intset.end(),
ostream_iterator<int>(cout, "\n"));
} ///:~

The insert( ) member does all the work: it tries putting the new element in and rejects it if it‟s
already there. Very often the activities involved in using a set are simply insertion and a test to
see whether it contains the element. You can also form a union, intersection, or difference of
sets, and test to see if one set is a subset of another.

In this example, the values 0 - 9 are inserted into the set 25 times, and the results are printed out
to show that only one of each of the values is actually retained in the set.

The copy( ) function is actually the instantiation of an STL template function, of which there are
many. These template functions are generally referred to as “the STL Algorithms” and will be
the subject of the following chapter. However, several of the algorithms are so useful that they
will be introduced in this chapter. Here, copy( ) shows the use of iterators. The set member
functions begin( ) and end( )produce iterators as their return values. These are used by copy( ) as
beginning and ending points for its operation, which is simply to move between the boundaries
established by the iterators and copy the elements to the third argument, which is also an iterator,
but in this case, a special type created for iostreams. This places int objects on cout and
separates them with a newline.

Because of its genericity, copy( ) is certainly not restricted to printing on a stream. It can be used
in virtually any situation: it needs only three iterators to talk to. All of the algorithms follow the
form ofcopy( ) and simply manipulate iterators (the use of iterators is the “extra level of
indirection”).

Now consider taking the form of Intset.cpp and reshaping it to display a list of the words used in
a document. The solution becomes remarkably simple.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

//: C04:WordSet.cpp
#include "../require.h"
#include <string>
#include <fstream>
#include <iostream>
#include <set>
using namespace std;

int main(int argc, char* argv[]) {


requireArgs(argc, 1);
ifstream source(argv[1]);
assure(source, argv[1]);
string word;
set<string> words;
while(source >> word)
words.insert(word);
copy(words.begin(), words.end(),
ostream_iterator<string>(cout, "\n"));
cout << "Number of unique words:"
<< words.size() << endl;
} ///:~

The only substantive difference here is that string is used instead of int. The words are pulled
from a file, but everything else is the same as in Intset.cpp. The operator>> returns a
whitespace-separated group of characters each time it is called, until there‟s no more input from
the file. So it approximately breaks an input stream up into words. Each string is placed in
the set using insert( ), and the copy( )function is used to display the results. Because of the
way set is implemented (as a tree), the words are automatically sorted.

Consider how much effort it would be to accomplish the same task in C, or even in C++ without
the STL.

The basic concepts

The primary idea in the STL is the container (also known as a collection), which is just what it
sounds like: a place to hold things. You need containers because objects are constantly marching
in and out of your program and there must be someplace to put them while they‟re around. You
can‟t make named local objects because in a typical program you don‟t know how many, or what
type, or the lifetime of the objects you‟re working with. So you need a container that will expand
whenever necessary to fill your needs.

All the containers in the STL hold objects and expand themselves. In addition, they hold your
objects in a particular way. The difference between one container and another is the way the
objects are held and how the sequence is created. Let‟s start by looking at the simplest
containers.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

A vector is a linear sequence that allows rapid random access to its elements. However, it‟s
expensive to insert an element in the middle of the sequence, and is also expensive when it
allocates additional storage. A deque is also a linear sequence, and it allows random access
that‟s nearly as fast as vector, but it‟s significantly faster when it needs to allocate new storage,
and you can easily add new elements at either end (vector only allows the addition of elements
at its tail). A list the third type of basic linear sequence, but it‟s expensive to move around
randomly and cheap to insert an element in the middle. Thuslist, deque and vector are very
similar in their basic functionality (they all hold linear sequences), but different in the cost of
their activities. So for your first shot at a program, you could choose any one, and only
experiment with the others if you‟re tuning for efficiency.

Many of the problems you set out to solve will only require a simple linear sequence like
a vector, deque or list. All three have a member function push_back( ) which you use to insert a
new element at the back of the sequence (deque and list also have push_front( )).

But now how do you retrieve those elements? With a vector or deque, it is possible to use the
indexing operator[ ], but that doesn‟t work with list. Since it would be nicest to learn a single
interface, we‟ll often use the one defined for all STL containers: the iterator.

An iterator is a class that abstracts the process of moving through a sequence. It allows you to
select each element of a sequence without knowing the underlying structure of that sequence.
This is a powerful feature, partly because it allows us to learn a single interface that works with
all containers, and partly because it allows containers to be used interchangeably.

One more observation and you‟re ready for another example. Even though the STL containers
hold objects by value (that is, they hold the whole object inside themselves) that‟s probably not
the way you‟ll generally use them if you‟re doing object-oriented programming. That‟s because
in OOP, most of the time you‟ll create objects on the heap with new and then upcast the address
to the base-class type, later manipulating it as a pointer to the base class. The beauty of this is
that you don‟t worry about the specific type of object you‟re dealing with, which greatly reduces
the complexity of your code and increases the maintainability of your program. This process of
upcasting is what you try to do in OOP with polymorphism, so you‟ll usually be using containers
of pointers.

Consider the classic “shape” example where shapes have a set of common operations, and you
have different types of shapes. Here‟s what it looks like using the STL vector to hold pointers to
various types of Shape created on the heap:

//: C04:Stlshape.cpp
// Simple shapes w/ STL
#include <vector>
#include <iostream>
using namespace std;

class Shape {
public:
virtual void draw() = 0;

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

virtual ~Shape() {};


};

class Circle : public Shape {


public:
void draw() { cout << "Circle::draw\n"; }
~Circle() { cout << "~Circle\n"; }
};

class Triangle : public Shape {


public:
void draw() { cout << "Triangle::draw\n"; }
~Triangle() { cout << "~Triangle\n"; }
};

class Square : public Shape {


public:
void draw() { cout << "Square::draw\n"; }
~Square() { cout << "~Square\n"; }
};

typedef std::vector<Shape*> Container;


typedef Container::iterator Iter;

int main() {
Container shapes;
shapes.push_back(new Circle);
shapes.push_back(new Square);
shapes.push_back(new Triangle);
for(Iter i = shapes.begin();
i != shapes.end(); i++)
(*i)->draw();
// ... Sometime later:
for(Iter j = shapes.begin();
j != shapes.end(); j++)
delete *j;
} ///:~

The creation of Shape, Circle, Square and Triangle should be fairly familiar. Shape is a pure
abstract base class (because of the pure specifier =0) that defines the interface for all types
of shapes. The derived classes redefine the virtual function draw( ) to perform the appropriate
operation. Now we‟d like to create a bunch of different types of Shape object, but where to put
them? In an STL container, of course. For convenience, this typedef:

typedef std::vector<Shape*> Container;

creates an alias for a vector of Shape*, and this typedef:

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

typedef Container::iterator Iter;

uses that alias to create another one, for vector<Shape*>::iterator. Notice that
the container type name must be used to produce the appropriate iterator, which is defined as a
nested class. Although there are different types of iterators (forward, bidirectional, reverse, etc.,
which will be explained later) they all have the same basic interface: you can increment them
with ++, you can dereference them to produce the object they‟re currently selecting, and you can
test them to see if they‟re at the end of the sequence. That‟s what you‟ll want to do 90% of the
time. And that‟s what is done in the above example: after creating a container, it‟s filled with
different types of Shape*. Notice that the upcast happens as
the Circle, Square or Rectangle pointer is added to the shapes container, which doesn‟t know
about those specific types but instead holds only Shape*. So as soon as the pointer is added to
the container it loses its specific identity and becomes an anonymous Shape*. This is exactly
what we want: toss them all in and let polymorphism sort it out.

The first for loop creates an iterator and sets it to the beginning of the sequence by calling
the begin( ) member function for the container. All containers have begin( ) and end( ) member
functions that produce an iterator selecting, respectively, the beginning of the sequence and one
past the end of the sequence. To test to see if you‟re done, you make sure you‟re != to the iterator
produced by end( ). Not <or <=. The only test that works is !=. So it‟s very common to write a
loop like:

for(Iter i = shapes.begin(); i != shapes.end(); i++)

This says: “take me through every element in the sequence.”

What do you do with the iterator to produce the element it‟s selecting? You dereference it using
(what else) the „*‟ (which is actually an overloaded operator). What you get back is whatever the
container is holding. This container holds Shape*, so that‟s what *i produces. If you want to
send a message to the Shape, you must select that message with ->, so you write the line:

(*i)->draw();

This calls the draw( ) function for the Shape* the iterator is currently selecting. The parentheses
are ugly but necessary to produce the proper order of evaluation. As an alternative, operator-> is
defined so that you can say:

i->draw();

As they are destroyed or in other cases where the pointers are removed, the STL containers do
not call delete for the pointers they contain. If you create an object on the heap with new and
place its pointer in a container, the container can‟t tell if that pointer is also placed inside another
container. So the STL just doesn‟t do anything about it, and puts the responsibility squarely in
your lap. The last lines in the program move through and delete every object in the container so
proper cleanup occurs.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

It‟s very interesting to note that you can change the type of container that this program uses with
two lines. Instead of including <vector>, you include <list>, and in the first typedef you say:

typedef std::list<Shape*> Container;

instead of using a vector. Everything else goes untouched. This is possible not because of an
interface enforced by inheritance (there isn‟t any inheritance in the STL, which comes as a
surprise when you first see it), but because the interface is enforced by a convention adopted by
the designers of the STL, precisely so you could perform this kind of interchange. Now you can
easily switch between vector and listand see which one works fastest for your needs.

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Real time applications
 Neural networks and parallel processing
 Object oriented systems

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
Templates - Function templates, class templates

2. SKILLS ADDRESSED:
Listening
Understanding
Analysis and implementation

3. OBJECTIVE OF THIS LESSON PLAN:


i. To facilitate students understand about templates.
ii. To enable students to understand about Single argument function templates.
iii. To enable students to understand about generic sorting
iv. To enable students to understand about Single argument function templates.
v. To enable students to understand about Function template with multiple arguments
,two generic arguments and non-generic parameters.
vi. To enable students to understand about class templates.

4. OUTCOMES:
i. Explain about Templates.
ii. Explain about Function Templates.
iii. Explain generic sorting
iv. Explain non-generic parameters and arguments
v. Explain template argument deduction.
vi. Define class template outside the class.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

5. LINK SHEET:
i. What is a Template?
ii. What is function template?
iii. What are the drawbacks of using Macros?
iv. Explain about single argument function template.
v. What is instantiation?
vi. What is Generic sorting?
vii. Explain function templates with multiple arguments ad 2 arguments.
viii. Explain about non-generic parameters and arguments in template function.
ix. Explain template argument deduction
x. What is a class template and define it.
xi. Explain class template with multiple generic datatypes.
xii. Explain class templates using non-type arguments and default arguments.
xiii. What is static data members?
xiv. Explain the friends of class templates

6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)

Template uses object-based model of reusability.


template<class L> class Key
{
L k;
L* kptr;
int length;
public:
Key(L);

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

// ...
};

Function templates :
Function templates are generic functions, which work for any data type that is
passed to them.
Drawbacks of using macros :
 Macros are not visible to the compiler.

 The type related information is lost in macros

 Macros are evaluated twice.

Single argument function templates:


 Function templates are simple to implement .

 Just some mechanical changes are need to be done in the normal function to
make it a function template.

Eg :

If you want to create a function approximate(), which determines whether two values are
within 5% of each other, you can define the following template:

#include <math.h>
template <class T> int approximate (T first, T second)
{
double aptemp=double(first)/double(second);
return int(abs(aptemp-1.0) <= .05);
};

Assuming that you have two values of type float you want to compare. You can use
the approximate function template:

float a=3.24, b=3.35;


if (approximate(a,b))
cout << "a and b are pretty close" << endl;

The above example generates the following template function to resolve the call:

int approximate(float,float).

Structuring Your Program Using Templates

You can structure your program three ways, by using templates:

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

 Include the function template definition (both the .h and .c files) in all files that may
reference the corresponding template functions.
 Include the function template declaration (the .h file only) in all files that may reference
the corresponding template functions. However, include the function definition (both
the .h and .c files) in one file only.
 Include the declaration of the function templates in a header file and the definition in a
source file that has the same name. When you include the header file in your source, the
compiler automatically generates the template functions.

The following examples use two files to illustrate all three methods:

File stack.h
#ifndef _STACK_TPL_H
#define _STACK_TPL_H

template<class T>
class stack
{
private:
T* v;
T* p;
int sz;

public:
stack( int );
~stack();
void push( T );
};
#endif

File stackdef.h
#include "stack.h"

template<class T> stack<T>::stack( int s )


{
v = p = new T[sz=s];
}

template<class T> stack<T>::~stack()


{
delete [] v;
}

template<class T> void stack<T>::push( T a )


{
*p++ = a;
}

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

To instantiate a stack of 50 ints, you would declare the following in each source file that requires
it:

stack<int> intStack(50);

For method 1, each source file that uses the template should include
both stack.h and stackdef.h.

For method 2, every source file should include stack.h. However, only one of the files needs to
includestackdef.h.

For method 3, every source file should include stack.h. The compiler automatically generates
the template functions in the TEMPINC PDS. You can use the TEMPINC option to set your
own TEMPINC PDS.

You should use the LSEARCH option to include the two


PDSs, USR.INCLUDE.C and USR.INCLUDE.H, which contain the stack.c and stack.h files,
respectively. The syntax for this is:

LSEARCH('USR.INCLUDE.+')
For information about include files, and the TEMPINC and LSEARCH options, see the OS/390
C/C++ User's Guide.

FUNCTION TEMPLATE
Is a template used to generate template functions. A function template can be only a
declaration, or it can define the function.
Template function
Is a function generated by a function template.

Example of a Function Template

If you want to create a function approximate(), which determines whether two values are
within 5% of each other, you can define the following template:

#include <math.h>
template <class T> int approximate (T first, T second)
{
double aptemp=double(first)/double(second);
return int(abs(aptemp-1.0) <= .05);
};

Assuming that you have two values of type float you want to compare. You can use
the approximate function template:

float a=3.24, b=3.35;


if (approximate(a,b))

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

cout << "a and b are pretty close" << endl;

The above example generates the following template function to resolve the call:

int approximate(float,float)

Overloading Resolution for Template Functions

OS/390 C++ resolves overloaded template functions in the following order:

1. Looks for a function with an exact type match. It does not include template functions,
unless you explicitly declare such functions by using a function declaration. OS/390 C++
performs trivial conversions if they produce an exact type match.
2. Looks for a function template that allows generation of a function with an exact type
match. OS/390 C++ performs trivial conversions if they produce an exact type match.
3. Tries ordinary overloading resolution for functions already present. This does not include
template functions, unless you have explicitly declared such functions by using a function
declaration.

A call to a template function causes an error, and OS/390 C++ does no overloading if the
following conditions are true:

 The only available functions for a call are template functions.


 These functions would require nontrivial conversions for the call to succeed.
 You have not explicitly declared these functions.

In the case of the approximate() function template, if the two input values are of different
types, overloading resolution does not take place:

float a=3.24;
double b=3.35;
if (approximate(a,b)) // error, different types
{ /* ... */ }

The solution is to force a conversion to one of the available function types by explicitly declaring
the function for the chosen type. To resolve the above example, include the following function
declaration:

int approximate(double a, double b);


// force conversion of the float to double

This declaration creates a function, approximate() that expects two arguments of type double.
When you callapproximate(a,b), the overloading is resolved by converting variable a to
type double.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Defining Template Functions

You can generate template functions in all compilation units that contain function template
definitions. Consequently, you may want to group function template definitions into one or two
compilation units.

Explicitly Defined Template Functions

In some situations, a function template can define a group of functions in which, for one function
type, the function definition would be inappropriate. For instance, consider the following
function template:

template<class T> int approximate(T first, T second);

The following explicitly defined template function compares two strings and returns a value that
indicates whether more than 5% of the characters differ between the two strings:

#include <string.h>
int approximate(char *first, char *second)
{
if (strcmp(first,second) == 0)
return 1; // strings are identical

double difct=0;
int maxlen=0;

if (strlen(first)>strlen(second))
maxlen=strlen(first);

else maxlen=strlen(second);
for (int i=0; i<=maxlen ; ++i)
if ( first[i] != second[i] ) difct++;
return int((difct / maxlen) <= .05 );
}

Given this definition, the following function call invokes the above explicitly defined function,
and no template function is generated:

approximate("String A","String B");

Assume that you explicitly define a template function as follows:

int approximate(double a, double b) { /* ... */ }

Then, consider the following call:

double a=3.54;

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

float b=3.5;
approximate(a,b);

The above call resolves to the following call:

approximate(double a, double b)

OS/390 C++ converts variable b to type double.

Function Template Declarations and Definitions

When you define a template function explicitly within a compilation unit, the compiler uses this
definition in preference to any instantiation from the function template. For example, if one
compilation unit contains the code:

#include <iostream.h>
template <class T> T f(T i) {return i+1;}
void main()
{
cout << f(2) << endl;
}

And another compilation unit contains the following:

int f(int i) {return i+2;}

When compiled and run, the program prints the number 4 to standard output. This indicates that
the compiler uses the explicitly defined function to resolve the call to f().

Declare a template function if any of the following situations apply:

 A function whose name matches a function template's name you have declared, and the
compiler can generate an appropriate template function.
 A function whose name matches a function template's name you have called, and the
compiler can generate an appropriate template function.
 A function whose name matches a function template's name you have called, and you
have explicitly defined the template function.
 You take the address of a template function in such a way that instantiation can occur.
This means that the pointer to function must supply a return type and supply argument
types that can be used to instantiate the template function.

Class Templates

The relationship between a class template and an individual class is like the relationship between
a class and an individual object. An individual class defines how a group of objects can be
constructed, while a class template defines how a group of classes can be generated.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Note the distinction between the terms class template and template class:

Class template
Is a template used to generate template classes. A class template can be only a
declaration, or it can be a definition of the class.

Template class
Is an instance of a class template.

A template definition is identical to any valid class definition that the template might generate,
except for the following:

 The following syntax precedes the class template definition:


 template < template-argument-list >

In the above syntax, template-argument-list can include zero or more type-arguments,


and zero or more argument-declarations. The template-argument-list must contain at
least one argument.

 Types, variables, constants and objects within the class template can be declared with
arguments of user-defined type as well as with explicit types (for example, int or char).
 The template-argument-list can include argument-declarations (for
example, int a or char* b), which are generally used to define constant values within the
created class.

A class template can declare a class without defining it by using an elaborated type specifier, for
example:

template <class L,class T> class key;

Using the type specifier reserves the name as a class template name. All template declarations for
a class template must have the same types and number of template arguments. OS/390 C++
allows only one template declaration that contains the class definition.

You can instantiate the class template by declaring a template class. If the template class member
function definitions are not inline, you have to define them. When you instantiate a template
class, its argument list must match the argument list in the class template declaration.

template <class L,class T> class key


{
// .
// .
// .
};

template <class L> class vector


{

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

// .
// .
// .
};

void main ()
{
class key <int, vector<int> >; // instantiate template
}

Any of the techniques that are used to access ordinary class member objects and
functions can access objects and functions of individual template classes. For example, assume
you have this class template:

template<class T> class vehicle


{
public:
vehicle() { /* ... */ } // constructor
~vehicle() {}; // destructor
T kind[16];
T* drive();
static void roadmap();
// ...
};

Class Template Declarations and Definitions

You must declare a class template before declaring a corresponding template class. A class
template definition can only appear once in any single compilation unit. You must define a class
template before using a template class that requires the size of the class, or refers to members of
the class.

The following example declares the class template key before defining it. The declaration of the
pointer keyiptris valid because the example does not need the size of the class. The declaration
of keyi, however, causes an error.

template <class L> class key; // class template declared,


// not defined yet
//
class key<int> *keyiptr; // declaration of pointer
//
class key<int> keyi; // error, cannot declare keyi
// without knowing size
//
template <class L> class key // now class template defined
{

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

// .
// .
// .
};

If you use a template class before defining the corresponding class template, the compiler issues
an error. The compiler considers a class name, with the appearance of a template class name, to
be a template class. In other words, angle brackets are valid in a class name only if that class is a
template class.

The compiler does not compile the definition of a class template until it requires the definition of
a template class. At that point, it compiles the class template definition by using the argument list
of the template class to instantiate the template arguments. The compiler flags any errors in the
class definition at this time. If the compiler never requires the definition of a class template, it
does not compile it. In this case, the compiler will not flag any errors in the definition.

Reference and Uniqueness

You can only define a class template once within a compilation unit. You cannot declare the
class template name to refer to any other template, class, object, function, value, or type in the
same scope.

Nontype Template Arguments

A nontype template argument that is provided within a template argument list is an expression
whose value can be determined at compile time. Such arguments must be constant expressions,
addresses of functions, objects with external linkage, or addresses of static class members. You
normally use nontype template arguments to initialize a class or to specify the sizes of class
members.

The resulting values of nontype template arguments within a template argument list form part of
the template class's type. If two template class names have the same template name and if their
arguments have identical values, they are the same class.

In the following example, a class template is defined that requires a nontype


template int argument as well as the type argument:

template<class T, int size> class myfilebuf


{
T* filepos;
static int array[size];
public:
myfilebuf() { /* ... */ }
~myfilebuf();
advance(); // function defined elsewhere in program
};

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

In this example, the template argument size becomes a part of the template class name. It
creates an object of such a template class with both the type arguments of the class and the
values of any additional template arguments.

From this template, you can create an object x and its corresponding template class with
arguments double andsize=200. Use a value as the second template argument:

myfilebuf<double,200> x;

You can also create x by using an arithmetic expression:

myfilebuf<double,10*20> x;

If the template arguments do not evaluate identically, the objects that are created are of
different types:

myfilebuf<double,200> x; // create object x of class


// myfilebuf<double,200>
myfilebuf<double,200.0> y; // error, 200.0 is a double,
// not an int

The instantiation of y fails because the value 200.0 is of type double, and the template argument
is of type int.

Consider the following two objects:

myfilebuf<double, 128> x
myfilebuf<double, 512> y

These two objects belong to separate template classes, and referencing either of these objects
later withmyfilebuf<double> is an error.

A class template does not need to have a type argument if it has nontype arguments. For
example, the following template is a valid class template:

template<int i> class C


{
public:
int k;
C() { k = i; }
};

Declarations such as the following can instantiate this class template:

class C<100>;
class C<200>;

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Again, these two declarations refer to distinct classes because the values of their nontype
arguments differ.

Explicitly Defined Template Classes

You can override the class template definition of a particular template class by providing a class
definition for the type of class required. For example, the following class template creates a class
for each type that it references, but that class may be inappropriate for a particular type:

template<class M> class portfolio


{
double capital;
M arr;
// ...
};

Using the applicable template class name can define the type for which the template class is
inappropriate. Assuming the inappropriately defined type is stocks, you can redefine the
class portfolio<stocks> as follows:

class portfolio<stocks>
{
double capital;
stocks yield;
// ...
};

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Application for designing

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
 STL

2. SKILLS ADDRESSED:
 Listening
 Understanding

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students understand about Standard Template Library.
 To enable students understand the principles in standard template library.

4. OUTCOMES:
 Explain Standard Template Library.
 Explain the principles in STL.

5. LINK SHEET:
 What is a standard template library ?
 List the principles of standard template library.
 What is generic programming.
 Explain about generic software components .
 Explain generic algorithms
 What is an iterator ?

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

 What are the advantages of using STL containers ?


 What is a container?

6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)

STANDARD TEMPLATE LIBRARY :

Standard Template library(STL) is a collection of generic software components and


generic algorithms, glued by objects called iterators

Principles behind design of STL :

 Generic programming
o It is a mechanism of designing generic software components like vector, list,
dequeue,..The genetic algorithms work with many variants of different software
components without any change.
 Genetic software components (containers)
o They are basically collection of other objects
o Advantages:
 Small in number
 Generality
 Efficient, tested, debugged, and standardized
 Portability and reusability
 Genetic algorithms
o Advantages:
o Programmers are freed from writing routines
o The algorithm use the best mechanisms to be as efficient as possible
o Genetic algorithms are standardized

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

o Similar semantics are designed for all these algorithms


 Iterators

Software components are collection of other objects. Iterators provide efficient methods
to traverse these ocntainers.

Other advantages of using STL containers

 Automatically adjust growth


 Similar behavior to built-in types
 Extensibility
 Working of STL
 Containers
 Sequence containers
 Adapted containers
 Eg:

 #include <iostream>
 #include <vector>
 using namespace std;

 int main()
 {
 // create a vector to store int
 vector<int> vec;
 int i;

 // display the original size of vec
 cout << "vector size = " << vec.size() << endl;

 // push 5 values into the vector
 for(i = 0; i < 5; i++){
 vec.push_back(i);
 }

 // display extended size of vec
 cout << "extended vector size = " << vec.size() << endl;

 // access 5 values from the vector
 for(i = 0; i < 5; i++){
 cout << "value of vec [" << i << "] = " << vec[i] << endl;
 }

 // use iterator to access the values
 vector<int>::iterator v = vec.begin();
 while( v != vec.end()) {
 cout << "value of v = " << *v << endl;
 v++;
 }

www.BrainKart.com
Click Here for Object Oriented Programming full study material.


 return 0;
 }

 When the above code is compiled and executed, it produces the following result:

 vector size = 0
 extended vector size = 5
 value of vec [0] = 0
 value of vec [1] = 1
 value of vec [2] = 2
 value of vec [3] = 3
 value of vec [4] = 4
 value of v = 0
 value of v = 1
 value of v = 2
 value of v = 3
 value of v = 4

 Function objects and predicate objects:


 The default behavior of the program can be changed by providing a third
argument. The third argument is a function object. Predicate objects are function objects
with return value bool.
 Allocators :
 Allocators are memory management mechanisms. A default allocator is used with
the containers.

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Iterators
 Concepts and modelling

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
Inheritance

2. SKILLS ADDRESSED:
 Listening
 Understanding
 Analysis

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students understand about Inheritance.
 To enable students to define derived classes using a single base class.

4. OUTCOMES:
 Explain about inheritance.
 Define derived classes using a single base class.

5. LINK SHEET:
 What is Inheritance ?
 List the advantages of using inheritance.
 Explain Isa and part of relationship.
 Define derived class using a single base class and explain using public,private and
protected access modifier.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)


INHERITANCE
Inheritance is a form of software reusability in which new classes are created from
existing classes by absorbing their attributes and behaviors and overriding these with capabilities
the new classes require.
When creating a new class, instead of writing completely new data members and member
functions, the programmer can designate that the new class is to inherit the data members and
member functions of a previously defined base class. The new class is referred to as derived
class.
Single inheritance – A class is derived from one base class
Multiple inheritance – Derived class inherits from multiple base classes.

BASE CLASSES AND DERIVED CLASSES :


The class from which other class is derived is called as base class or superclass.
The new class is known as derived class or sub class.
Eg:
Base class Derived classes
Student Undergraduate student
Post graduate student
Shape Circle
Triangle
Square

Inheritance forms a tree like hierarchical structure. A base class exists in a hierarchical
relationship with its derived classes.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Eg: A portion of class shape hierarchy


Shape

Two dimensional shape three dimensional shape

Circle square triangle sphere cube tetrahedron

A base class’s public members are accessible by all functions in the program. A base class’s
private members are accessible only by member functions and friends of the base class.

PROTECTED MEMBERS :
Protected access is an intermediate level of protection between public and private
access. A base class’s protected members may be accessed only by members and friends of the
base class and by members and friends of the derived classes. Derived class members can refer
to public and protected members of the base class simply by using the member names. Protected
breaks encapsulation-a change to protected members of a base class may require modification of
all derived classes.

MULTIPLE INHERITANCE:

#include<iostream.h>
#include<conio.h>

class student
{
protected:
int rno,m1,m2;
public:
void get()
{
cout<<"Enter the Roll no :";
cin>>rno;
cout<<"Enter the two marks :";
cin>>m1>>m2;
}
};
class sports
{
protected:
int sm; // sm = Sports mark
public:
void getsm()

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

{
cout<<"\nEnter the sports mark :";
cin>>sm;

}
};
class statement:public student,public sports
{
int tot,avg;
public:
void display()
{
tot=(m1+m2+sm);
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal : "<<tot;
cout<<"\n\tAverage : "<<avg;
}
};
void main()
{
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();
}

Output:

Enter the Roll no: 100

Enter two marks

90
80

Enter the Sports Mark: 90

Roll No: 100


Total : 260
Average: 86.66

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

MULTILEVEL INHERITANCE:
A class be can derived from a derived class which is known as multilevel
inhertiance.
EG:
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"Base class content.";
}
};
class B : public A
{
};
class C : public B
{
};
int main()
{
C c;
c.display();
return 0;
}

Output

Base class content.

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
Real time systems.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
 Exceptions

2. SKILLS ADDRESSED:
 Listening
 Understanding

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students understand about Exception Handling.
 To enable students to understand about Traditional handling,need for exceptional
handling,components,challenges, use of throw.

4. OUTCOMES:
 Explain Exception Handling.

5. LINK SHEET:
 What is Exception handling ?
 Explain traditional error handling.
 What is the need for exceptional handling ?
 What are the challenges in exception handling ?
 Explain the use of throw within and outside a function.
 Explain the usage of multiple catch.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

6.EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)

EXCEPTION HANDLING :
Exception handling is a mechanism to handle exceptions. Exceptions are error like
situations. When exception handling is in place, instead of providing normal means of execution
when an exception occurs, we need to provide an alternative path of execution. In case if
exception is not applicable, the program will be terminated.
Traditional error handling :
Three ways :
1. Returning error number
2. Global flag manipulation
3. Abnormal termination

1. Returning error number :

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

If something in a function argument is wrong or something goes wrong while processing,


the function returns an error code. There is no universal standard for such error codes. Returning
1 may indicate wrong argument type in one case, in other case it may signify that a pointer
argument passed contain invalid address.

2. Global flag manipulation :


There is an error variable, which is globally available. They can set the value of errno to
indicate error. The disadvantage of this method is the reliance of the user to comply and test the
value of global flag every time the function is called.

3. Abnormal termination of the program :


This is the most common exception handling procedure. Whenever something goes out of
bound, we casl exit() or abort(). It is little better to use assert() which displays a message before
terminating. Use of this procedure means that an error would eventually crash the program.

Need for exception handling ;


 Dividing the error handling
 Unconditional termination and programmer defined termination
 Seperating error reporting and error handling
 The object destroy problem.

Components of exception handling mechanism


The exception handling mechanism has three building blocks :

Try –for indicating program area where exception can be thrown,


Throw- for throwing an exception
Catch – for actually taking an action for the specific exception.

Try :
The try block is the one which can throw an exception. The code that we want to monitor
for exceptions is placed within the try block.

Catch :
This is the section where the exception is handled.
Eg:
try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Throw :
Eg:
#include <iostream>
#include <exception>
using namespace std;

class myexception: public exception


{
virtual const char* what() const throw()
{
return "My exception happened";
}
} myex;

int main () {
try
{
throw myex;
}
catch (exception& e)
{
cout << e.what() << '\n';
}
return 0;
}

Challenges in the new approach :


 Finding proper handler
 Finding proper handler for a polymorphic object
 Backtracking till the beginning of try block

Use of throw within and outside the function:

#include <iostream.h>

int testeh(void);
class A {
int i;
public:
A(int j) { i = j; cout << "A ctor: i=" << i << '\n';}
~A() { cout << "A dtor: i=" << i << '\n';}
};
class B {
char c;

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

public:
B(char d) { c = d; cout << "B ctor: c=" << c << '\n'; }
~B() { cout << "B dtor: c=" << c << '\n'; }
};
A globA(1);
B globB('a');
main()
{
int rc = 55;
A a(1001);

try {
cout << "calling testeh\n";
testeh();
}
catch(char c) { cout << "caught char\n"; }
catch(short s) { cout << "caught short s = " << s << '\n'; }
catch(int i) { cout << "caught int i = " << i << '\n'; }
cout << "rc = " << rc << '\n';
return(rc);
}
testeh() throw(int,short)
{
A a(2001);
B b('k');
short k=12;

try {
cout << "testeh running\n";
throw (6);
}
catch(char c) { cout << "testeh caught char\n";}
catch(int j) { cout << "testeh caught int j = " << j << '\n';
try {
cout << "testeh throwing a short\n";
throw(k);
}
catch(char d) { cout << "char d caught\n"; }
}
cout << "this line should not be printed\n";
return(0);
}

The expected output from this program is:

A ctor: i=1

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

B ctor: c=a
A ctor: i=1001
calling testeh
A ctor: i=2001
B ctor: c=k
testeh running
testeh caught int j = 6
testeh again throwing a short
B dtor: c=k
A dtor: i=2001
caught short s = 12
rc = 55
A dtor: i=1001
B dtor: c=a
A dtor: i=1

Rethrowing an Exception

If a catch block cannot handle the particular exception it has caught, you can rethrow the
exception. The rethrow expression, throw with no argument, causes the originally thrown object
to be rethrown.

The handler has already caught the exception at the scope in which the rethrow expression
occurs. Consequently, the exception is rethrown to the next dynamically enclosing try block.
Therefore, catch blocks at the scope in which the rethrow expression occurred cannot handle it.
Any catch blocks following the dynamically enclosing try block have an opportunity to catch the
exception.

In the following example, catch(FileIO) catches any object of type FileIO, and any objects
that are public base classes of the FileIO class. The example then checks for those exceptions it
can handle. For any exception it cannot handle, it issues a rethrow expression to rethrow the
exception. This allows another handler in a dynamically enclosing try block to handle the
exception.

// This example illustrates rethrowing an exception.

#include <iostream.h>
class FileIO
{
public:
int notfound;
int endfile;
FileIO(); // initialize data members
// the following member functions throw an exception
// if an input error occurs
void advance(int x);
void clear();

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

void put(int x, int y);


};
// .
// .
// .
void f()
{
FileIO fio;
try
{
// call member functions of FileIO class
fio.advance (1);
fio.clear();
fio.put(1,-1);
}
catch(FileIO fexc)
{
if (fexc.notfound)
cout << "File not Found" << endl;
else if (fexc.endfile)
cout << "End of File" << endl;
else
throw; // rethrow to outer handler
}
catch(...) { /* ... */ } // catch other exceptions
}
main()
{
try
{
f();
}
catch(FileIO) { cout << "Outer Handler" << endl; }
}

The rethrow expression can be caught by any catch whose argument matches the argument of
the exception originally thrown. Note that in this example, the catch(...) will not catch the
rethrow expression. When the example issues a rethrow expression, it passes control out of the
scope of the function f() into the next dynamically enclosing block.

Catching Exceptions

You can declare a handler to catch many types of exceptions. You declare the allowable
objects that a function can catch in the parentheses that follow the catch keyword (the catch
argument). You can catch objects of the fundamental types, base and derived class objects,
references, and pointers to all of these types. You can also catch const and volatile types.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

You can also use the catch(...) form of the handler to catch all thrown exceptions that
have not been caught by a previous catch block. The ellipsis in the catch argument indicates that
this handler can handle any exception that is thrown.

If an exception is caught by a catch(...) block, there is no direct way to access the object
thrown. Information about an exception caught by catch(...)is very limited.

You can declare an optional variable name if you want to access the thrown object in the
catch block.

A catch block can only catch accessible objects. The object that is caught must have an
accessible copy constructor.

try
{
// protected code
}catch( ExceptionName e )
{
// code to handle ExceptionName exception
}

Exception Specifications

C++ provides a mechanism that limits a given function to throwing only a specified list
of exceptions. An exception specification at the beginning of any function acts as a guarantee to
the function's caller that the function will not directly or indirectly throw any exception not
contained in the exception specification. For example, consider the following function:

void translate() throw(unknown_word,bad_grammar) { /* ... */ }

The above function explicitly states that it will not throw any exception other
than unknown_word orbad_grammar. The function translate() must handle any exceptions
thrown by functions it might call, unless those exceptions are specified in the exception
specification of translate(). Consider if an exception is thrown by a function called
by translate() and the exception is not handled by translate() or contained in the exception
specification of translate(). Then, OS/390 C/C++ calls unexpected(). The
functionunexpected() is discussed in Special Exception Handling Functions.

There are qualifications to the rule about throwing only a specified list of exceptions. If a
class A is included in the exception specification of a function, the function will also allow
exception objects of any classes that are publicly derived from class A. Also, if a pointer type B*
is included in the exception specification of a function, the function will allow exceptions of type
B* or of pointers to any type publicly derived from B*.

Empty Exception Specifications

A function with an empty throw() specification guarantees that the function will not
throw any exceptions.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Functions without an Exception Specification

A function without an exception specification allows any object to be thrown from the function.

Other Exception Specifications

The compiler does not prevent an exception specification from defining more valid
exceptions than the set of exceptions the function may actually throw. Such an error is detected
only at run time, and only if the unspecified exception is thrown.

In the following example, NameTooShort is thrown from within a function that explicitly
states that it will only throw NameTooLong. This is a valid function, although at run time,
if NameTooShort is thrown, a call tounexpected() will be made.

#include <string.h> // needed for strlen


class NameTooLong {};
class NameTooShort {};

void check(char* fname) throw (NameTooLong)


{
if ( strlen(fname)<4 ) throw NameTooShort();
}

If a function with an exception specification calls a subfunction with a less restrictive exception
specification (one that contains more objects than the calling function's exception specification),
any thrown objects from within the subfunction that are not handled by the subfunction, and that
are not part of the outer function's specification list, must be handled within the outer function. If
the outer function fails to handle an exception not in its exception specification, a call
to unexpected() is made.

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Error handling

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
Why Object-Oriented Programming in C++

2. SKILLS ADDRESSED:
Learning

3. OBJECTIVE OF THIS LESSON PLAN:


vii. To facilitate students understand the basics of C++.
viii. To enable students understand the various Object Oriented Concepts .

4. OUTCOMES:
vii. Explain the various Object Oriented concepts.
viii. Explain the difference between object oriented and procedure oriented concepts.

5. LINK SHEET:
xv. What is Object oriented programming?
xvi. List the Object Oriented concepts

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

6.EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)

Object Oriented Programming is a method of visualizing and programming the


problem in a global way. Object oriented programming is a technique to envision the problem as
a collection of objects that represents real world entities
Features :
 Emphasis is on data rather than procedure
 Programs are divided into objects
 Functions that operate on the data of the object are tied together in data structure
 Data is hidden and cannot be accessed by external functions
 Objects may communicate with each other usibg functions

INTRODUCTION TO C++:
Difference between Procedure oriented programming and Object oriented programming.

POP OOP
1) Emphasis on non-real item Emphasis on real item
2) Programs are divided into Programs are divided into Objects
functions Data are not sharable
3) Data are sharable Object Oriented Programming
4) Structured Programming Bottom-Up Approach
5) Top-Down Approach

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Tokens
Smallest individual unit in a program. C++ tokens are Keywords, Identifiers, Constants,
Strings, Operators.

Data Types in C++


 Built-in Data types
 User Defined Data types
 Derived Data Types

Block Structure of C++


Include Files
Class Declaration
Member Function Defintions
Main Function Program

Operators in C++
 :: Scope Resolution Operator
 : :* Member pointer operator
 ->* Pointer-to-Pointer Member using pointer to object Operator
 .* Pointer-to-Pointer Member using object Operator
 delete Memory Release Operator
 endl Line feed operator
 new Memory allocation operator
 Setw Memory width operator
 Casting operator for C-style casting from any type to any other irrelevant type
reinterpret_cast
 const_cast Removing the const nature of a variable while casting.
 dynamic_cast casting operator that can be used to safeguard against irrelevant
casting ,used in case of polymorphic classes.
 typeid used to find type of an object at run time
 throw useful for throwing an exception at the time of an error.

Expressions in C++
Constant Expressions
Integral Expressions
Float Expressions
Pointer Expressions
Relational Expressions
Logical Expressions
Bitwise Expressions

OBJECT ORIENTED PROGRAMMING CONCEPTS :


 Objects
 Classes

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

 Data Abstraction and Encapsulation


 Inheritance
 Polymorphism
 Dynamic binding
 Message passing

OBJECTS :
Objects are the basic run-time entities in an object – oriented system. They represent a
person,place,a bank account or a table of data or item that a program has to handle.When
a program is executed,the objects interact by passing messages to each other.
Eg: Customer and account are two objects. The customer object may send a
message to the account object requesting for bank balance.
CLASSES :
A Class is collection of objects of similar type. Objects are variables of the type class.
Classes are user defined data-types and behave like a built in type of a programming
language.
Eg: Apple, Mango, Orange are members of the class fruits.
Syntax : fruit mango ; Fruits

Apple Mango Orange

METHODS AND MESSAGES :


Objects communicate with each other by passing messages to each other. The
code for providing response to the message is known as method.
Eg :
Teacher SomeTeacher;
SomeTeacher = RollCall6030903.getTeacher();
The first statement defines an object SomeTeacher of class Teacher. Here,Teacher
is known as userdefined type and SomeTeacher is a variable of that type. The call to the
function is defined inside the class RollCall.The statement RollCall6030903.getTeacher()
calls the function getTeacher() which works on the object RollCall6030903 and get the
Teacher associated with that roll call. In the statement SomeTeacher =
RollCall6030903.getTeacher(), wec assign the Teacher object returned by that function to
SomeTeacher.
Here, getTeacher() is known as a message being passed to an object
RollCall6030903.The object executes the body of the function getTeacher() and returns
with the response,the Teacher object. The code for providing response to the message,
i.e,. body of the function getTeacher() is known as method.

ABSTRACTION AND ENCAPSULATION :


Abstraction refers to the act of representing the essential features without
including the background details or explanation. Classes use the concept of abstraction and are

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

defined as a list of abstract attributes such as size,weight,cost and functions to operate on these
attributes. The attributes are called members and functions as methods or member functions. The
classes use Data abstraction and are called Abstract Data Types(ADT).
Eg: Abstraction example: ATM is a good example of abstraction, we doesn't know what
are all the internal processes that are going when we access it..instead we know only the
inquiries, deposit, withdrawal etc.
The wrapping up of data and functions into a single unit(class) is called Encapsulation.
The data is not accessible to the outside world ,and those functions that are wrapped in the class
can access it. This insulation of program by direct access of program is called data hiding or
Information hiding.
Eg: Ink is the important component in pen but it is hiding by some other material.
you don't "need to know the internal working of the mobile phone to operate" with it.
You have an interface to use the device behaviour without knowing implementation details.

INHERITANCE :
Inheritance is the processs by which the object of one class acquire the properties
of objects of another class.
Eg: class Bird-> class flying bird ->class robin

ABSTRACT CLASSES:
Abstract class is the class with no objects. The abstract classes does not represent any
real-world entity. The purpose of an abstract class (often referred to as an ABC) is to provide an
appropriate base class from which other classes can inherit. Abstract classes cannot be used to
instantiate objects and serves only as an interface.
Consider the following example where parent class provides an interface to the base class to
implement a function called getArea():
#include <iostream>

using namespace std;

// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

};

// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};

int main(void)
{
Rectangle Rect;
Triangle Tri;

Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;

Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result:

Total Rectangle area: 35


Total Triangle area: 17

ABSTRACT CLASSES:
Abstract class is the class with no objects. The abstract classes does not represent any
real-world entity. The purpose of an abstract class (often referred to as an ABC) is to provide an

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

appropriate base class from which other classes can inherit. Abstract classes cannot be used to
instantiate objects and serves only as an interface.
Consider the following example where parent class provides an interface to the base class to
implement a function called getArea():
#include <iostream>

using namespace std;

// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};

// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};

int main(void)
{

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Rectangle Rect;
Triangle Tri;

Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;

Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;

return 0;
}

When the above code is compiled and executed, it produces the following result:

Total Rectangle area: 35


Total Triangle area: 17

POLYMORPHISM:
Polymorphism is a concept in which the operation may exhibit different behaviour in
different instances.
Eg: addition will sum two numbers in case of numerical operands. In case of
string , it will form a third string by concatenation.

An example C++ program :


Adding two number using class (C++)
#include<iostream.h>
#include<conio.h>
class add
{
private:
int a,b,c;
public:
void read()
{
cout<<"enter Two Number "<<endl;
cin>>a>>b;
}
void display()
{
cout<<" A = "<<a<<endl;
cout<<" B = "<<b<<endl;

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

cout<<"Sum = "<<c<<endl;
}
void sum()
{
c= a+b;
}
};
void main()
{
add x; // x is a object off add
clrscr();
x.read();
x.sum();
x. display();
getch();
}

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Real time applications
 Neural networks and parallel processing
 Object oriented systems

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
Data types, variables and arrays

2. SKILLS ADDRESSED:
Listening
Understanding
Analysis and implementation

3. OBJECTIVE OF THIS LESSON PLAN:


i. To facilitate students to understand about Data types.
ii. To enable students to understand about variables.
iii. To enable students to understand about array

4. OUTCOMES:
i. Explain about data types and variables in java.
ii. Explain about array in java.

5. LINK SHEET:
i. Illustrate data types and variables.
ii. What is an array?
iii. Illustrate the use of array with a sample java program

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)

DATA TYPE

Data type specifies the size and type of values that can be stored in an identifier. The Java
language is rich in its data types. Different data types allow you to select the type appropriate to
the needs of the application.

Data types in Java are classified into two types:


1. Primitive—which include Integer, Character, Boolean, and Floating Point.
2. Non-primitive—which include Classes, Interfaces, and Arrays.

Primitive Data Types

1. Integer
Integer types can hold whole numbers such as 123 and −96. The size of the values that can be
stored depends on the integer type that we choose.
Type Size Range of values that can be stored

byte 1 byte −128 to 127

short 2 bytes −32768 to 32767

int 4 bytes −2,147,483,648 to 2,147,483,647

9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,755,807
The range of values is calculated as −(2n−1) to (2n−1)−1; where n is the number of bits required.
For example, the byte data type requires 1 byte = 8 bits. Therefore, the range of values that can
be stored in the byte data type is −(28−1) to (28−1)−1
= −27 to (27) -1
= −128 to 127

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

2. Floating Point
Floating point data types are used to represent numbers with a fractional part. Single precision
floating point numbers occupy 4 bytes and Double precision floating point numbers occupy 8
bytes. There are two subtypes:
Type Size Range of values that can be stored

float 4 bytes 3.4e−038 to 3.4e+038

double 8 bytes 1.7e−308 to 1.7e+038

3. Character
It stores character constants in the memory. It assumes a size of 2 bytes, but basically it can hold
only a single character because char stores unicode character sets. It has a minimum value of
‗u0000′ (or 0) and a maximum value of ‗uffff‘ (or 65,535, inclusive).

4. Boolean
Boolean data types are used to store values with two states: true or
false. Java Tokens
A token is the smallest element in a program that is meaningful to the compiler. These tokens
define the structure of the language. The Java token set can be divided into five categories:
Identifiers, Keywords, Literals, Operators, and Separators.

1. Identifiers
Identifiers are names provided by you. These can be assigned to variables, methods, functions,
classes etc. to uniquely identify them to the compiler.

2. Keywords
Keywords are reserved words that have a specific meaning for the compiler. They cannot be used
as identifiers. Java has a rich set of keywords. Some examples are: boolean, char, if, protected,
new, this, try, catch, null, threadsafe etc.

3. Literals
Literals are variables whose values remain constant throughout the program. They are also called
Constants. Literals can be of four types. They are:

a. String Literals
String Literals are always enclosed in double quotes and are implemented using the
java.lang.String class. Enclosing a character string within double quotes will automatically create
a new String object. For example, String s = "this is a string";. String objects are immutable,
which means that once created, their values cannot be changed.

b. Character Literals
These are enclosed in single quotes and contain only one character.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

c. Boolean Literals
They can only have the values true or false. These values do not correspond to 1 or 0 as in C or
C++.

d. Numeric Literals
Numeric Literals can contain integer or floating point values.

4. Operators
An operator is a symbol that operates on one or more operands to produce a result.
They will be discussed in greater detail in the next article.

5. Separators
Separators are symbols that indicate the division and arrangement of groups of code. The
structure and function of code is generally defined by the separators. The separators used in Java
are as follows:

parentheses ( )
Used to define precedence in expressions, to enclose parameters in method definitions,
and enclosing cast types.
braces { }
Used to define a block of code and to hold the values of arrays.
brackets [ ]
Used to declare array types.
semicolon ;
Used to separate statements.
comma ,
Used to separate identifiers in a variable declaration and in the forstatement.
period .
Used to separate package names from classes and subclasses and to separate a variable or
a method from a reference variable.

VARIABLES

There are different types of variables in Java. They are as follows:

1. Instance Variables(Non-Static Fields)


Objects store their individual states in ―non-static fields‖, that is, fields declared without
the static keyword.
Non-static fields are also known as instance variables because their values are unique to each
instance of a class. For example, the currentSpeed of one bicycle is independent from
the currentSpeed of another.

2. ClassVariables (Static Fields)


A class variable is any field declared with the static modifier; this tells the compiler that there is
exactly one copy of this variable in existence, regardless of how many times the class has been
instantiated. A field defining the number of gears for a particular kind of bicycle could be

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

marked as static since, conceptually, the same number of gears will apply to all instances. The
codestatic int numGears = 6; would create such a static field.

3. Local Variables
A method stores its temporary state in local variables. The syntax for declaring a local variable is
similar to declaring a field (for example, int count = 0;). There is no special keyword designating
a variable as local; that determination comes entirely from the location in which the variable is
declared—between the opening and closing braces of a method. As such, local variables are only
visible to the methods in which they are declared; they are not accessible from the rest of the
class.

4. Parameters
They are the variables that are passed to the methods of a class.
Variable Declaration
Identifiers are the names of variables. They must be composed of only letters, numbers, the
underscore, and the dollar sign ($). They cannot contain white spaces. Identifiers may only begin
with a letter, the underscore, or the dollar sign. A variable cannot begin with a number. All
variable names are case sensitive.
Syntax for variable declaration
datatype1 variable1, datatype2 variable2, … datatypen variablen;
For example:

int a, char ch;

Initialisation
Variables can be assigned values in the following way: Variablename = value;
For example;

ch='a';
a=0;

ARRAY

An array is a container object that holds a fixed number of values of a single type. The
length of an array is established when the array is created. After creation, its length is fixed. You
have seen an example of arrays already, in the main method of the "Hello World!" application.
This section discusses arrays in greater detail.

Each item in an array is called an element, and each element is accessed by its
numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th
element, for example, would therefore be accessed at index 8.

The following program, ArrayDemo, creates an array of integers, puts some values in the
array, and prints each value to standard output.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;

// allocates memory for 10 integers


anArray = new int[10];

// initialize first element


anArray[0] = 100;
// initialize second element
anArray[1] = 200;
// and so forth
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;

System.out.println("Element at index 0: "


+ anArray[0]);
System.out.println("Element at index 1: "
+ anArray[1]);
System.out.println("Element at index 2: "
+ anArray[2]);
System.out.println("Element at index 3: "
+ anArray[3]);
System.out.println("Element at index 4: "
+ anArray[4]);
System.out.println("Element at index 5: "
+ anArray[5]);
System.out.println("Element at index 6: "
+ anArray[6]);
System.out.println("Element at index 7: "
+ anArray[7]);
System.out.println("Element at index 8: "
+ anArray[8]);
System.out.println("Element at index 9: "
+ anArray[9]);
}
}

The output from this program is:

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Element at index 0: 100


Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
Array Manipulations

Arrays are a powerful and useful concept used in programming. Java SE provides methods to
perform some of the most common manipulations related to arrays. For instance,
the ArrayCopyDemo example uses the arraycopy() method of the System class instead of
manually iterating through the elements of the source array and placing each one into the
destination array. This is performed behind the scenes, enabling the developer to use just one line
of code to call the method.

For your convenience, Java SE provides several methods for performing array manipulations
(common tasks, such as copying, sorting and searching arrays) in thejava.util.Arrays class. For
instance, the previous example can be modified to use the CopyOfRange() method of
the java.util.Arrays class, as you can see in theArrayCopyOfDemo example. The difference is
that using the CopyOfRange() method does not require you to create the destination array before
calling the method, because the destination array is returned by the method:

class ArrayCopyOfDemo {
public static void main(String[] args) {

char[] copyFrom = {'d', 'e', 'c', 'a', 'f', 'f', 'e',


'i', 'n', 'a', 't', 'e', 'd'};

char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);

System.out.println(new String(copyTo));
}
}

As you can see, the output from this program is the same (caffein), although it requires fewer
lines of code.

Some other useful operations provided by methods in the java.util.Arrays class, are:

 Searching an array for a specific value to get the index at which it is placed
(the binarySearch() method).
 Comparing two arrays to determine if they are equal or not (the equals() method).

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

 Filling an array to place a specific value at each index (the fill() method).
 Sorting an array into ascending order. This can be done either sequentially, using
the sort() method, or concurrently, using the parallelSort() method introduced in Java SE
8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array
sorting.

8. TEXT BOOKS :
1. E Balagurusamy,‖Object Oriented Programming with C++ and Java‖.
2. Ira Pohl, ―Object-Oriented Programming Using C++‖, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 RPC

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
 operators

2. SKILLS ADDRESSED:
 Listening
 Understanding

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students understand about Standard operator.

4. OUTCOMES:
 Explain different types of operator.

5. LINK SHEET:
 List the types of operator and explain it in detail.

6. EVOCATION: (10 Minutes)

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

7. LECTURE NOTES: (40 Minutes)

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:

 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators
The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:

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

Operator Description Example


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

The Relational Operators:

There are following relational operators supported by Java language

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

Operator Description Example

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Checks if the values of two operands are equal or


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

The Bitwise Operators:


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

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13;
now in binary format they will be as follows:

a = 0011 1100

b = 0000 1101

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

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators:

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

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Operator Description Example


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

The Logical Operators:


The following table lists the logical operators:

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

Operator Description Example


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

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

The Assignment Operators:


There are following assignment operators supported by Java language:

Operator Description Example


Simple assignment operator,
Assigns values from right
= C = A + B will assign value of A + B into C
side operands to left side
operand
Add AND assignment
operator, It adds right
+= operand to the left operand C += A is equivalent to C = C + A
and assign the result to left
operand
Subtract AND assignment
operator, It subtracts right
-= operand from the left C -= A is equivalent to C = C - A
operand and assign the
result to left operand
Multiply AND assignment
operator, It multiplies right
*= operand with the left C *= A is equivalent to C = C * A
operand and assign the
result to left operand
Divide AND assignment
operator, It divides left
/= operand with the right C /= A is equivalent to C = C / A
operand and assign the
result to left operand
Modulus AND assignment
operator, It takes modulus
%= using two operands and C %= A is equivalent to C = C % A
assign the result to left
operand
Left shift AND assignment
<<= C <<= 2 is same as C = C << 2
operator
Right shift AND assignment
>>= C >>= 2 is same as C = C >> 2
operator
Bitwise AND assignment
&= C &= 2 is same as C = C & 2
operator

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

bitwise exclusive OR and


^= C ^= 2 is same as C = C ^ 2
assignment operator
bitwise inclusive OR and
|= C |= 2 is same as C = C | 2
assignment operator

Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide
which value should be assigned to the variable. The operator is written as:

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

Following is the example:

public class Test {

public static void main(String args[]){


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

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


System.out.println( "Value of b is : " + b );
}
}

This would produce the following result:

Value of b is : 30
Value of b is : 20

instanceof Operator:
This operator is used only for object reference variables. The operator checks whether the object
is of a particular type(class type or interface type). instanceof operator is wriiten as:

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

If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true. Following is the example:

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

public class Test {

public static void main(String args[]){


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

This would produce the following result:

true

This operator will still return true if the object being compared is the assignment compatible with
the type on the right. Following is one more example:

class Vehicle {}

public class Car extends Vehicle {


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

This would produce the following result:

true

Precedence of Java Operators:


Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

Category Operator Associativity


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

8. TEXT BOOKS :
1. E Balagurusamy,‖Object Oriented Programming with C++ and Java‖.
2. Ira Pohl, ―Object-Oriented Programming Using C++‖, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Real time applications
 Neural networks and parallel processing
 Object oriented systems

www.BrainKart.com
Click Here for Object Oriented Programming full study material.

1. CONTENT LIST:
Control statements

2. SKILLS ADDRESSED:
 Listening
 Analysis

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students understand about control statements

4. OUTCOMES:
 Explain about control statements.

5. LINK SHEET:
 Illustrate control statement

6. EVOCATION: (10 Minutes)

www.BrainKart.com
7. LECTURE NOTES: (40 Minutes)
There may be a situation when we need to execute a block of code several number of times,
and is often referred to as a loop.

Java has very flexible three looping mechanisms. You can use one of the following three loops:

 while Loop
 do...while Loop
 for Loop
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:
The syntax of a while loop is:

while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.
Example:
public class Test {

public static void main(String args[]) {


int x = 10;

while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

This would produce the following result:

value of x : 10
value of x : 11
value of x : 12

www.BrainKart.com
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.

Syntax:
The syntax of a do...while loop is:

do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in
the loop execute again. This process repeats until the Boolean expression is false.

Example:
public class Test {

public static void main(String args[]){


int x = 10;

do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}

This would produce the following result:

value of x : 10
value of x : 11
value of x : 12

www.BrainKart.com
The for Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.

A for loop is useful when you know how many times a task is to be repeated.

Syntax:
The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}

Here is the flow of control in a for loop:

 The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here, as long as
a semicolon appears.

 Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and flow of control jumps to the next statement
past the for loop.

 After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement can be
left blank, as long as a semicolon appears after the Boolean expression.

 The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.

Example:
public class Test {

public static void main(String args[]) {

www.BrainKart.com
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Enhanced for loop in Java:


As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

Syntax:
The syntax of enhanced for loop is:

for(declaration : expression)
{
//Statements
}
 Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for block and
its value would be the same as the current array element.
 Expression: This evaluates to the array you need to loop through. The expression can be
an array variable or method call that returns an array.
Example:
public class Test {

public static void main(String args[]){


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ){
System.out.print( x );
System.out.print(",");

www.BrainKart.com
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}

This would produce the following result:

10,20,30,40,50,
James,Larry,Tom,Lacy,

The break Keyword:


The break keyword is used to stop the entire loop. The break keyword must be used inside any
loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line
of code after the block.

Syntax:
The syntax of a break is a single statement inside any loop:

break;
Example:
public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}

This would produce the following result:

www.BrainKart.com
10
20

The continue Keyword:


The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.

 In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement.

 In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.

Syntax:
The syntax of a continue is a single statement inside any loop:

continue;
Example:
public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}

This would produce the following result:

10
20
40
50

www.BrainKart.com
8. TEXT BOOKS :
1. E Balagurusamy,‖Object Oriented Programming with C++ and Java‖.
2. Ira Pohl, ―Object-Oriented Programming Using C++‖, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Real time systems.

www.BrainKart.com
1. CONTENT LIST:
 Classes, objects, methods

2. SKILLS ADDRESSED:
 Learning
 Remembering
 Implementing

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students understand about objects and classes in java.

4. OUTCOMES:
 Describe objects and classes in java.

5. LINK SHEET:
 What is an object?
 Illustrate methods, objects and classes in java

www.BrainKart.com
6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)

OBJECTS

A typical Java program creates many objects, which as you know, interact by invoking methods.
Through these object interactions, a program can carry out various tasks, such as implementing a
GUI, running an animation, or sending and receiving information over a network. Once an object
has completed the work for which it was created, its resources are recycled for use by other
objects.

Here's a small program, called CreateObjectDemo, that creates three objects: one Point object
and two Rectangle objects. You will need all three source files to compile this program.

public class CreateObjectDemo {

public static void main(String[] args) {

// Declare and create a point object and two rectangle objects.


Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

// display rectOne's width, height, and area


System.out.println("Width of rectOne: " + rectOne.width);
System.out.println("Height of rectOne: " + rectOne.height);
System.out.println("Area of rectOne: " + rectOne.getArea());

// set rectTwo's position


rectTwo.origin = originOne;

// display rectTwo's position


System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);

www.BrainKart.com
// move rectTwo and display its new position
rectTwo.move(40, 72);
System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);
}
}

This program creates, manipulates, and displays information about various objects. Here's
the output:

Width of rectOne: 100


Height of rectOne: 200
Area of rectOne: 20000
X Position of rectTwo: 23
Y Position of rectTwo: 94
X Position of rectTwo: 40
Y Position of rectTwo: 72

CLASSES AND METHODS

The introduction to object-oriented concepts in the lesson titled Object-oriented


Programming Concepts used a bicycle class as an example, with racing bikes, mountain bikes,
and tandem bikes as subclasses. Here is sample code for a possible implementation of
a Bicycle class, to give you an overview of a class declaration. Subsequent sections of this lesson
will back up and explain class declarations step by step. For the moment, don't concern yourself
with the details.

public class Bicycle {

// the Bicycle class has


// three fields
public int cadence;
public int gear;
public int speed;

// the Bicycle class has


// one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}

// the Bicycle class has


// four methods
public void setCadence(int newValue) {

www.BrainKart.com
cadence = newValue;
}

public void setGear(int newValue) {


gear = newValue;
}

public void applyBrake(int decrement) {


speed -= decrement;
}

public void speedUp(int increment) {


speed += increment;
}

A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:

public class MountainBike extends Bicycle {

// the MountainBike subclass has


// one field
public int seatHeight;

// the MountainBike subclass has


// one constructor
public MountainBike(int startHeight, int startCadence,
int startSpeed, int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}

// the MountainBike subclass has


// one method
public void setHeight(int newValue) {
seatHeight = newValue;
}

MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a
method to set it (mountain bikes have seats that can be moved up and down as the terrain
demands).

www.BrainKart.com
8.TEXT BOOKS :
1. E Balagurusamy,‖Object Oriented Programming with C++ and Java‖.
2. Ira Pohl, ―Object-Oriented Programming Using C++‖, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
RPC

www.BrainKart.com
1. CONTENT LIST:
 Inheritance

2. SKILLS ADDRESSED:
 Learning
 Implementing

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students understand about inheritance.

4. OUTCOMES:
 Describe inheritance.
 Explain the types of inheritance

5.LINK SHEET:
 What is Inheritance?
 Illustrate the types of inheritance

www.BrainKart.com
6.EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)


Inheritance can be defined as the process where one object acquires the properties of another.
With the use of inheritance the information is made manageable in a hierarchical order.

When we talk about inheritance, the most commonly used keyword would
be extends andimplements. These words would determine whether one object IS-A type of
another. By using these keywords we can make one object acquire the properties of another
object.
IS-A Relationship:

IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword
is used to achieve inheritance.
public class Animal{
}

public class Mammal extends Animal{


}

public class Reptile extends Animal{


}

public class Dog extends Mammal{


}

Now, based on the above example, In Object Oriented terms, the following are true:
 Animal is the superclass of Mammal class.
 Animal is the superclass of Reptile class.
 Mammal and Reptile are subclasses of Animal class.
 Dog is the subclass of both Mammal and Animal classes.

www.BrainKart.com
Now, if we consider the IS-A relationship, we can say:
 Mammal IS-A Animal
 Reptile IS-A Animal
 Dog IS-A Mammal
 Hence : Dog IS-A Animal as well
With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.

We can assure that Mammal is actually an Animal with the use of the instance operator.

Example:
public class Dog extends Mammal{

public static void main(String args[]){

Animal a = new Animal();


Mammal m = new Mammal();
Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This would produce the following result:

true
true
true
Since we have a good understanding of the extends keyword let us look into how
the implementskeyword is used to get the IS-A relationship.
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be
extended by the classes.

Example:
public interface Animal {}

public class Mammal implements Animal{


}

public class Dog extends Mammal{


}

www.BrainKart.com
The instanceof Keyword:
Let us use the instanceof operator to check determine whether Mammal is actually an Animal,
and dog is actually an Animal
interface Animal{}

class Mammal implements Animal{}

public class Dog extends Mammal{


public static void main(String args[]){

Mammal m = new Mammal();


Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This would produce the following result:

true
true
true
HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class HAS-
Acertain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:

public class Vehicle{}


public class Speed{}
public class Van extends Vehicle{
private Speed sp;
}
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have
to put the entire code that belongs to speed inside the Van class., which makes it possible to
reuse the Speed class in multiple applications.

In Object-Oriented feature, the users do not need to bother about which object is doing the real
work. To achieve this, the Van class hides the implementation details from the users of the Van
class. So basically what happens is the users would ask the Van class to do a certain action and
the Van class will either do the work by itself or ask another class to perform the action.

www.BrainKart.com
A very important fact to remember is that Java only supports only single inheritance. This means
that a class cannot extend more than one class. Therefore following is illegal:

public class extends Animal, Mammal{}

However, a class can implement one or more interfaces. This has made Java get rid of the
impossibility of multiple inheritance.

8. TEXT BOOKS :
1. E Balagurusamy,‖Object Oriented Programming with C++ and Java‖.
2. Ira Pohl, ―Object-Oriented Programming Using C++‖, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 RPC

www.BrainKart.com
1. CONTENT LIST:
 Packages and Interfaces

2. SKILLS ADDRESSED:
 Learning
 Analysis

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students understand about packages in java.
 To facilitate students understand about interfaces and inner classes.

4.OUTCOMES:
 Describe packages in java.
 Describe interfaces.

5.LINK SHEET:
 What is a package?
 How to create a package in java?
 Illustrate the use of set CLASSPATH system variable in package.
 What is a java interface?

www.BrainKart.com
6.EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)


Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

A Package can be defined as a grouping of related types(classes, interfaces, enumerations and


annotations ) providing access protection and name space management.

Some of the existing packages in Java are::

 java.lang - bundles the fundamental classes


 java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, annotations are related.

Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.

Creating a package:
When creating a package, you should choose a name for the package and put
a package statement with that name at the top of every source file that contains the classes,
interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be put into an unnamed package.

www.BrainKart.com
Example:
Let us look at an example that creates a package called animals. It is common practice to use
lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
Put an interface in the package animals:
/* File name : Animal.java */
package animals;

interface Animal {
public void eat();
public void travel();
}
Now, put an implementation in the same package animals:
package animals;

/* File name : MammalInt.java */


public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");
}

public int noOfLegs(){


return 0;
}

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
Now, you compile these two files and put them in a sub-directory called animals and try to run
as follows:
$ mkdir animals
$ cp Animal.class MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels

www.BrainKart.com
The import Keyword:
If a class wants to use another class in the same package, the package name does not need to be
used. Classes in the same package find each other without any special syntax.

Example:
Here, a class named Boss is added to the payroll package that already contains Employee. The
Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by
the following Boss class.

package payroll;

public class Boss


{
public void payEmployee(Employee e)
{
e.mailCheck();
}
}

What happens if Boss is not in the payroll package? The Boss class must then use one of the
following techniques for referring to a class in a different package.

The fully qualified name of the class can be used. For example:

payroll.Employee

The package can be imported using the import keyword and the wild card (*). For example:

import payroll.*;

The class itself can be imported using the import keyword. For example:

import payroll.Employee;
Note: A class file can contain any number of import statements. The import statements must
appear after the package statement and before the class declaration.
The Directory Structure of Packages:
Two major results occur when a class is placed in a package:

 The name of the package becomes a part of the name of the class, as we just discussed in the
previous section.

 The name of the package must match the directory structure where the corresponding
bytecode resides.

www.BrainKart.com
Here is simple way of managing your files in Java:

Put the source code for a class, interface, enumeration, or annotation type in a text file whose
name is the simple name of the type and whose extension is .java. For example:
// File Name : Car.java

package vehicle;

public class Car {


// Class implementation.
}
Now, put the source file in a directory whose name reflects the name of the package to which the
class belongs:

....\vehicle\Car.java

Now, the qualified class name and pathname would be as below:

 Class name -> vehicle.Car

 Path name -> vehicle\Car.java (in windows)

In general, a company uses its reversed Internet domain name for its package names. Example: A
company's Internet domain name is apple.com, then all its package names would start with
com.apple. Each component of the package name corresponds to a subdirectory.

Example: The company had a com.apple.computers package that contained a Dell.java source
file, it would be contained in a series of subdirectories like this:

....\com\apple\computers\Dell.java
At the time of compilation, the compiler creates a different output file for each class, interface
and enumeration defined in it. The base name of the output file is the name of the type, and its
extension is.class
For example:

// File Name: Dell.java

package com.apple.computers;
public class Dell{

}
class Ups{

www.BrainKart.com
Now, compile this file as follows using -d option:

$javac -d . Dell.java

This would put compiled files as follows:

.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class
You can import all the classes or interfaces defined in \com\apple\computers\ as follows:
import com.apple.computers.*;

Like the .java source files, the compiled .class files should be in a series of directories that reflect
the package name. However, the path to the .class files does not have to be the same as the path
to the .java source files. You can arrange your source and class directories separately, as:

<path-one>\sources\com\apple\computers\Dell.java

<path-two>\classes\com\apple\computers\Dell.class

By doing this, it is possible to give the classes directory to other programmers without revealing
your sources. You also need to manage source and class files in this manner so that the compiler
and the Java Virtual Machine (JVM) can find all the types your program uses.

The full path to the classes directory, <path-two>\classes, is called the class path, and is set with
the CLASSPATH system variable. Both the compiler and the JVM construct the path to your
.class files by adding the package name to the class path.

Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the
compiler and JVM will look for .class files in <path-two>\classes\com\apple\compters.

A class path may include several paths. Multiple paths should be separated by a semicolon
(Windows) or colon (Unix). By default, the compiler and the JVM search the current directory
and the JAR file containing the Java platform classes so that these directories are automatically
in the class path.

Set CLASSPATH System Variable:


To display the current CLASSPATH variable, use the following commands in Windows and
UNIX (Bourne shell):

 In Windows -> C:\> set CLASSPATH

 In UNIX -> % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use :

 In Windows -> C:\> set CLASSPATH=

www.BrainKart.com
 In UNIX -> % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable:

 In Windows -> set CLASSPATH=C:\users\jack\java\classes

 In UNIX -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH

INTERFACE

An interface is a collection of abstract methods. A class implements an interface, thereby


inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are
two different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface
need to be defined in the class.

An interface is similar to a class in the following ways:

 An interface can contain any number of methods.

 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The bytecode of an interface appears in a .class file.

 Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.

However, an interface is different from a class in several ways, including:

 You cannot instantiate an interface.

 An interface does not contain any constructors.

 All of the methods in an interface are abstract.

 An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.

 An interface is not extended by a class; it is implemented by a class.

 An interface can extend multiple interfaces.

www.BrainKart.com
Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to


declare an interface:
Example:
Let us look at an example that depicts encapsulation:

/* File name : NameOfInterface.java */


import java.lang.*;
//Any number of import statements

public interface NameOfInterface


{
//Any number of final, static fields
//Any number of abstract method declarations\
}

Interfaces have the following properties:

 An interface is implicitly abstract. You do not need to use the abstract keyword when
declaring an interface.

 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

 Methods in an interface are implicitly public.

Example:
/* File name : Animal.java */
interface Animal {

public void eat();


public void travel();
}

Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing
to perform the specific behaviors of the interface. If a class does not perform all the behaviors of
the interface, the class must declare itself as abstract.

A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.

/* File name : MammalInt.java */

www.BrainKart.com
public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");
}

public int noOfLegs(){


return 0;
}

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

This would produce the following result:

Mammal eats
Mammal travels

When overriding methods defined in interfaces there are several rules to be followed:

 Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.

 The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.

 An implementation class itself can be abstract and if so interface methods need not be
implemented.

When implementation interfaces there are several rules:

 A class can implement more than one interface at a time.

 A class can extend only one class, but implement many interfaces.

 An interface can extend another interface, similarly to the way that a class can extend another
class.

www.BrainKart.com
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 RPC

www.BrainKart.com
1. CONTENT LIST:
 Exception handling

2. SKILLS ADDRESSED:
 Learning
 Understanding
 Analysis

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students to understand about exception handling.

4. OUTCOMES:
 Describe exception handling.

5. LINK SHEET:
 What is exception handling?

www.BrainKart.com
6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)


An exception is a problem that arises during the execution of a program. An exception can occur
for many different reasons, including the following:

 A user has entered invalid data.

 A file that needs to be opened cannot be found.

 A network connection has been lost in the middle of communications or the JVM has
run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.

To understand how exception handling works in Java, you need to understand the three
categories of exceptions:

Checked exceptions: A checked exception is an exception that is typically a user error or a


problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but
the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the
time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably could have
been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are
ignored at the time of compilation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored
at the time of compilation.

www.BrainKart.com
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.

Errors are not normally trapped form the Java programs. These conditions normally happen in
case of severe failures, which are not handled by the java programs. Errors are generated to
indicate errors generated by the runtime environment. Example : JVM is out of Memory.
Normally programs cannot recover from errors.

The Exception class has two main subclasses: IOException class and RuntimeException Class.

Here is a list of most common checked and unchecked Java's Built-in Exceptions.
Exceptions Methods:
Following is the list of important medthods available in the Throwable class.

SN Methods with Description


public String getMessage()
1 Returns a detailed message about the exception that has occurred. This message
is initialized in the Throwable constructor.
public Throwable getCause()
2
Returns the cause of the exception as represented by a Throwable object.
public String toString()
3
Returns the name of the class concatenated with the result of getMessage()
public void printStackTrace()
4 Prints the result of toString() along with the stack trace to System.err, the error
output stream.

www.BrainKart.com
public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at
5
index 0 represents the top of the call stack, and the last element in the array
represents the method at the bottom of the call stack.
public Throwable fillInStackTrace()
6 Fills the stack trace of this Throwable object with the current stack trace, adding
to any previous information in the stack trace.

Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A try/catch
block is placed around the code that might generate an exception. Code within a try/catch block
is referred to as protected code, and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If
the type of exception that occurred is listed in a catch block, the exception is passed to the catch
block much as an argument is passed into a method parameter.

Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd
element of the array which throws an exception.

// File Name : ExcepTest.java


import java.io.*;
public class ExcepTest{

public static void main(String args[]){


try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}

This would produce the following result:

www.BrainKart.com
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Multiple catch Blocks:
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following:

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}

The previous statements demonstrate three catch blocks, but you can have any number of them
after a single try. If an exception occurs in the protected code, the exception is thrown to the first
catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets
caught there. If not, the exception passes down to the second catch statement. This continues
until the exception either is caught or falls through all catches, in which case the current method
stops execution and the exception is thrown down to the previous method on the call stack.

Example:
Here is code segment showing how to use multiple try/catch statements.

try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}

www.BrainKart.com
The throws/throw Keywords:
If a method does not handle a checked exception, the method must declare it using
the throwskeyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught,
by using the throw keyword. Try to understand the different in throws and throw keywords.
The following method declares that it throws a RemoteException:

import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}

A method can declare that it throws more than one exception, in which case the exceptions are
declared in a list separated by commas. For example, the following method declares that it
throws a RemoteException and an InsufficientFundsException:

import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
The finally Keyword
The finally keyword is used to create a block of code that follows a try block. A finally block of
code always executes, whether or not an exception has occurred.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax:

try
{
//Protected code

www.BrainKart.com
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
Example:
public class ExcepTest{

public static void main(String args[]){


int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}

This would produce the following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


First element value: 6
The finally statement is executed

Note the following:

 A catch clause cannot exist without a try statement.

 It is not compulsory to have finally clauses when ever a try/catch block is present.

 The try block cannot be present without either catch clause or finally clause.

 Any code cannot be present in between the try, catch, finally blocks.

www.BrainKart.com
Declaring you own Exception:
You can create your own exceptions in Java. Keep the following points in mind when writing
your own exception classes:

 All exceptions must be a child of Throwable.

 If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.

 If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below:

class MyException extends Exception{


}

You just need to extend the Exception class to create your own Exception class. These are
considered to be checked exceptions. The following InsufficientFundsException class is a user-
defined exception that extends the Exception class, making it a checked exception. An exception
class is like any other class, containing useful fields and methods.

Example:
// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception


{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}

To demonstrate using our user-defined exception, the following CheckingAccount class contains
a withdraw() method that throws an InsufficientFundsException.

// File Name CheckingAccount.java


import java.io.*;

public class CheckingAccount


{

www.BrainKart.com
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws
InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}

The following BankDemo program demonstrates invoking the deposit() and withdraw() methods
of CheckingAccount.

// File Name BankDemo.java


public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing $100...");

www.BrainKart.com
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}

Compile all the above three files and run BankDemo, this would produce the following result:

Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

8.TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Real time applications
 Neural networks and parallel processing
 Object oriented systems

www.BrainKart.com
1. CONTENT LIST:
 Multithreaded programming

2. SKILLS ADDRESSED:
 Learning
 Understanding
 Analysis

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students understand about threads in java.

4. OUTCOMES:
 Describe threads.
 Illustrate multithreading
 Explain the life cycle of thread

5. LINK SHEET:
 What is a thread?
 Explain the life-cycle of a thread.
 Give the thread priorities.
 Create a thread using extends.

www.BrainKart.com
6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)


Java is amultithreaded programming language which means we can develop multithreaded
program using Java. A multithreaded program contains two or more parts that can run
concurrently and each part can handle different task at the same time making optimal use of the
available resources specially when your computer has multiple CPUs.
By definition multitasking is when multiple processes share common processing resources such
as a CPU. Multithreading extends the idea of multitasking into applications where you can
subdivide specific operations within a single application into individual threads. Each of the
threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.

Multithreading enables you to write in a way where multiple activities can proceed concurrently
in the same program.

Life Cycle of a Thread:


A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. Following diagram shows complete life cycle of a thread.

www.BrainKart.com
Above-mentioned stages are explained here:

 New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
 Runnable: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
 Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task.A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
 Timed waiting: A runnable thread can enter the timed waiting state for a specified interval
of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
 Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in which threads execute and very much platform dependentant.

Create Thread: by Implementing Runnable Interface


If your class is intended to be executed as a thread then you can achieve this by
implementingRunnable interface. You will need to follow three basic steps:
STEP 1:

As a first step you need to implement a run() method provided by Runnable interface. This
method provides entry point for the thread and you will put you complete business logic inside
this method. Following is simple syntax of run() method:
public void run( )
STEP 2:

At second step you will instantiate a Thread object using the following constructor:
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface
and threadName is the name given to the new thread.

www.BrainKart.com
STEP 3

Once Thread object is created, you can start it by calling start( ) method, which executes a call
to run( ) method. Following is simple syntax of start() method:
void start( );
Example:
Here is an example that creates a new thread and starts it running:

class RunnableDemo implements Runnable {


private Thread t;
private String threadName;

RunnableDemo( String name){


threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start ()


{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}

public class TestThread {


public static void main(String args[]) {

www.BrainKart.com
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();
}
}

This would produce the following result:

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Create Thread by Extending Thread Class:
The second way to create a thread is to create a new class that extends Thread class using the
following two simple steps. This approach provides more flexibility in handling multiple threads
created using available methods in Thread class.
STEP 1

You will need to override run( ) method available in Thread class. This method provides entry
point for the thread and you will put you complete business logic inside this method. Following
is simple syntax of run() method:
public void run( )
STEP 2

Once Thread object is created, you can start it by calling start( ) method, which executes a call
to run( ) method. Following is simple syntax of start() method:
void start( );

www.BrainKart.com
Example:
Here is the preceding program rewritten to extend Thread:

class ThreadDemo extends Thread {


private Thread t;
private String threadName;

ThreadDemo( String name){


threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start ()


{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}

public class TestThread {


public static void main(String args[]) {

ThreadDemo T1 = new ThreadDemo( "Thread-1");


T1.start();

ThreadDemo T2 = new ThreadDemo( "Thread-2");


T2.start();
}

www.BrainKart.com
}

This would produce the following result:

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Thread Methods:
Following is the list of important methods available in the Thread class.

SN Methods with Description


public void start()
1 Starts the thread in a separate path of execution, then invokes the run() method
on this Thread object.
public void run()
2 If this Thread object was instantiated using a separate Runnable target, the run()
method is invoked on that Runnable object.
public final void setName(String name)
3 Changes the name of the Thread object. There is also a getName() method for
retrieving the name.
public final void setPriority(int priority)
4
Sets the priority of this Thread object. The possible values are between 1 and 10.
public final void setDaemon(boolean on)
5
A parameter of true denotes this Thread as a daemon thread.
public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current
6
thread to block until the second thread terminates or the specified number of
milliseconds passes.

www.BrainKart.com
public void interrupt()
7 Interrupts this thread, causing it to continue execution if it was blocked for any
reason.
public final boolean isAlive()
8 Returns true if the thread is alive, which is any time after the thread has
been started but before it runs to completion.

The previous methods are invoked on a particular Thread object. The following methods in the
Thread class are static. Invoking one of the static methods performs the operation on the
currently running thread.

SN Methods with Description


public static void yield()
1 Causes the currently running thread to yield to any other threads of the
same priority that are waiting to be scheduled.
public static void sleep(long millisec)
2 Causes the currently running thread to block for at least the specified number
of milliseconds.

3 public static boolean holdsLock(Object x)


Returns true if the current thread holds the lock on the given Object.
public static Thread currentThread()
4 Returns a reference to the currently running thread, which is the thread that
invokes this method.
public static void dumpStack()
5 Prints the stack trace for the currently running thread, which is useful when
debugging a multithreaded application.

Example:
The following ThreadClassDemo program demonstrates some of these methods of the Thread
class. Consider a class DisplayMessage which implements Runnable:
// File Name : DisplayMessage.java
// Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
private String message;
public DisplayMessage(String message)
{
this.message = message;
}
public void run()
{
while(true)
{

www.BrainKart.com
System.out.println(message);
}
}
}

Following is another class which extends Thread class:

// File Name : GuessANumber.java


// Create a thread to extentd Thread
public class GuessANumber extends Thread
{
private int number;
public GuessANumber(int number)
{
this.number = number;
}
public void run()
{
int counter = 0;
int guess = 0;
do
{
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName()
+ " guesses " + guess);
counter++;
}while(guess != number);
System.out.println("** Correct! " + this.getName()
+ " in " + counter + " guesses.**");
}
}

Following is the main program which makes use of above defined classes:

// File Name : ThreadClassDemo.java


public class ThreadClassDemo
{
public static void main(String [] args)
{
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();

Runnable bye = new DisplayMessage("Goodbye");

www.BrainKart.com
Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();

System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);

thread4.start();
System.out.println("main() is ending...");
}
}

This would produce the following result. You can try this example again and again and you
would get different result every time.

Starting hello thread...


Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......

8. TEXT BOOKS :

www.BrainKart.com
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 Real time systems.

1. CONTENT LIST:
 Strings

2. SKILLS ADDRESSED:
 Learning
 Implementing

www.BrainKart.com
3. OBJECTIVE OF THIS LESSON PLAN:
 To facilitate students understand about strings in java.

4. OUTCOMES:
 Describe strings in java.

5. LINK SHEET:
 What are all the string operations that can be done in java?
 Illustrate the strings with a sample java program

6. EVOCATION: (10 Minutes)

www.BrainKart.com
7.LECTURE NOTES (45 minutes)

Strings, which are widely used in Java programming, are a sequence of characters. In the
Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings:
The most direct way to create a string is to write:

String greeting = "Hello world!";

Whenever it encounters a string literal in your code, the compiler creates a String object
with its value in this case, "Hello world!'.

As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has eleven constructors that allow you to provide the initial value of
the string using different sources, such as an array of characters.

public class StringDemo{

public static void main(String args[]){


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println( helloString );
}
}

This would produce the following result:

www.BrainKart.com
hello.
String Length:
Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the number
of characters contained in the string object.

After the following two lines of code have been executed, len equals 17:

public class StringDemo {

public static void main(String args[]) {


String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}

This would produce the following result:

String Length is : 17
Concatenating Strings:
The String class includes a method for concatenating two strings:

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end. You can also use the
concat() method with string literals, as in:

"My name is ".concat("Zara");

Strings are more commonly concatenated with the + operator, as in:

"Hello," + " world" + "!"

which results in:

"Hello, world!"

Let us look at the following example:

public class StringDemo {

www.BrainKart.com
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}

This would produce the following result:

Dot saw I was Tod


Creating Format Strings:
You have printf() and format() methods to print output with formatted numbers. The String class
has an equivalent class method, format(), that returns a String object rather than a PrintStream
object.

Using String's static format() method allows you to create a formatted string that you can reuse,
as opposed to a one-time print statement. For example, instead of:

System.out.printf("The value of the float variable is " +


"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);

you can write:

String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
RPC

www.BrainKart.com
1. CONTENT LIST:
 Input/Output

2. SKILLS ADDRESSED:
 Learning
 Understanding
 Analysis

3. OBJECTIVE OF THIS LESSON PLAN:


 To facilitate students understand about java streams and i/o.

4. OUTCOMES:
 Describe streams.

5. LINK SHEET:
 What are the streams that are used in java?

www.BrainKart.com
6. EVOCATION: (10 Minutes)

7. LECTURE NOTES: (40 Minutes)


STREAMS
The java.io package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination. The
stream in the java.io package supports many data such as primitives, Object, localized characters,
etc.

A stream can be defined as a sequence of data. The InputStream is used to read data from
a source and the OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to Files and networks but this
tutorial covers very basic functionality related to streams and I/O. We would see most commonly
used example one by one:

Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are
many classes related to byte streams but the most frequently used classes are
, FileInputStream andFileOutputStream. Following is an example which makes use of these
two classes to copy an input file into an output file:
import java.io.*;

public class CopyFile {


public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;

www.BrainKart.com
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content:
This is test for copy file.

As a next step, compile above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt. So let's put above code in CopyFile.java file and
do the following:

$javac CopyFile.java
$java CopyFile

Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as
Java Characterstreams are used to perform input and output for 16-bit unicode. Though there
are many classes related to character streams but the most frequently used classes are
, FileReader and FileWriter.. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at
a time and FileWriter writes two bytes at a time.
We can re-write above example which makes use of these two classes to copy an input file
(having unicode characters) into an output file:

import java.io.*;

public class CopyFile {


public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

www.BrainKart.com
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content:
This is test for copy file.

As a next step, compile above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt. So let's put above code in CopyFile.java file and
do the following:

$javac CopyFile.java
$java CopyFile

Standard Streams
All the programming languages provide support for standard I/O where user's program can take
input from a keyboard and then produce output on the computer screen. If you are aware if C or
C++ programming languages, then you must be aware of three standard devices STDIN,
STDOUT and STDERR. Similar way Java provides following three standard streams

 Standard Input: This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System.in.
 Standard Output: This is used to output the data produced by the user's program and
usually a computer screen is used to standard output stream and represented as System.out.
 Standard Error: This is used to output the error data produced by the user's program and
usually a computer screen is used to standard error stream and represented as System.err.
Following is a simple program which creates InputStreamReader to read standard input stream
until the user types a "q":
import java.io.*;

public class ReadConsole {


public static void main(String args[]) throws IOException
{
InputStreamReader cin = null;

www.BrainKart.com
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}

Let's keep above code in ReadConsole.java file and try to compile and execute it as below. This
program continues reading and outputting same character until we press 'q':

$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
Reading and Writing Files:
As described earlier, A stream can be defined as a sequence of data. The InputStream is used to
read data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

www.BrainKart.com
The two important streams are FileInputStream and FileOutputStream, which would be
discussed in this tutorial:
FileInputStream:
This stream is used for reading data from the files. Objects can be created using the keyword new
and there are several types of constructors available.

Following constructor takes a file name as a string to create an input stream object to read the
file.:

InputStream f = new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows:

File f = new File("C:/java/hello");


InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be
used to read to stream or to do other operations on the stream.
SN Methods with Description
public void close() throws IOException{}
1 This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method
2
of this file output stream is called when there are no more references to this
stream. Throws an IOException.
public int read(int r)throws IOException{}
3 This method reads the specified byte of data from the InputStream. Returns an
int. Returns the next byte of data and -1 will be returned if it's end of file.

www.BrainKart.com
public int read(byte[] r) throws IOException{}
4 This method reads r.length bytes from the input stream into an array. Returns the
total number of bytes read. If end of file -1 will be returned.
public int available() throws IOException{}
5 Gives the number of bytes that can be read from this file input stream. Returns
an int.

There are other important input streams available, for more detail you can refer to the following
links:

 ByteArrayInputStream
 DataInputStream
FileOutputStream:
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write the
file:

OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows:

File f = new File("C:/java/hello");


OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.
SN Methods with Description
public void close() throws IOException{}
1 This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method
2
of this file output stream is called when there are no more references to this
stream. Throws an IOException.
public void write(int w)throws IOException{}
3
This methods writes the specified byte to the output stream.
public void write(byte[] w)
4
Writes w.length bytes from the mentioned byte array to the OutputStream.

www.BrainKart.com
There are other important output streams available, for more detail you can refer to the following
links:

 ByteArrayOutputStream
 DataOutputStream
Example:
Following is the example to demonstrate InputStream and OutputStream:

import java.io.*;

public class fileStreamTest{

public static void main(String args[]){

try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();

InputStream is = new FileInputStream("test.txt");


int size = is.available();

for(int i=0; i< size; i++){


System.out.print((char)is.read() + " ");
}
is.close();
}catch(IOException e){
System.out.print("Exception");
}
}
}

The above code would create file test.txt and would write given numbers in binary format. Same
would be output on the stdout screen.

File Navigation and I/O:


There are several other classes that we would be going through to get to know the basics of File
Navigation and I/O.

 File Class
 FileReader Class
 FileWriter Class

www.BrainKart.com
Directories in Java:
A directory is a File which can contains a list of other files and directories. You use File object to
create directories, to list down files available in a directory. For complete detail check a list of all
the methods which you can call on File object and what are related to directories.
Creating Directories:
There are two useful File utility methods, which can be used to create directories:
 The mkdir( ) method creates a directory, returning true on success and false on failure.
Failure indicates that the path specified in the File object already exists, or that the directory
cannot be created because the entire path does not exist yet.
 The mkdirs() method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory:

import java.io.File;

public class CreateDir {


public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}

Compile and execute above code to create "/tmp/user/java/bin".

Note: Java automatically takes care of path separators on UNIX and Windows as per
conventions. If you use a forward slash (/) on a Windows version of Java, the path will still
resolve correctly.
Listing Directories:
You can use list( ) method provided by File object to list down all the files and directories
available in a directory as follows:
import java.io.File;

public class ReadDir {


public static void main(String[] args) {

File file = null;


String[] paths;

try{
// create new file object
file = new File("/tmp");

// array of files and directory

www.BrainKart.com
paths = file.list();

// for each name in the path array


for(String path:paths)
{
// prints filename and directory name
System.out.println(path);
}
}catch(Exception e){
// if any error occurs
e.printStackTrace();
}
}
}
This would produce following result based on the directories and files available in
your /tmp directory:
test1.txt
test2.txt
ReadDir.java
ReadDir.class

8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003

9. APPLICATIONS :
 RPC

www.BrainKart.com

You might also like