Professional Documents
Culture Documents
Information Technology
(DISTANCE MODE)
DCS 115
Object Oriented Programming
I SEMESTER
COURSE MATERIAL
Author
Reviewer
Editorial Board
Dr. C. Chellappan
Professor
Department of Computer Science
and Engineering
Anna University Chennai
Chennai 600 025
Professor
Department of Computer Science
and Engineering
Anna University Chennai
Chennai 600 025
Copyrights Reserved
(For Private Circulation only)
ACKNOWLEDGEMENT
I would like to express my sincere thanks to Dr.C.Chellapppan, Professor and
Deputy Director, Centre for Distance Education, Anna University, Chennai for providing
me theme the opportunity to prepare this course material.
I am very much grateful to acknowledge the following sources from where the
inputs where drawn to prepare this course material, to meet the requirements of the
syllabus
H.Schildt, Teach yourself C++, Osborne 2000
E. Balagurusamy Object Oriented Progamming with c++, Tat Mcgraw till 2000
Walter Savitch, Problem Solving with c++, Addison Wesly 2002 (4th Edition) 1995
Rick Mercer, Computing fundamentals with c++, Object Oriented Programming &
design, Mac Millan Press IInd edition 1995
Stroustrup, B., The c++ Programming Language Addision-Wesley,1997
(3rd edition)
Bruce Eckel, Thinking in c++, 2000 prentice Hall.
Jamie Jaworski Java2 Certification guide ,2000, New Riders
http:// www. Sun.com
Brouce Eckel, Thinking in Java, 2000 prentice Hall
E. Balagurusamy, Programming with Java, Tata Mcgraw hill 2000.
DCS 115
Page Nos.
CHAPTER 2 - FUNCTIONS
21
37
65
CHAPTER 5 - INHERITANCE
83
CHAPTER 6 - POLYMORPHISM
113
CHAPTER 7 - FILES
123
CHAPTER 8 - TEMPLATES
143
159
175
197
224
235
CHAPTER 14 - INTERFACES
249
CHAPTER 15 -PACKAGES
260
273
DCS 116
DATA STRUCTURES
Page Nos.
DCS 115
NOTES
CHAPTER 1
INTRODUCTION TO C++
PROGRAMMING
Structure of the Unit
Data Types
Built in Data Types
User Defined Data Types
Derived Data Types
Control Structures
Expressions
Conditional Expressions
1.1. Introduction
C++ is an object oriented language. It is an expanded version of C
language.C++ was invented by Bjarne Stroustrup in 1979 at Bell laboratories in
Murray Hill, New Jersy. C++ was originally called as C with classes , however
the name was changed to C++ in 1983.
C++ is a superset of C, hence almost all concepts available in C is also
available in C++.This chapter discuss about all the fundamental concepts of this
programming language. This chapter introduces basic console I/O statements and
manipulators. This chapter then discusses all C++ tokens, data types and control
structures. This chapter provides the necessary background to understand the C++
concepts presented in the subsequent chapters.
1.2 Learning Objectives
DCS 115
NOTES
DCS 115
NOTES
You can input any items as you like in one input statement. As in C,
individual data items must be separated by whitespace characters (spaces, tabs,
or newlines). When a string is read, input will stop when the first whitespace
character is encountered.
NOTE :
A comment in C++ can be given in a same way as we give in C. /* .... */ is a
multline comment and // is a single line comment. For Example
/* This is a multiline comment and can
Span for multilines.This comment
is similar to C */
// This is a singleline comment
DCS 115
NOTES
Keywords
Identifiers
Constants
Operators
1.5.1 Keywords
The list given below contains all the C++ keywords. Every keyword will perform a
specific operation in C++. Keywords in C++ cannot be redefined by a programmer;
further keywords cannot be used as identifier name.
and
bool
compl
do
export
goto
namespace
or_eq
return
struct
try
using
xor
and_eq
break
const
double
extern
if
new
private
short
switch
typedef
virtual
xor eq
asm
case
const_cast
dynamic_cast
false
inline
not
protected
signed
template
typeid
void
auto
catch
continue
else
float
int
not_eq
public
sizeof
this
typename
volatile
bitand
char
default
enum
for
long
operator
register
static
throw
union
wchar t
bitor
class
delete
explicit
friend
mutable
or
reinterpret_cast
static_cast
true
unsigned
while
DCS 115
NOTES
1.5.2 Identifiers
Every named program component in C++ like variables, functions, arrays, classes
etc. must have legal identifier (name) .In C++ all variables must be declared before
they are used. Furthermore, variables must be used in a manner consistent with
their associated type.
An identifier is formed with a sequence of letters (including _ ) and digits. The
first character must be a letter. Identifiers are case sensitive, i.e., first_name is
different from First_name.
Examples of valid variable names are
myname, jj, name123
Examples of invalid variables
12B
Basic pay
ABC,1
1.5.3 Constants
Constants refer to values that do not change during the execution of the program.
Examples for constants are
1998
25.789
Hello World
a
Integer constant
Floating point constant
String constant
Character constant
1.5.4 Operators
The various operators in C++ and their associatively are listed below in the
Table 1.1. The Operators are listed according to their precedence
Associativity
Operator
left to right
::
left to right
Right to left
! (negation), ~ (bit-not)
Right to left
Left to right
*, /, % (modulus)
5
DCS 115
NOTES
Left to right
-+
Left to right
<<, >>
Left to right
Left to right
= =, !=
Left to right
Left to right
^ (bit-xor)
Left to right
Left to right
|| (logical or)
Right to left
?:
Left to right
throw
Left to right
Right to left
int x,y
long int a;
DCS 115
Unsigned integer:
The unsigned integer types are unsigned short int (abbreviation unsigned
short), unsigned int and unsigned long int (abbreviation unsigned long). The sizes
follow the same rules as for singed integers. Examples for unsigned integer variable
declarations are listed below.
NOTES
unsigned short a;
unsigned long x;
Character type:
Character type variables can hold a single character. The character types
are char, signed char and unsigned char. Note that a simple char can mean either
signed or unsigned, as this is not defined in ANSI C. It depends therefore only on
the implementation of the compiler. A variable can be declared as character type
as given below.
char x
double m
float f
Boolean type:
Standard C++ has an explicit boolean type bool. (C only has an implicit
boolean type: 0 = logical false, nonzero = logical true). This type is used to express
results of logical operations. The value of the Boolean type is symbolic, either
false or true. To ensure compatibility with C and older C++ compiler, the boolean
type is automatically converted to/from integer values. In these cases an integer
value of 0 indicates false and a non-zero value indicates true. A variable can be
declared as boolean type as given below.
bool logic
Empty type:
The special type void is used for three occasions: defining a function
without parameters, defining a function that has no return value and for generic
pointers. Example
7
DCS 115
NOTES
void func()
The following Table 1.2 with sizes of data types has been generated on a
Windows NT and Linux system
Data Type
Char
Short int
Int
Float
Double
long double
1
2
4
4
8
8
1
2
4
4
8
12
DCS 115
NOTES
union u1
{
int i;
float f;
char c;
} u;
The variable u will be large enough to hold the largest of the three types; the
specific size is implementation-dependent. In this example the size of the union
variable will be 4 bytes (since the float variable occupies 4 bytes). Unions allow
only one variable to refer at a time; all union variables cannot be accessed
simultaneously.
Syntactically, members of a union are accessed as
union-name.member
or
union-pointer->member.
Classes are discussed in detail in chapter 3
Enumeration Data Type
An enumeration is a set of named integer constants that specify all the allowable
set of values a variable of that type may have.The general syntax of enumeration
data type is
enum enum-name{enumeration values} ;
Example
enum states{Andhara,Karnataka,Kerala,Tamilnadu} ;
enum currency { dollar,euro,rupees}
Once the enumeration is created, we can declare variables of that type. Example
coin money;
states s;
Given these declarations the following statements are valid. The statements
if(s= =kerala)
cout<<Welcome to Gods Own Country;
and
cin>>money;
if(money==rupees)
{
//do this
9
DCS 115
NOTES
}
are perfectly valid.
1.6.3 Derived Data Type
Arrays
In C++ arrays are handled in the same way as of C. For example the declaration
int a[10];
defines an array of size 10, that is, a block of 10 consecutive objects named a[0], a[1],
...,a[9].
10
DCS 115
NOTES
The control-flow of a language specifies the order in which computations are performed.
The various control structures supported by C++ is discussed below.
If-Else
The if-else statement is used for making decisions. The syntax is
if (expression)
statement1
else
statement2
The flow chart for if else is given below.
True
False
Expression
Statements
Statements
True
False
a>b
C=a
C=b
11
DCS 115
NOTES
In this example the value of a will be assigned c if a is greater than b else the value of b
will be assigned to c.
Else if
The syntax for else-if ladder structure is given below
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
This sequence of if statements is the most general way of writing a multi-way
decision. The expressions are evaluated in order; if an expression is true, the
statement associated with it is executed, and this terminates the whole chain.
The last else part handles the default case where none of the other conditions is
satisfied.
An example for this construct is given below.
if (( a>b) && (a>c))
cout<<A is big;
else if ((b>a) && (b>c))
cout<<B is big;
else if ((c>a) && (c>b))
cout<<C is big;
Switch Statement
The switch statement is a multi-way decision that tests whether an expression
matches one of a number of constant integer values, and branches accordingly.
The syntax of switch statement is given below.
switch (expression)
{
case const-expr:
statements
12
DCS 115
case const-expr:
statements
default:
statements
}
NOTES
causes an immediate exit from the switch after the code for one case is done,
execution falls through to the next case unless you leave the switch .You can use
break statement to explicitly come out of the switch.
Looping Statements
C++ supports three type of looping statements as C language .They are
While Loop
DoWhile Loop
For Loop
While Loop
The Syntax of while loop is
while (expression)
{
13
DCS 115
statements;
NOTES
}
the expression is evaluated. If it is non-zero(i.e. if the condition given in the
expression is true) , statements is executed and expression is re-evaluated. This
cycle continues until expression becomes zero (false).
Example
i=0; //initial value
while(i<100) //condition
{
cout<<i;
i=i+2 //increment
}
Here in this example the while loop prints all the even numbers between 0 and
100.Note the while loop checks for the condition i<100 every time when the loop
iterates.
For Loop
The for statement is given below
Most commonly, expr1 and expr3 are assignments or function calls and expr2 is a
relational expression. Any of the three parts can be omitted, although the
semicolons must remain. If expr1 or expr3 is omitted, it is simply dropped from
the expansion. If the test, expr2, is not present, it is taken as permanently true.
Anna University Chennai
14
DCS 115
NOTES
Example
for (i=0 ;i<100 ;i=i+2)
cout<<i;
This is the for loop version of the previous program for printing even numbers
between 0 and 100.Here we can note that in for loop the initilaization,condition
and increment statements are kept together in the for statement.
Do...while Loop
The while and for loops test the termination condition at the top. But the dowhile, tests at the bottom after making each pass through the loop body; the body
is always executed at least once. The Syntax of do while statement is
do
{
Statements;
}while (expression);
The statement is executed, and then expression is evaluated. If it is true, statement
is evaluated again, and so on. When the expression becomes false, the loop
terminates. do...while loop is essential when we expect the loop to be executed at
least once irrespective of the condition.
Example
i=0; //initialization
do
{
cout<<i;
i+=2; //increment
}while(i<100); //condition.
Break and Continue Statements
Sometimes it will require exiting from a loop other than by testing at the top or
bottom. The break statement provides an early exit from for, while, and do, just as
from switch. A break causes the innermost enclosing loop or switch to be exited
immediately. The example given below helps a better understanding about break
statement.
15
DCS 115
NOTES
while (i<100)
{
cout<<ENTER NEGATIVE NUMBER TO EXIT;
cin>>a;
if(a < 0)
break;
sum+=a;
}
In this example the while loop is writtern to execute 100 times but however when
the user gives a negative input the break statement causes the loop to make an
early exit
The continue statement is related to break, it causes the next iteration of the enclosing
for, while, or do loop to begin. In the while and do, this means that the test part is
executed immediately; in the for, control passes to the increment step. The continue
statement applies only to loops, not to switch. Consider the example
for (i = 0; i < 100; i++)
{
cin>>c;
if (c <= 0) /* skip the remaining part of the loop */
continue;
no_of_positive++;
}
The continue statement is used here to skip the remaining part of the loop when a
negative number is given as input.
Have you Understood Questions?
1. Mention the control structures that is used for multi way decisions
2. How does a while loop differs from do while loop
3. In which situations we will use break and continue statements
1.8 Expressions
An expression is a combination of operands (both variables and constants),
operators arranged as per the syntax of the language.An expression may be an
simple expression such as
i=i+2
An expression may also use combination of simple expressions such as
i=i * 2 + (m +1)/2
16
DCS 115
NOTES
An expression such as
a=a+2
in which the variable on the left side is repeated immediately on the right, can be
written in the compressed form
a+= 2
The operator += is called an assignment operator.
Most binary operators (operators like + that have a left and right operand) have a
corresponding assignment operator op=, where op is one of
+ - * / % << >> & ^ |
k += m*5 is equivalent to
k=k+m*5
Conditional Expressions
The statements
if (a > b)
c = a;
else
c = b;
Assign c the maximum of a and b. The conditional expression, written with the ternary
operator ?:, provides an alternate way to write this and similar constructions. In the
expression
expr1 ? expr2 : expr3
the expression expr1 is evaluated first. If it is non-zero (true), then the expression expr2
is evaluated, and that is the value of the conditional expression. Otherwise expr3 is
evaluated, and that is the value. Only one of expr2 and expr3 is evaluated. Thus to set
c to the maximum of a and b.
17
DCS 115
NOTES
Exercises
Short Questions
1. Write any two differences between C and C++.
2. cout is an input statement(TRUE/FALSE)
3. A logical AND we have___________ associativity.
4. ___________ operator is used to access a structure variables.
5. Write the significance of void datatype.
6. List out the various user defined datatypes available in C++.
18
DCS 115
Long Questions
NOTES
*/
Section 1.4
1. setw(5)
2. endl
Section 1.5
1. Keywords,Identifiers,Constants,Operators
2. A constant will not change its value during program execution, but a
variable does.
Section 1.6
1. Built in data type, User defined datatpe and derived data type.
2. A structure is a collection of one or more variables, possibly of different
types, grouped together under a single name for convenient handling.
3. An enumeration is a set of named integer constants that specify all the
allowable set of values a variable of that type may have.
4. A pointer is a variable that contains the address of a variable.
Section 1.7
1. else.. if ladder structure and switch statement.
19
DCS 115
2. While loop checks the condition first and then executes the loop on the other
hand do while loop checks that condition at the last. We can guarantee that a
do while loop will at least once but such guarantee cannot be given for while
loop.
NOTES
3. The break statement provides an early exit from for, while, and do, just as
from switch.
Section 1.8
1. a+=b.
2. The conditional expression, written with the ternary operator ?:, provides
an alternate way to write simple if statement.
References
1.
2.
3.
4.
20
DCS 115
NOTES
CHAPTER 2
FUNCTIONS
Function Prototypes
Functions with Return Values
Call by Value
Call by Reference
2.1
Return by Reference
Inline Functions
Functions with Default Arguments
Function Overloading
Introduction
Learning Objectives
2.3
DCS 115
NOTES
2.3.1
Function Prototypes
#include <iostream.h>
void show(int);
// FUNCTION PROTOTYPE
void main()
{
int a;
cout<<Enter the value for A;
cin>>a
show(a);
}
void show(int x)
{
cout<<The value passed to function is << x;
}
Output of the Program
Enter the value for A 20
The value passed to function is 20
22
DCS 115
This program make use of a function called show( ) with an integer parameter .The
function just displays the value of x. Since the function is not returning anything its
return type is made void.
2.3.2
NOTES
As mentioned earlier a function can take parameters and also can return value.
Example 2:
This function show() used in this program takes two parameters and returns the
sum of the parameters
#include <iostream.h>
int mul(int,int);
// FUNCTION PROTOTYPE
void main()
{
int a,b,c;
cout<<Enter two values <<endl;
cin>>a>>b;
c=mul(a,b);
cout<<The Product is <<c;
}
int show(int x,int y)
{
int z;
z=x * y;
return z;
}
Output of the Program
Enter two values
5
6
The Product is 30
The variable a,b are known as actual parameters whose values are copied
to the dummy variables x and y. The result of the multiplication is stored in z and
this value is copied to c.
2.3.3
Call by Value
DCS 115
NOTES
parameters. The main effect is that even if the dummy parameters are modified the
corresponding parameter will not change the arguments value.
Example 3:
The following program makes use of call by value concept to swap the values of
two variables.
#include<iostream.h>
void swap(int,int);
void main()
{
int a,b;
cout<<enter two values <<endl;
cin>>a>>b;
swap(a,b);
cout<<Values in the main program\n;
cout<<a<<\t<<b;
}
void swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
cout<<The values after swapping in swap() function \n <<x<<\t<<y;
}
Output of the Program
enter two values
10
20
The values after swapping in swap() function
20
10
Values in the main program
10
20
If suppose you give 5 and 6 as input to a and b which are copied x and y parameters
of the swap function(which swaps the value of x and y).The swapped values will
not affect the actual parameters a and b thus the cout statement in the main
program will print only 5 and 6
24
DCS 115
2.3.4
Call by Reference
NOTES
25
DCS 115
NOTES
2.3.5
Return by Reference
26
DCS 115
2.4
Inline Functions
NOTES
Inline functions are like macros. Inline functions will avoid the time complexity that
arises due to context switch over head in a function call. A context switch involves
locating the function, moving to it, saving the register status, pushing the arguments in
the stack and returning to the calling function. All these overheads can be avoided by
making a function inline. Inline functions have some restrictions.
The disadvantage of in-line functions is that if they are too large and called to
often, the program grows larger. For this reason, in general only short functions
are declared as in-line functions.
A Function can be made inline by prefixing it with the keyword inline. The Syntax
for writing Inline function is given below.
inline function-prototype
{
function body
}
Example 6:
This example program makes use of inline function to determine whether the
given number is Odd/Even.
#include < iostream.h >
#include<iomanip.h>
inline int even(int x)
{
if (x %2==0)
return 1;
else
return 0;
}
int main( )
{
int a;
cout<<Enter any number<<endl;
27
DCS 115
cin>>a;
if(even(a))
cout<<EVEN NUMBER;
else
cout<<ODD NUMBER;
NOTES
}
Output of the Program
Enter any number
20
EVEN NUMBER
Have you Understood Questions?
1. What do you mean by Inline functions?
2. How will you make a function Inline?
2.5
In C++ it is possible to call functions without passing all its arguments. This can
be made possible by specifying the default arguments. The default arguments
will be specified with some default values. Default parameters will be used when
there is a missing parameter in the function call.
For Example consider the following function declaration.
int add(int x , int y=100,int z=200);
Here we can note that the default value to the parameter is assigned as an ordinary
variable initialization. Thus all the function calls given below are valid.
m=add(15);
m=add(10,20);
m=add(10,20,30)
The following point has to be noted while writing functions with default arguments.
28
DCS 115
int add(int x=100,int y,int z) //default parameters should be assigned from left to
right
int add(int x,int y=100,int z) //default parameters should be assigned from left to
right
NOTES
Example 7:
The following example illustrates the concept of default arguments in a function
#include<iostream.h>
#include<iomanip.h>
void add(int ,int=5,int=7); // DEFAULT VALUE DECLARED
void main()
{
int a,b,c;
cout<<enter three values<<endl;
cin>>a>>b>>c;
cout<<Output with only 2 parameters <<endl;
add(a,b); \\ Third parameter missing hence default parameter used
cout<<Output with all 3 parameters <<endl;
add(a,b,c);
}
void add( int x, int y, int z)
{
int t;
t=x+y+z;
cout<<t;
}
Output of the Program
enter three values
10
20
30
Output with only 2 parameters
37
Output with all 3 parameters
60
Example 8:
The following example makes use of the function called simpleinterest with default
arguments
29
DCS 115
NOTES
#include<iostream.h>
#include<iomanip.h>
float simpleinterset(int ,int=5,float=3.5); // DEFAULT VALUE DECLARED
void main()
{
int p,n;
float r,si;
cout<<enter the principal amount<<endl;
cin>>p;
cout<<enter the number of years<<endl;
cin>>n;
cout<<enter the rate of interest<<endl;
cin>>r;
cout<<Output with only 2 parameters <<endl;
simpleinterest(p,n); \\Third parameter missing hence default parameter used(i.e
float=3.5)
cout<<Output with all 3 parameters <<endl;
simpleinterest (p,n,r);
}
float simpleinterest( int x, int y, float z)
{
float ans;
ans=(x*y*z)/100;
return ans;
}
Have you Understood Questions?
1. Default parameters are assigned from ________ to ___________ .
2.6
Function Overloading
Function overloading is one of the most important features available in C++ two
or more functions can share the same name as long as either the type of their
arguments differs or the number of their arguments differs - or both. When two or
more functions share the same name, they are said overloaded.
Overloaded functions can help reduce the complexity of a program by allowing
related operations to be referred to by the same name. To overload a function,
Anna University Chennai
30
DCS 115
simply declare and define all required versions. The compiler will automatically select
the correct version based upon the number and/or type of the arguments used to call
the function. Function overloading provides the compile time polymorphism feature of
OOPS.
NOTES
(ii)
(iii)
(ii)
int convert(int x)
float convert (int j);
Remember that the return type alone is not sufficient to allow function overloading.
If two functions differ only in the type of data they return, the compiler will not
always be able to select the proper one to call.
Example 9:
The following example illustrates the overloading of sum( ) function.
#include<iostream.h>
#include<iomanip.h>
void sum(int,int);
void sum(int,int,int);
void main()
{
int a ,b, c ;
cout<<Enter three values <<endl;
cin>>a>>b>>c;
cout<<Calling the function with two parameters<<endl;
31
DCS 115
NOTES
sum(a,b);
cout<<Calling the function with three parameters<<endl;
sum(a,b,c);
}
void sum(int x,int y)
{
int z;
z=x+y;
cout<<z;
}
void sum(int x,int y,int z)
{
int r;
r=x+y+z;
cout<<r;
}
Output of the Program
enter three values
10
20
30
Calling the function with two parameters
30
Calling the function with three parameters
60
The compiler automatically calls the correct version of the function based
upon the type of data used as an argument. Overloaded functions can also differ
in the number of arguments.
Example 10:
This example overloads the function called area.
#include<iostream.h>
#include<iomanip.h>
int area(int side);
float area(float radius);
int area(int l,int b)
void main()
{
int s;
float r,
32
DCS 115
int len,bre;
NOTES
33
DCS 115
NOTES
Summary
1. Functions provide modular structure to C++ program Functions help to divide
a larger program into number of smaller units which is the basis of top down
approach.
2. In C++ functions can be called by value, called by reference and can return
by reference
3. By default, functions pass arguments by value, which means that when
the function is used, the actual values of arguments are copied into the
dummy parameters.
4. In call by reference, the & symbol specifies that the actual parameter
and dummy the argument correspond to the same value.
5. Inline functions are like macros. Inline functions will avoid the time
complexity that arises due to context switch over head in a function call.
6. In C++ it is possible to call functions without passing all its arguments.
This can be made possible by specifying the default arguments
7. In C++ two or more functions can share the same name as long as either
the type of their arguments differs or the number of their arguments differs
- or both. When two or more functions share the same name, they are said
overloaded.
Exercises
Short Questions
1.
2.
3.
4.
5.
Long Questions
1. Explain the concept of call by value, call by reference and return by
reference in detail.
2. Mention the rules associated with passing of default arguments. Give
example
3. Explain function overloading with examples.
Programming Exercises
1. Create a function to compute simple interest. Supply default arguments to
the function
2. Create an overloaded function called myabs() to find absolute value for
a number.( absolute value for a number is the positive value of that number)
Anna University Chennai
34
DCS 115
NOTES
35
DCS 115
NOTES
References
1.
2.
3.
4.
36
DCS 115
NOTES
CHAPTER 3
CLASSES AND OBJECTS IN C++
Structure of the Unit
3.1
Introduction
In the previous chapters, you have followed the modular approach to C++
programming. The power of C++ lies in writing object oriented programs. In
object oriented programming the data members and the functions which act upon
those data are combined into a single entity called Object. Object provides a
systematic way of accessing the data members. This chapter introduces you to
write object oriented C++ programs using classes and objects. This chapter then
discusses details regarding Constructers and Destructors. Further this chapter
introduces static data members, static functions and const functions. At the end
this chapter provides necessary details regarding friend functions and classes.
3.2
Learning Objectives
DCS 115
NOTES
3.3
Classes and structures are syntactically and functionally identical, C++ structures and
classes have their own members. These members include variables (including other
structures and classes), functions (specific identifiers or overloaded operators) known
as methods, constructors and destructors. Classes and Structures are declared with
class and struct keywords respectively. Declaration of the members are done within
the definition of classes and structures. For example
struct book
{
int pages;
char *author;
float price
};
class book
{
public:
int pages;
char *author;
float price
};
From these declarations you can note that except the public keyword in class, both
the declarations are identical.
Till this point structures and classes are identical. But class is superior user defined data
type that incorporates some additional features than structures. Classes and structures
differ in the following aspects.
By default, the members of structures are public while that for class is private
Structures doesnt provide something like data hiding which is provided by
the classes
Classes supports data hiding but Structures doesnt provide data hiding
Structures contains only data while class bind both data and member functions
38
DCS 115
Since class is specially designed user defined data type in C++ to bind data and code,
this book focus only on classes.
NOTES
39
DCS 115
NOTES
3.4.1
Member functions can be declared either inside/outside the class. If the member function
is declared inside the class it is said to be inline functions. When the function is declared
outside the class it should follow the syntax given below.
<return type> classname :: functionname(argument list)
{
//body of the function.
}
For example the function get_ab(),put_ab() of the number class can be written as.
void number :: get_ab()
{
cin>>a;
cin>>b;
}
void number :: put_ab()
{
cout<<a;
cout<<b;
}
3.4.2
Creating Objects
Once an object of a class has been created, the program can reference its public
Anna University Chennai
40
DCS 115
members by using the dot operator in much the same way that structure members are
accessed. The syntax for accessing the object is given below.
NOTES
<object name>.functionname(arguments);
The statement given below invokes the get_ab() and put_ab() member functions
of the number class.
ob1.get_ab();
ob1.put_ab();
Example 1:
The following code creates a class called number with member functions
get_ab(),add() and mul().
#include<iostream.h>
class number
{
private:
int a,b;
public:
void get_ab()
{
cout<<Enter values for a and b \n;
cin>>a;
cin>>b;
}
void add();
void mul();
};
void number :: add()
{
int c;
c=a+b;
cout<<THE SUM IS <<c;
}
void number :: mul()
{
int d;
d=a*b;
cout<<THE PRODUCT IS <<d;
}
41
DCS 115
NOTES
void main()
{
number ob1;
ob1.get_ab();
ob1.add();
ob1.mul();
}
42
DCS 115
}
void add()
{
int c;
c=a+b;
cout<<THE SUM IS <<c<<endl;
}
void mul()
{
int c;
c=a*b;
cout<<THE PRODUCT IS <<c;
}
NOTES
};
void main()
{
number ob1;
int d1,d2;
cout<<ENTER TWO DATA<<endl;
cin>>d1>>d2;
ob1.get_ab(d1,d2); // d1 value is copied to x and d2 value is copied to y
ob1.add();
ob1.mul();
}
Output of the Program
ENTER TWO DATA
10
20
THE SUM IS 30
THE PRODUCT IS 200
3.4.5 Inline Functions outside Classes.
A member function that is declared outside can be made inline just by prefixing it
with the keyword inline.
Example 3:
The following is an example for an inline function written outside the class.
#include<iostream.h>
class point
{
private:
int x,y;
43
DCS 115
NOTES
public:
void getpoints();
void putpoints();
};
inline void point :: getpoints()
{
cout<<Enter 2 points\n
cin>>x>>y;
}
inline void point :: putpoints()
{
cout<<The points are\n;
cout<<x<<\t<<y;
}
void main()
{
point p;
p.getpoints();
p.putpoints();
}
Output of the Program
Enter 2 points
10
20
The points are
11
20
Have you Understood Questions?
1.
2.
3.
3.5
Generally every object we create will require some sort of initialization. C++
allows a constructor function to be included in a class declaration. A classs
constructor is called each time an object of that class is created. Thus, any
initialization to be performed on an object can be done automatically by the
constructor function. A constructor function has the following characteristics.
44
DCS 115
arguments.
Constructers can take default arguments
Constructers can be dynamically initialized.
Constructer function cannot be made virtual
It should be always declared in the public section of the class.
NOTES
Example 4:
The following program makes use of a constructor.
#include <iostream.h >
class number
{
int a;
public:
number( ); //constructor
void show( );
};
number::number( )
{
cout << In constructor\n;
a=100;
}
void number::show( )
{
cout << a;
}
void main( )
{
number ob; // automatic call to constructor
ob.show( );
}
Output of the Program
In constructor
100
In this simple example the constructor is called when the object is created, and
the constructor initializes the private variable a to 100 .For a global object, its
constructor is called once, when the program first begins execution. For local
objects, the constructor is called each time the declaration statement is executed.
45
DCS 115
NOTES
void show( );
};
number::number(int x)
{
cout << In constructor\n;
a=x;
}
void number::show( )
{
cout <<Value of a is << a<<\n;
}
int main( )
{
number ob(4);
ob.show( );
return 0;
}
Output of the Program
In constructor
Value of a is 4
In this example the object ob is parameterized. The value 4, specified in the
parentheses following ob, is the argument that is passed to number( )s parameter
x that is used to initialise a. Actually, the syntax is shorthand for this longer form:
number ob = number(4);
Anna University Chennai
46
DCS 115
Although the previous example has used a constant value, you can pass an objects
constructor any valid expression, including variables.
3.5.2
NOTES
Constructer Overloading
Similar to the function overloading concept in C++, you can also overload
constructers. Constructer overloading helps us to keep multiple constructers in
the class, such that each constructer can perform different methods of initialization.
Here is an example for constructer overloading.
Example 6:
The following program illustrates the constructor overloading concept. The
constructor function number () is overloaded with two, one and no parameters
# include < iostream.h >
class number
{
int a,b;
public:
number()
{
cout<<Default constructer;
x=y=0;
}
number(int x);
number(int x,int y);
void show( );
};
number::number(int x)
{
cout << In one parameter constructor\n;
a=x;
b=0;
}
number::number(int x,int y)
{
cout << In two parameter constructor\n;
a=x;
b=y;
}
47
DCS 115
NOTES
void number::show( )
{
cout << a<<\n<<b;
}
int main( )
{
number ob(); //invokes default constructer
ob.show( );
number ob1(5); //invokes constructer with one parameter
ob1.show( );
number ob2(5,10); //invokes constructer with two parameters
ob2.show( );
return 0;
}
Output of the Program
Default constructer
0
0
In one parameter constructor
5
0
In two parameter constructor
5
10
3.5.3
Copy Constructers
Copy constructer is used to copy the value of one object to another. The copy
constructor takes a single argument of the same type as the class. It creates a new
object, which is an (exact) copy of the passed object. This is done by copying all
member variables from the passed object into the new object.
As mentioned earlier the purpose of copy constructer is to declare and initialize
an object from another object. An example for copy constructer is given below.
Example 7:
The following program makes use of copy constructors
# include < iostream.h >
class number
Anna University Chennai
48
DCS 115
NOTES
int a;
public:
number(int x); //constructor
number(number & x) //copy constructer
void show( );
};
number::number(int x)
{
cout << In constructor\n;
a=x;
}
number :: number(number& x)
{
cout<<Copy Constructor\n;
a=x.a
}
void number::show( )
{
cout <<Value of a is << a<<\n;
}
int main( )
{
number ob(4);
ob.show( );
//displays 4
number ob1(ob); //invokes copy constructer
ob1.show();
//displays 4
return 0;
}
Output of the Program
In constructor
Value of a is 4
Copy Constructor
Value of a is 4
Always the Copy constructer takes reference variable as a parameter. In this
example the copy constructer copies the value of the object ob to object ob1.
Have you Understood Questions?
1.
2.
What is a constructer?
Is it possible to overload constructer?
49
DCS 115
NOTES
3.
3.6
50
DCS 115
NOTES
number ob;
ob.show();
}
Output of the Program
In constructor
A is 100
In Destructor...
A classs destructor is called when an object is destroyed. Local objects are
destroyed when they go out of scope. Global objects are destroyed when the
program ends.
Have you Understood Questions?
1.
2.
What is a destructor?
Is it possible to overload destructor?
3.7
3.7.1
Objects can be passed to functions as arguments in just the same way that other
types of data are passed. Simply declare the functions parameter as a class type
and then use an object of that class as an argument when calling the function. As
with other types of data, by default all objects are passed by value to a function.
Example 9:
In the following program an object is passed as parameter to the member function
product.
class number
{
int i;
public:
number(int n) { i = n; }
int product(number o1,number o2);
};
int number :: product(number o1,number o2)
{
51
DCS 115
NOTES
int main( )
{
number a(5), b(2);
cout << a.product(a,b)<< \n; //OUTPUT 10
cout << b.product(a,b) << \n; //OUTPUT 10
return 0;
}
Output of the Program
10
10
The default method of passing of parameters in C++ is pass by value (including
objects).In this example the function product takes two objects as arguments and
return their product.
3.7.2
Functions can return objects. First, declare the function as returning a class type.
Second, return an object of that type using the normal return statement. Remember
that when an object is returned by a function, a temporary object is automatically
created which holds the return value. It is this object that is actually returned by
the function. After the value is returned, this object is destroyed.
Example 10:
The following program illustrates the concept of returning an object from a
function. This example add objects of the class money.
#include<iostream.h>
class money
{
int rs;
int ps;
money()
{
rs=0;
ps=0;
}
Anna University Chennai
52
DCS 115
money(int r,int p)
{
rs=r;
ps=p;
}
money add(money m1,money m2);
void display();
NOTES
}
money money :: add(money m1,money m2)
{
money temp;
temp.ps=m1.ps+m2.ps;
if(temp.ps>99)
{
temp.rs++;
temp.ps-=99
}
temp.rs+=m1.rs+m2.rs;
return temp;
}
void money :: display()
{
cout<<Total Rupees <<rs;
cout<<\n Total Paise <<ps;
}
void main()
{
money m1(10,55);
money m2(11,55);
money m3;
m3.add(m1,m2);
m3.display();
}
Output of the Program
Total Rupees 22
Total Paise 10
Have you Understood Questions?
1.
53
DCS 115
NOTES
3.8
Example 11:
The example given below will count the number of objects created for the class
one.
#include<iostream.h>
class one
{
private:
static int count;
public:
void incr()
{
count ++;
}
void display( )
{
cout <<count<< objects;
}
};
int one :: count ; //Static data member definition
void main()
{
one 01, 02, 03;
01. incr ();
02. incr ();
Anna University Chennai
54
DCS 115
NOTES
}
Output of the Program
3 objects
In this example a variable count is declared as a static data member. It will be
initialized to zero. Every time when the function incr( ) is called the variable is
incremented by one irrespective of the object.
3.8.1
Example 12:
The following program illustrates the concept of static member functions.
#include<iostream.h>
class one
{
private:
int a;
static int count;
public:
void set()
{
a=5;
count=5;
}
static void incr()
{
a++;
//ERROR a is non static variable
count++;
cout<<a;
55
DCS 115
cout<<count;
NOTES
}
int one :: count;
void main()
{
one obj1, obj2, obj3;
obj1.set ();
obj2.set ();
obj3.set ();
one::incr(); // calling a static function.
}
Note:
The program has some compilation errors hence it will not run
Have you Understood Questions?
1.
2.
3.
4.
3.9
Class member functions may be declared as const. When this is done, that method
cannot modify the object that invokes it. Also, a const function/method may not
invoke a non-const member function of the same object. However a const method
might call non-const methods of other classes or of other objects of the same
class as itself. Further, a const class can be called from either const or non-const
objects. To specify a member function as const, use the form shown in the following
example:
class ex1
{
private:
int x;
public:
int fun() const; // const member function
};
The purpose of declaring a member functions as const is to prevent it from
Anna University Chennai
56
DCS 115
NOTES
There will be time when you want a function to have access to the private members
of a class without that function actually being a member of that class.C++ supports
friend functions to achieve this purpose. A friend function is not a member of a
class but still has access to its private elements. Friend functions are useful with
operator overloading and the creation of certain types of I/O functions. Friend
Functions posses the following features.
The function that is declared as friend will not fall in the scope of the class
it was declared.
A friend declaration can be placed in either the private or the public part
of a class declaration
Like a member function, a friend function is explicitly declared in the
declaration of the class of which it is a friend
A friend function can access private data members of that class.
A friend function will be called without the object.
Usually friend function takes object as an argument.
public:
DCS 115
callme( );
NOTES
}
Example 13:
58
DCS 115
NOTES
};
class test2 //Definition of the class that has the forward declaration.
{
}
Example 14:
The following example creates two friendly classes.
DCS 115
NOTES
}
friend float avg(c1 01,c2 02);
};
class c2
{
private:
int y;
public:
c2()
{
cin>>y;
}
friend float avg(ci 01,c2 02);
};
60
DCS 115
NOTES
Summary
Class is an user defined data type in C++. Classes in C++ are also called
as Abstract Data Type (ADT) .Classes bind the data with its associated
code.
Member functions can be declared either inside/outside the class. If the
member function is declared inside the class it is said to be inline functions.
In C++ class variables are called as objects. Objects are run time entities
of an object oriented system.
A constructer is a special member function that has the same name as the
class. A classs constructor is called each time an object of that class is
created.
Constructers will not have return type but can take parameters, hence
constructers can be overloaded.
Copy constructer is used to copy the value of one object to another.
The complement of a constructor is the destructor. This function is called
when an object is destroyed.
A static member is part of a class, but not part of an object of a class, so
theres only one instance of them however many objects of that class are
created.
A static member function can access only static variables and they are
called using the class name.
Class member functions may be declared as const. When this is done, that
method cannot modify the object that invokes it.
A friend function is not a member of a class but still has access to its
private elements.
Forward declaration is a concept in which we declare a class before defining
it. Forward declaration intimates the compiler that the class declared is
defined in the later part of the program
Exercises
Short Questions
1.
2.
3.
4.
5.
6.
DCS 115
NOTES
7.
8.
9.
10.
11.
Long Questions
1.
2.
3.
4.
Explain how objects can be passed and returned from a function with
an example
Explain the concept of constructer overloaing
Explain the concept of Friend functions with example.
Explain briefly regarding static data members and static functions.
Programming Exercises
1.
2.
3.
4.
2.
3.
Class is another user defined data type in C++. Classes in C++ are also
called as Abstract Data Type (ADT) .Classes binds the data with its
associated code. Objects are run time entities of a class
Just by prefixing the keyword inline before the function prototype.
<class name> object;
Eg. number obj
Section 3.5
1.
Constructers are special member functions that have the same as the
class. They are called when we create an object for a class.
62
DCS 115
2.
Yes
3.
Copy constructer is used to copy the value of one object to another.
Section 3.6
NOTES
0
Just by prefixing with the keyword static before variable declaration
True.
c1::fn()
Section 3.9
1.
False
Section 3.10
1.
2.
3.
References
1.
2.
DCS 115
NOTES
3.
Author: E Balagurusamy
Publisher: Tata Mcgraw Hill 2000
Problem Solving with C++ (4th edition)
Author: Walter Savitch
Publisher: Addison Wesley 2002
4.
5.
64
DCS 115
NOTES
CHAPTER 4
OPERATOR OVERLOADING AND TYPE
CONVERSIONS
4.1
Operator Overloading
Type Conversions
Defining Operator Overloading
Implicit Type Conversion
Overloading Binary Operator
Explicit Type Conversion
Overloading Unary Operator
Basic to Class Type
Overloading Prefix and Postfix Increment/Decrement Operators
Class to Basic Type
Overloading new and delete Operators
One Class to another Class Type
Operator Overloading Using Friend Functions
Introduction
Learning Objectives
DCS 115
NOTES
4.3
4.3.1
66
DCS 115
4.3.2
NOTES
When a member operator function overloads a binary operator, the function will
have only one parameter. This parameter will receive the object that is on the
right side of the operator. The object on the left side is the object that generates
the call to the operator function and is passed implicitly by this pointer.
Example 1:
The following program overloads the + operator such that it adds two objects
of the type complex.
#include <iostream.h>
class complex
{
int real;
float imag;
public:
complex()
{
real=imag=0;
}
complex (int r,float i)
{
real = r; imag=i;
}
//overload + operator for complex class
complex operator +(complex);
void display()
{
cout<<The Result is ;
cout<<real << +j <<imag ;
}
};
complex complex :: operator + (complex c1)
{
complex temp;
temp.real=real +c1.real;
temp.imag=imag + c1.imag;
return temp;
}
67
DCS 115
NOTES
void main()
{
complex c1,c2,c3;
int a; float b;
cout<<ENTER REAL AND IMAG PART OF COMPLEX
NUMBER1<<endl;
cin>>a>>b;
c1=complex(a,b);
cout<<ENTER REAL AND IMAG PART OF COMPLEX
NUMBER2<<endl;
cin>>a>>b;
c2=complex(a,b);
//adds two complex objects invokes operator + (complex) function
c3=c1 + c2 ;
c3.display();
}
Output of the Program
ENTER REAL AND IMAG PART OF COMPLEX NUMBER1
5
7.1
ENTER REAL AND IMAG PART OF COMPLEX NUMBER2
3
8.3
The Result is 8 + j 15.3
Example 2:
The program given below is the modified version of the example 10 program in
Chapter3. The member function add() present in that program is replaced by the
operator overloading function.
#include<iostream.h>
class money
{
int rs;
int ps;
money()
{
rs=0;
ps=0;
}
money(int r,int p)
68
DCS 115
NOTES
rs=r;
ps=p;
}
money operator +(money);
void display();
}
money money :: operator +(money m1)
{
money temp;
temp.ps=m1.ps+ps;
if(temp.ps>99)
{
temp.rs++;
temp.ps-=99
}
temp.rs+=m1.rs+rs;
return temp;
}
void money :: display()
{
cout<<Total Rupees <<rs;
cout<<\n Total Paise <<ps;
}
void main()
{
money m1(10,55);
money m2(11,55);
money m3;
m3=m1+m2;
m3.display();
}
Output of the Program
Total Rupees 22
Total Paise 10
4.3.3
DCS 115
NOTES
operand, it is this operand that generates the call to the operator function. There is
no need for another parameter.
Example 3:
The following program overloads the unary operator that negates the object of
point class
#include <iostream.h>
class point
{
int x, y;
public:
point( )
{
x = 0; y = 0;
}
point(int i, int j)
{
x = i; y = j;
}
point operator-( );
void display()
{
cout<<x <<\t<<y;
}
};
// Overload - operator for point class
point point::operator-( )
{
x=-x;
y=-y;
}
int main( )
{
point o1(10, 10);
int x, y;
-o1; //Negate the object
o1.display();
}
Output of the Program
-10
-10
70
DCS 115
4.3.4
NOTES
When overloading the prefix ++ operator you write the member function as
void operator ++( )
Similarly when overloading the postfix ++ operator we will write the member
function as
void operator ++( )
Hence there is an ambiguity because both the member function takes the same
form the same problem exist for the pre and post fix decrement operators. To
resolve this you have to pass a dummy integer argument for the postfix operator.
void operator ++( );
void operator ( ) ;
void operator ++(int);
void operator ( int ) ;
Note:
The int parameter in the postfix operator is a dummy variable
Example 4:
The program given below overloads unary prefix ++ operator to increment the
object of type point class
#include <iostream.h>
class point
{
int x, y;
public:
point( )
{
x = 0; y = 0;
}
point(int i, int j)
{
x = i; y = j;
}
point operator++( );
void display()
71
DCS 115
NOTES
72
DCS 115
NOTES
Most large C++ programs make use of dynamically allocated memory. C++
supports dynamic allocation and deallocation of memory using new and delete
operators. Like other operators (except the few operators that cannot be overloaded)
C++ allows these two operators to be overloaded. By using the overloaded version
of new and delete operators there will be a simple and natural way to allocate and
dellocate an object from a memory pool and initialize it properly.
Example 6:
The following example demonstrates the overloading of new and delete operators.
#include<iostream.h>
#include<cstdlib.h>
class TestClass
73
DCS 115
NOTES
{
int x,y;
public:
TestClass()
{
x = y = 0;
}
TestClass(int a, int b)
{
x = a;
y = b;
}
void show()
{
cout << x << \t ;
cout << y << endl;
}
void *operator new(size_t size);
void operator delete(void *p);
};
// overloaded new operator
void *TestClass::operator new(size_t size)
{
void *p;
cout << In overloaded new.\n;
p = malloc(size);
if(!p)
{
cout<<Unable to allocate<<endl;
return;
}
return p;
}
// delete operator overloaded
void MyClass::operator delete(void *p)
{
74
DCS 115
NOTES
}
4.3.6
DCS 115
NOTES
}
int main( )
{
point o1(10, 10), o2(5, 3), o3;
o3 = o1 + o2; //add to objects
// this calls operator+( )
o3.display();
return 0;
}
Output of the Program
X IS : 15 ,Y IS : 13
Note that the left operand is passed to the first parameter and the right operand is
passed to the second parameter
Have you Understood Questions?
1.
2.
3.
4.
4.4
Definition
Type conversion or typecasting refers to changing an entity of one data type into
another. This is done to take advantage of certain features of type hierarchies. For
instance, values from a more limited set, such as integers, can be stored in a more
compact format and later converted to a different format enabling operations not
previously possible, such as division with several decimal places worth of accuracy.
Type conversion allows programs to treat objects of one type as one of their ancestor
types to simplify interacting with them.
4.4.1
76
DCS 115
Example
NOTES
int y;
float x=123.45;
y = x;
In this example the float variable x is automatically gets converted to int. Thus
the fractional part of y gets truncated.
4.4.2 Explicit Type Conversion
Automatic type conversion for user defined data types is not supported by the
compiler hence the conversion routines are ought to be specified explicitly. Three
types of situations might arise in the data conversion between incompatible types.
DCS 115
NOTES
}
The constructor used for type conversions take a single argument whose type is to
be converted.
Class to Basic Type
Overloaded casting operator is used to convert data from a class type to a basic
data type.
Syntax:
operator typename()
{
statements.....
}
This function converts a class type to specified type name. For example operator
int() converts the class object to integer data type.
Conditions for a casting operator function
It must be a class member.
It must not specify a return type.
It must not have any arguments.
Example 9:
The following example cast the object of type time to basic data types (int and
float)
class time
{
int min,sec;
public:
time(int n)
{
min = n/60;
sec=n%60;
}
Anna University Chennai
78
DCS 115
NOTES
};
void main()
{
time t1(160);
int n = t1;
//Conversion
float x = t1; //Conversion
}
One Class to another Class Type
The Constructors helped us to define the conversion from a basic data type to
class type and the overloaded casting operator helped to define the conversion
from a class type to basic data type. Now to convert from one class type to another
class type these both help us to do.
Example 10:
The following program converts the class type length1 to type length2
class length2; //forward declaration
class length1
{
int m,cm;
public:
length1(int n)
{
m=n/100;
cm=n%100;
}
operator length2() //from length1 type to length2 type
79
DCS 115
NOTES
80
DCS 115
When you overload a unary operator using a member function, the function
has no parameters.
To overload unary postfix operators a dummy integer is passed as a
parameter to the operator function
It is possible to overload an operator relative to a class by using a friend
rather than a member function
We cannot use a friend to overload the assignment operator.
Type conversion or typecasting refers to changing an entity of one data
type into another
Implicit type conversion is an automatic type conversion by the compiler.
The type conversions are automatic as long as the data types involved are
built-in types.
Explicit type conversion is necessary for user defined data types.
NOTES
Exercises
Short Questions
1.
2.
3.
4.
Long Questions
1. Explain how prefix and postfix operators are overloaded
2. How will you overload new and delete operators? Give example
3. Explain Explicit type conversion methods with example.
Programming Exercises
1. Write a program to overload binary operator + such that it is capable of
adding two objects of distance class .The distance is expressed as foot
and inches.
2. Write a program to overload ++ operator to increment time object. Time
is expressed in hour, minute and second.
Answers to Have you Understood Questions
Section 4.3
1. No
81
DCS 115
NOTES
2. return-type class-name::operator#(arg-list)
{
// operation to be performed
}
3. Unary operator Eg !. Binary operator Eg. +
4. =(assignment operator)
Section 4.4
1. Type conversion or typecasting refers to changing an entity of one data
type into another.
2. =(assignment operator)
References
1.
2.
3.
4.
5.
82
DCS 115
NOTES
CHAPTER 5
INHERITANCE
Overview Of Inheritance
Multiple Inheritance
Single Inheritance
Multilevel Inheritance
Access Control
Hierarchical Inheritance
Hybrid Inheritance
Parameterized Constructers in
Derived Classes
5.1
Introduction
This chapter explores one of the most powerful features of C++ language, the
inheritance. C++ strongly supports the concept of reusability with the help of
inheritance. Inheritance is one of the primary features of any object oriented
language. In this chapter you will go through the various forms of inheritance and
you will learn how to implement them in C++ programs further this chapter will
introduce you the access specifiers and you will learn how to apply them in your
programs.
5.2
Learning Objectives
83
DCS 115
NOTES
Single inheritance
Multiple inheritance
Multilevel inheritance
Hierarchical inheritance
Hybrid inheritance
Base Class
Derived class
Fig.5.1 Single Inheritance
The syntax for implementing inheritance is
class derivedclassname : access mode baseclassname
Anna University Chennai
84
DCS 115
NOTES
};
class derived : public base
{
};
In this example the class derived inherits the properties of the class base. The
inheritance is made in the public mode.
Example 1
The following code is a simple example for single inheritance. In this example
the derived class (number2) inherits the base class (number1) in public mode
#include<iostream.h>
class number1
{
int a;
public:
number1( )
{
a=0;
}
void get_a()
{
cout<<Enter the value for a \n
cin>>a;
}
void show_a()
{
85
DCS 115
NOTES
cout<<a is <<a;
}
};
class number2: public number1
{
private:
int b;
public:
number2( )
{
b=0;
}
void get_b()
{
cout<<Enter the value for b \n
cin>>b;
}
void show_b()
{
cout<<b is <<b;
}
};
void main ( )
{
number2 obj;
obj. get_a ( );
obj. get_b ( );
obj.show_a( );
obj.show_b( );
}
Output of the Program
Enter the value for a
10
Enter the value for b
20
a is 10
b is 20
Here the inheritance is made in the public visibility mode. In the main program
we create the object for derived class and access all public functions present in
the base class. The derived class number2 will have the following features.
86
DCS 115
NOTES
Public Functions
Private Variables
number2( ) //constructer
void get_b()
void show_b()
int b
Public Functions
Private Variables
void get_a()
void show_a( )
None.
Only objects of the same class can have access rights to a member function or
data member declared as private.
A data member or a method declared as public can be accessed by all classes and
their objects.
Data members, methods that are declared protected are accessible by that class
and the inherited subclasses
The program given below uses all C++ access specifiers
#include<iostream.h>
87
DCS 115
NOTES
class Base
{
private:
int privateInt ;
protected:
int protectedInt;
public:
int publicvar;
Base()
{
privateInt =10;
protectedInt=20;
publicvar=30;
}
void display()
{
cout<< privateInt;
cout<< protectedInt;
cout<< publicvar;
}
};
class Derived :public Base
{
public:
void change()
{
privetInt++ //Wrong! Private variables cannot be
accessed
protectedInt++; //OK
publicvar++; //OK
}
}
void main()
{
88
DCS 115
Derived obj;
obj. privetInt=50 ; //Wrong! Private variables cannot be accessed
obj. protectedInt=50; // Wrong! Protected variables cannot be accessed
obj.publicInt=50; //OK
NOTES
}
Note:
The program has some compilation errors hence it will not run.
5.5.1
The Table 5.1 lists the visibility and access rights in C++.
ACCESS RIGHTS FOR THE DIFFERENT SCOPES
CLASS\ACCESS
RIGHTS
same class
subclass
Other classes
yes
no
no
yes
yes
no
yes
yes
yes
DCS 115
NOTES
private to base class, i.e. nothing can access them. All protected members of the
base class stay protected, i.e. only the derived class (and further derived classes)
can access them.
3. class derived : public base
All public members of the base class are public in the derived class, i.e.anything
can access them. All private members of the base are private to the base class, i.e.
nothing can access them. All protected members of the base class stay protected,
i.e. only the derived class (and further derived classes) can access them
5.5.3
We know that when the access specifier is private public members of the base
become private members of the derived class, but these are still accessible by
member functions of the derived class.
NOTE: The program given below will not compile ,it has some errors
Example 2:
The program given below is an example for inheritance in private mode.
#include <iostream.h>
class base
{
int x;
public:
void setx(int n)
{
x = n;
}
void showx( )
{
cout << x << \n;
}
};
// Inherit base as private
class derived : private base
{
int y;
public:
void sety(int n)
{
Anna University Chennai
90
DCS 115
y = n;
}
void showy( )
{
cout << y << \n;
}
NOTES
};
int main( )
{
derived ob;
ob.setx(10); // ERROR now private to derived class
ob.sety(20); // access member of derived class - OK
ob.showx( ); // ERROR now private to derived class
ob.showy( ); // access member of derived class - OK
return 0;
}.
Note:
The program given in example 2 contains some errors as indicated in the
comments, hence the program will not run.
As the comments in this program illustrates, both showx( ) and setx() become
private to derived and are not accessible outside it. Note that showx( ) and setx( )
are still public within base, no matter how they are inherited by some derived
class. This means that an object of type base could access these functions anywhere.
5.5.4
As you know from the preceding section, a derived class does not have access to
the private members of the base class. However, there will be times when you
want to keep a member of a base class private but still allow a derived class
access to it. To accomplish this, C++ includes the protected access specifier. The
protected access specifier is equivalent to the private specifier with the sole
exception that protected members of a base class are accessible to members of
any class derived from that base. Outside the base or derived classes, protected
members are not accessible.
The protected access specifier can occur any where in the class declaration,
although typically it occurs after the (default) private members are declared and
before the public members. The full general form of a class declaration is shown
here:
91
DCS 115
NOTES
class class-name
{
// private members
protected: //optional
// protected members
public:
//public members
};
Example 3:
The following program illustrates a single inheritance concept with protected
variables
#include<iostream.h>
class base
{
protected:
int a; //private to base but accessible from derived
public:
void get_a ( )
{
cout<<Enter the Value for a \n;
cin>>a;
}
};
class derived : public base
{
int b;
public:
void get_b()
{
cout<<Enter the Value for b \n;
cin>>b;
}
void product()
{
int c;
c= a * b // variable a is protected member of class base
cout<<The Product is <<c;
}
};
void main()
92
DCS 115
NOTES
derived obj;
obj.get_a();
obj.get_b();
obj.product();
}
Output of the Program
Enter the Value for a
10
Enter the Value for b
20
The Product is 200
Have you Understood Questions?
1. If a base class is inherited in private mode, how its public members appears
for the derived class
2. If a base class is inherited in public mode, all the members of the class
appears as public members to the derived class (TRUE/FALSE)
3. What is the special access specifier used for inheritance?
4. List the access specifiers available in C++.
5.6 Multiple Inheritance
C++ allows a class to get derived from multiple base classes. A derived class
can directly inherit more than one base class. In this situation, two or more base
class is combined to create the derived class. Multiple inheritance is never
necessary (some object oriented languages, e.g. java, dont even support
multiple inheritance) and should be avoided. However, sometimes it makes
programming easier. The multiple inheritance diagram is depicted below.
93
DCS 115
NOTES
Here the class D inherits the properties of classes A, B and C. The syntax for creating
a derived class with multiple inheritance is
class derived classname : access mode base1, access mode base2,..access
mode base n
{
//body of the derived class
}
Example 4:
The following code contains the C++ classes for the multiple inheritance
diagram given in fig 5.3
EXPERIENCE
DETAILS
SALARY
DETAILS
PROMOTION
94
EDUCATION
DETAILS
DCS 115
protected:
NOTES
int salary;
public:
void salary( )
{
cout<<Enter your Salary<<endl;
cin >>salary;
}
};
class Edudet
{
protected:
char *degree;
public:
void eduqua( )
{
cout<<Enter your Degree<<endl;
cin>>degree;
}
};
class Promotion : public Expdet ,public Saldet, public Edudet
{
public:
void promote( )
{
if(tot_exp> 10 && sal>=20000 && (strcmp(degree,PG)= =0))
cout<< PROMOTED FOR HIGHER GRADE;
else
cout<<CANNOT BE PROMOTED ;
}
};
void main( )
{
Promotion obj;
obj . expr( );
obj . salary( );
obj . eduqua( );
obj . promote( );
}
95
DCS 115
NOTES
Multilevel Inheritance
PERSON
EMPLOYEE
MANAGER
Fig.5.4 Multilevel Inheritance
Thus this scheme can be extended to any level ( i.e generalization to
specialization).Let us write the program for multilevel inheritance
96
DCS 115
Example 5:
NOTES
The following code contains the C++ classes for the multilevel inheritance diagram
given in fig 5.4
#include<iostream.h>
#include<iomanip.h>
#include<string.h>
class person
{
protected:
int age;
char *name;
public:
void get1( )
};
class emp : public person
{
protected:
int basic,hra;
public:
void get2()
};
class manager : public emp
{
private:
int deptcode;
public:
void get3( );
void display( );
};
void person :: get1( )
{
cout<<Enter your Age<<endl;
cin >> age;
cout<<Enter your name<<endl;
cin>> name;
}
void emp :: get2( )
{
cout<<Enter your Basic and HRA<<endl;
cin>>basic>>hra;
}
97
DCS 115
NOTES
Class emp
Public Functions
Protected Variables
98
DCS 115
NOTES
Class manager
Public Functions
void get1() (From person class)
void get2() (From emp class)
void get3()
void display()
Protected variables
name, age (From person class)
basic,hra (From emp class)
deptcode(private variable)
Hierarchical Inheritance
The hierarchical inheritance structure is given below .This type is helpful when
we have class hierarchies. In this scheme the base class will include all the features
that are common to the subclasses.
DCS 115
NOTES
protected:
int x, y;
public:
void get ( )
{
cout<<Enter two values<<endl;
cin>> x>>y;
}
};
class B : public A
{
private:
int m;
public:
void add( )
{
m= x + y;
cout<<The Sum is <<m;
}
};
class C : public A
{
private:
int n;
public:
void mul( )
{
n= x * y;
cout << The Product is <<n;
}
};
class D : public A
{
private:
float l;
public:
void division( )
{
l = x / y;
cout <<The Quotient is << l;
}
Anna University Chennai
100
DCS 115
NOTES
};
void main( )
{
B obj1;
C obj2;
D obj3;
B .get( );
B .add( );
C .get( );
C .mul( );
D .get( );
D .division( );
}
5.9
101
DCS 115
NOTES
Emp_det
Normal pay
Additional pay
Net pay
102
DCS 115
}
void disp_bpay()
{
cout<< BASIC PAY IS = <<bpay<<endl;
}
NOTES
};
class add_pay
{
protected:
int hrs;
int rp;
int ap;
public:
void get_addpay()
{
cout<<ENTER OVERTIME HOURS<<endl;
cin>>hrs;
co ut<<ENTER HOW MUCH RUPEES PER
HOUR<<endl;
cin>>rp
}
void disp_addpay()
{
ap=hrs * rp;
cout<<TOTAL OVERTIME HOURS<<hrs<<endl;
cout<<ADDITIONAL PAY = << ap <<endl;
}
};
class net_pay :public norm_pay,public add_pay
{
int netpay;
public:
void display()
{
netpay=ap+bpay;
cout<<NET PAY IS <<netpay;
}
};
void main()
{
net_pay obj;
obj.get_id();
obj.get_bpay();
103
DCS 115
obj.get_addpay();
NOTES
obj.disp_id();
obj.disp_bpay();
obj.disp_addpay();
obj.display();
}
Output of the Program
ENTER EMPID
1101
ENTER BASIC PAY
10000
ENTER OVERTIME HOURS
10
ENTER HOW MUCH RUPEES PER HOUR
50
EMPID IS 1101
BASIC PAY IS = 10000
TOTAL OVERTIME HOURS 10
ADDITIONAL PAY = 500
NET PAY IS 10500
Have you Understood Questions?
1. Hybrid inheritance scheme is the combination of
(a) Multiple (b) Multilevel (c) both a and b
5.10
It is possible for the base class, the derived class, or both to have constructor and/
or destructor functions. When a base class and a derived class both have constructor
and destructor functions, the constructor functions are executed in order of
derivation. The destructor functions are executed in reverse order. That is, the
base constructor is executed before the constructor in the derived class. The reverse
is true for destructor functions: the destructor in the derived class is executed
before the base class destructor.
Example 8:
This example illustrates the order in which the constructors and destructors get
executed in an inheritance program
104
DCS 115
class A
{
public:
A( )
{
NOTES
cout<<INSIDE A;
}
~A ( )
{
cout<<EXIT A;
}
};
class B : public A
{
public:
B()
{
cout<<INSIDE B;
}
~B()
{
cout<<EXIT B;
}
};
class C : public B
{
public:
C( )
{
cout<<INSIDE C;
}
~ C( )
{
cout<<EXIT C;
}
};
void main()
{
C obj;
}
105
DCS 115
NOTES
106
DCS 115
};
class B
{
int b;
public:
B(int y) : b(y)
{
cout<<INSIDE B;
cout<< b is <<b<<endl;
NOTES
}
~B()
{
cout<<EXIT B;
}
};
class C : public A,public B
{
int m,n
public:
C(int p,int q,int r,int s ) :A(p),B(q*2),m(r),n(s)
{
cout<<INSIDE C;
cout<< m is <<m<< n is <<n<<endl;
}
~ C( )
{
cout<<EXIT C;
}
};
void main()
{
C obj(10,20,30,40);
}
Output of the Program
INSIDE A
a is 10
INSIDE B
B is 40
INSIDE C
m is 30 n is 40
107
DCS 115
NOTES
EXIT C
EXIT B
EXIT A
In this program the object for the class C is created, in the constructer of class C
we have initialized the values for the member variables m and n using the statements
m(r) and n(s) which is given in the initialization section of the constructer C.
Similarly we have also initialized the values of the base class constructers. The
statement A(p) will initialize the value of a in the base class A and the statement
B(q*2) will initialize the value of b to q multiplied by 2 in the base class B.
Have you Understood Questions?
1.
2.
Summary
Inheritance is a feature by which new classes are derived from the existing
classes.
The parent class(Original existing class) is said to be the base class the
new made class from it is called a derived class
When a class is derived from a single base class it is said to be single
inheritance. It can be thought of as a specialization of an existing class.
A derived class can directly inherit more than one base class this concept
is said o be multiple inheritance
Multilevel inheritance is one form of multiple inheritance. In this scheme
the derived class is made from two or more base class
When the properties of one class are inherited by two or more classes then
that inheritance scheme is said to be hierarchical inheritance.
Hybrid inheritance scheme is the combination many simple inheritance
schemes.
A derived class can inherit a base class in public or protected or private
mode.
The protected access specifier is equivalent to the private specifier with
the sole exception that protected members of a base class are accessible to
members of any class derived from that base.
It is possible for the base class, the derived class, or both to have constructor
and/or destructor functions.
When a base class and a derived class both have constructor and destructor
functions, the constructor functions are executed in order of derivation.
The destructor functions are executed in reverse order.
108
DCS 115
Exercises
Short Questions
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
NOTES
Long Questions
1.
2.
3.
4.
Programming Exercises
1.
Create a base class called vehicle and add relevant data members and
functions to it. Create derived classes that directly inherit the base class
called two wheeler and four wheeler add relevant data members and
functions to them. Write a main program and create objects for the
derived class and access the member functions
2.
AUTHOR DETAILS
PUBLISHER DETAILS
109
DCS 115
NOTES
3.
Device
Input device
Output device
4.
5.
Two Wheeler
Four Wheeler
Cars
Trucks
1.
2.
Section 5.4
1.
Base Class
Derived class
Anna University Chennai
110
DCS 115
NOTES
private
FALSE
Protected
private, protected and public
Section 5.6
1.
2.
If a derived class directly inherits from more than one base class.then
this scheme of inheritance is said to be multiple inheritance.
C++,Java
Section 5.7
1.
TRUE
Section 5.8
1.
Hierarchy
Section 5.9
1.
C
Section 5.10
1.
The constructor functions are executed in order of derivation.
2.
The destructors are executed from derived to base.
111
DCS 115
NOTES
References
1.
2.
3.
4.
5.
6.
Thinking in C++
Author: Bruce Eckel
Publisher : Prentice Hall 2000
112
DCS 115
NOTES
CHAPTER 6
POLYMORPHISM
6.1
Binding
Virtual Functions
Virtual Destructors
Introduction
Learning Objectives
6.3
DCS 115
NOTES
at compile time exactly, which code is associated with an object. This is called
static binding or early binding.
However, sometimes the compiler cannot know at compile time, which function
is meant. In this case, the binding has to happen at run time. This is called dynamic
binding or late binding.
Early binding achieves compile time polymorphism and late biding achieves run
time polymorphism.
In C++ dynamic binding can be achieved by creating object pointers to the base
class. When you create object pointers to base class we get the following advantages
Pointers to base classes can be assigned addresses of derived classes. When such
a pointer is used to access member methods, the compiler does not know, which
method to call. It can be either the function from the base class or potentially an
overloaded function in the derived class.
Example 1:
The following program creates a object pointer to the base class and access
functions of both base and derived class.
#include<iostream.h>
class base
{
public:
void display()
{
cout<<I AM IN BASE;
}
};
class derived : public base
{
public:
void display()
{
cout<<I AM IN DERIVED;
}
Anna University Chennai
114
DCS 115
};
void main()
{
base b,*ptr;
derived d;
//To call display function in class base
ptr= &b;
ptr->display();
//To call display function in class derived
ptr=&d;
ptr->display(); //This will invoke the display function of base not derived
}
NOTES
Virtual Functions.
A virtual function is simply declared by putting the keyword virtual before the
function declaration. Overloading virtual functions is called as overriding. The
argument list and return-type of the function in derived classes must be the same
as in the base class otherwise it is only overloaded, not overridden.
Any pointer to a class that contains virtual functions is provided with additional
information about what it points to. When a virtual function is called through
such a pointer, then the pointer knows what object it points to. This is dynamic
binding.
Example 2:
The following program is the modified version of example 1, here the function
display() is declared as virtual.
#include<iostream.h>
class base
{
public:
virtual void display()
{
115
DCS 115
cout<<I AM IN BASE;
NOTES
}
};
class derived : public base
{
public:
void display()
{
cout<<I AM IN DERIVED;
}
};
void main()
{
base b,*ptr;
derived d;
ptr= &b; //To call display function in class base
ptr->display();//To call display function in class derived
ptr=&d;
ptr->display(); //This will invoke the display function of derived
}
Output of the Program
I AM IN BASE
I AM IN DERIVED
A function declared virtual in base class is always virtual. The keyword virtual is
not required in the derived class. Some important points about virtual functions:
Overridden virtual functions must have the same argument list and return
type.
The different behavior of a virtual function and a non-virtual function
occurs only, if the object is accessed through a pointer with type of a base
class.
Even if the virtual function is overridden, the derived class has still access
to the virtual function. It can call it by using the scope-operator (::).
The prototype of the virtual function in the base class and the derived
class must be the same.
A virtual function must be a member function of the class. It should not
be a friend function.
Virtual functions cannot be made static.
Constructors cannot be made virtual; however destructors can be made
virtual.
116
DCS 115
NOTES
Virtual Destructors
Constructers and destructors are not inherited. Constructors always create one
particular type and hence it makes no sense to inherit them. Therefore they cannot
be made virtual. Destructors are used when an object is deleted. If the derived
class allocates some resources that outside the base class methods, it needs its
own destructor. However, as explained before, a pointer to a base class can be
used to point to a derived class. To ensure that the correct destructor is called, the
destructor should be virtual otherwise it might happen that some resource is not
deallocated. For this reason, destructors should always be declared virtual.
Have you Understood Questions?
1. Constrcuters are inherited(TRUE /FALSE)
2. Destructors are not inherited (TRUE/FALSE)
6.5
Suppose you have two derived classes B and C that have a common base class A,
and you also have another class D that inherits from B and C. You can declare the
base class A as virtual to ensure that B and C share the same sub object of A.
In the following example, an object of class D has two distinct sub objects of
class A, one through class B1 and another through class B2. You can use the
keyword virtual in front of the base class specifies in the base lists of classes B1
and B2 to indicate that only one sub object of type A, shared by class B1 and class
B2, exists.
117
DCS 115
NOTES
A
B2
B1
D
Fig. 6.1 Virtual Base Classes
The C++ classes for the fig 6.1 were
class A
{
};
class B1 :virtual public A
{
};
class B2: virtual public A
{
};
class D:public B1,public B2
{
}
NOTE:
The keywords virtual and public can be used in either order. For Example virtual
public A is equivalent to public virtual A
118
DCS 115
NOTES
119
DCS 115
NOTES
class shape
{
public:
virtual void area()=0;
};
Once the abstract class is created the class inheriting it should override all the
pure virtual functions. For example
class square :public shape
{
public:
void area()
{
cin>>side;
int s=2 * side;
cout<<AREA IS <<s;
}
};
Have you Understood Questions?
1.
Summary
120
DCS 115
Exercises
Short Questions
1.
Differentiate early and late binding concepts
2.
The binding that is associated with function overloading is
_____________________
3.
What is the purpose of function look up table ?
4.
Write short notes on Virtual destructors
5.
Why we need pure virtual functions? How it is declared?
6.
Overloading of virtual functions is called as ________________
Long Questions
1.
Explain virtual functions with a example. Write the rules associated
with virtual functions.
2.
Write a not on Virtual Destructors
3.
Explain Abstract classes and its features with example
Programming Exercises
1. Implement the inheritance scheme given below with a C++ program
NOTES
Device
Output device
Input device
Input/Output device
1.
Create a virtual base class called shape with a virtual function area ().
Create derived classes rect, square and circle and override the function
area() and compute the area of the objects.
121
DCS 115
NOTES
Section 6.4
1.
False
2.
True
Section 6.5
1.
2.
If we declare the base class as virtual to ensure that all the sub classes
share the same object of the base class
They can appear in either order.
Section 6.6
1.
By equating the function prototype to zero.
Section 6.7
1.
TRUE.
References
1.
2.
3.
4.
5.
6.
Thinking in C++
Author: Bruce Eckel
Publisher : Prentice Hall 2000
122
DCS 115
NOTES
CHAPTER 7
FILES
7.1
Binary
File I/O
Binary
Sequential Input And Output
Operations
Random Access Files
Introduction
We all know C++ I/O operates on streams hence it is very important to know
about streams supported by C++. Regarding streams this chapter starts the
discussions from knowing the hierarchy of C++ I/O classes. You will be learning
handling sequential files, random access files and binary files in detail. This chapter
introduces you to write programs in C++ to handle the above mentioned files.
Finally the chapter also discusses the error handling mechanisms supported by
c++ when working with files.
7.2
Learning Objectives
7.3
DCS 115
NOTES
There are two types of streams: text and binary. A text stream is used with
characters. When a text stream is being used, some character translations may
take place (e.g. newline to carriage-return/linefeed combination). A binary stream
uses binary format for representing data in the memory. A binary stream can be
used with any type of data. No character translation will occur. Thus always the
binary file contains exact data sent by the stream.
C++ contains several predefined streams that are automatically opened. These
are cin, cout, cerr and clog. By default, cin is linked to the keyboard, while the
others are linked to the screen. The difference between cout, cerr and clog is, that
cout is used for normal output, cerr and clog are used for error messages.
The I/O system of C++ has many classes and file handling functions. All these
classes are derived from the base class ios.The hierarchy of C++ I/O classes are
given below.
IOS
ISTREAM
STREAMBUF
OSTREAM
IOSTREAM
IFSTREAM
FSTREAM
OFSTREAM
124
DCS 115
have access to all operations defined by ios. In C++, a file is opened by linking it
to a stream. There are three types of streams: input, output and input/output. Before
you can open a file, you must first obtain a stream.
NOTES
Examples
ofstream out(emp.dat); //Opens emp.dat file in output mode
ifstream in(emp.dat); //Opens emp.dat file in input mode
fstream fin(emp.dat); //Opens emp.dat file in input/output mode
The prototype of each member function is given below.
Here filename is the name of the file to be processed, the filename also includes
the path specifier. The value of the mode specifies how the file has to be
opened.C++ supports the following file opening modes
ios::app
ios::ate
ios::binary
ios::in
ios::out
ios::trunk
Note that the file opening modes can be combined using | symbol. For example
ofstream out(emp.dat ,ios::out | ios::trunk)
ios::app: causes all output to that file to be appended to the end. Only
with files capable of output.
ios::ate: causes a seek to the end of the file to occur when the file is
opened.
ios::out: specify that the file is capable of output.
ios::in: specify that the file is capable of input.
ios::binary: causes the file to be opened in binary mode. By default, all
files are opened in text mode. In text mode, various character translations
might take place, such as carriage return/linefeed sequences being
125
DCS 115
NOTES
Once the file is opened we can read from or write into the file based on the mode you
have opened. After processing the file it has to be closed. To close a file we have to use
the member function called close, for example
in.close() //this will close file pointed by the stream in.
The close function will not take any parameters and will not return any value.
Example 1:
The following program writes name and rollno into a file called student.
#include<iostream.h>
#include<fstream.h>
int main()
{
ofstream out(Student); //open the file student in output mode
char name[30];
int rollno;
cout<<ENTER YOUR NAME<<endl;
cin>>name;
cout<<ENTER YOUR ROLL NO<<endl;
cin>>rollno;
out<<name <<\t ; // write name to the file student
out<<rollno;
// write rollno to the file student
out.close();
}
Output of the Program
ENTER YOUR NAME
AHAMED
ENTER YOUR ROLL NO
1101
126
DCS 115
To view the outputs from file go to command prompt and type the command given
below.
c:\tc\bin>type student (press enter key)
AHAMED
NOTES
1101
In this example we have opened the file student in output mode. Since the
openmode parameter to open( ) defaults to a value appropriate to the type of
stream being opened, there is no need to specify its value in the preceding example.
Example 2:
The following example reads the content of the file student.
#include<iostream.h>
#include<fstream.h>
int main()
{
ifstream in(Student); //open the file student in input mode
char name[30];
int rollno;
in>>name; // read name from the file student
in>>rollno; // read rollno from the file student
cout<<NAME IS <<name<<endl;
cout<<ROLL NO IS <<rollno ;
in.close();
}
Output of the Program
NAME IS AHAMED
ROLL NO 1101
In the preceding examples we are working with one file at a time. Now lets learn now
let us learn how to work with multiple files.
Example 3:
This example works with more than one file.
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
int main()
127
DCS 115
NOTES
{
ofstream out;
out.open(book);
out<<C++;
out<<JAVA;
out.close();
out.open(author);
out<<H.SCHILDT;
out<<BALAGURUSAMY;
out.close();
out.open(publisher);
out<<OSBORNE;
out<<TATA MCGRAW;
out.close();
ifstream in;
char disp[100]; //create a buffer to store the data read from the file
in.open(book);
cout<<BOOK DETAILS <<endl;
while(in) //iterate till end of file
{
getline(in,disp); //read a line from the file and put in the buffer
cout<<disp;
}
in.close();
cout<<AUTHOR DETAILS<<endl;
in.open(author);
while(in) //iterate till end of file
{
getline(in,disp); //read a line from the file and put in the buffer
cout<<disp;
}
in.close();
cout<<PUBLISHER DETAILS<<endl;
in.open(publisher);
while(in) //iterate till end of file
{
getline(in,disp); //read a line from the file and put in the buffer
128
DCS 115
cout<<disp;
}
in.close();
NOTES
return 0;
}
Output of the Program
BOOK DETAILS
C++ JAVA
AUTHOR DETAILS
H.SCHILDT BALAGURUSAMY
PUBLISHER DETAILS
OSBORNE TATA MCGRAW
Here three files book, author, publisher are opened in output mode and the contents
are written and then same files are opened in input mode, the contents are read
from the file and displayed.
In this example we have used the getline function, which is used to read a line
from the file pointed by the stream and store in a buffer .The second parameter in
the getline function indicates buffer name.
Have you Understood Questions?
1. List some classes available in fstream header file?
2. if we want have a input and output operations on a file which type of
object we create?
3. Write any two file opening modes?
7.5 Sequential Input And Output Operations
Sequential input and output operations are performed on sequential files. A
sequential file is one in which every record is accessed serially, in the order in
which they are written hence to process any ith record all the previous i-1 records
has to be processed.
In C++ every sequential file (including Random access file) will be associated
with two file pointers. They are
129
DCS 115
NOTES
get() pointer
put() pointer
The get pointer is an input pointer; it is used to read the content of the file. The get
pointer will point content of the file to be read. When the file is opened in input
mode the get pointer will point the first location of the file.
The put pointer is an output pointer; it is used to write content to the file. The put
pointer will point to location where the content has to be written. When the file is
opened in output mode the put pointer will point the first location of the file.
However when the file is opened in append mode (ios::app) the put pointer will
point the last location of the file.
Example 4:
This example program uses put pointer to write content to the sequential file.
#include<iostream.h>
#include<fstream.h>
int main()
{
fstream out(test,ios::out); //opens test file in output mode
cout<<ENTER A STRING AT END PRESS #<<endl;
do
{
cin.get(ch);
out.put(ch); //write a character to the file
} while (ch! =#)
out.close();
}
Output of the Program
ENTER A STRING AT END PRESS#
ANNA UNIVERSITY#
c:\tc\bin>type test
ANNA UNIVERSITY#
Example 5:
This is an example program that uses get pointer to read content from the sequential
file.
130
DCS 115
#include<iostream.h>
#include<fstream.h>
int main()
{
fstream in (test,ios::in); //opens test file in input mode
char ch;
cout<<READING CONTENT FROM THE FILE.<<endl;
while (in)
{
in.get(ch); //get a character to the file
cout<<ch;
}
in.close();
}
NOTES
seekg()
seekp()
tellg()
tellp()
The tell pointer is use to give the current position of the file. The functions
tellg() and tellp() have the following prototype
position tellg()
position tellp()
Here position is the integer value that is capable of holding the largest value that
defines the file position.
131
DCS 115
NOTES
ios::beg
ios::cur
ios::end
in.seekg(0,ios::beg)
in.seekg(0,ios::end)
in.seekg(10,ios::cur)
in.seekg(-k,ios::end)
out.seekp(k,ios::beg)
out.seekp(-k,ios:;end)
Example 6:
The following program opens a random access file in input and output mode and it will
allow accessing the specified character in the file.
132
DCS 115
#include<iostream.h>
#include<fstream.h>
int main()
{
fstream in(test,ios::in | ios :: out); //opens test file in input/output mode
char ch;
int pos;
cout<<ENTER A STRING AT END PRESS #<<endl;
do
{
cin.get(ch);
in.put(ch); //write a character to the file
} while (ch! =#);
in.seekg(0) ; // Goto the beginning of the file;
cout<<READING CONTENT FROM THE FILE<<endl;
while (in)
{
out.get(ch); //get a character to the file
cout<<ch;
}
cout<<ENTER THE POSITION OF THE FILE TO READ;
cin>>pos;
in.seekg(pos,ios::beg); //MOVES THE GET POINTER TO THE
POSITION
while (in)
{
out.get(ch); //get a character to the file
cout<<ch;
}
in.close();
}
NOTES
DCS 115
NOTES
134
DCS 115
#include<iostream.h>
#include<fstream.h>
int main()
{
ifstream in;
in.open(number,ios::binary); //opens a binary file
int k;
in.read((char *) &k,sizeof(k));
cout<<k;
out.close();
return 0;
}
NOTES
We can write a object to a binary file as we do with the primitive data type like
int, float etc. Similarly we can also read an object from the binary file. We will
still use the read() and write() functions to perform read and write operations. The
program given below illustrates reading and writing an object from the binary
file.
Example 9:
#include<iostream.h>
#include<fstream.h>
class book
{
char bname[40];
float cost;
char aname[40];
int pubid;
public:
void getdetails();
void printdetails();
};
void book :: getdetails()
{
cout<<ENTER BOOK NAME<<endl;
cin>>bname;
cout<<ENTER AUTHOR NAME<<endl;
135
DCS 115
cin>>aname
cout<<ENTER COST OF THE BOOK<<endl;
cin>>cost;
cout<<ENTER PUBLISHER ID<<endl;
cin>>pubid;
NOTES
}
void book :: printdetails()
{
cout<<BOOK NAME IS <<bname<<endl;
cout<<AUTHOR NAME IS<<aname<<endl;
cout<<COST OF THE BOOK IS <<cost<<endl;
cout<<PUBLISHER ID IS <<pubid<<endl;
}
int main()
{
fstream fin;
fin.open(book,ios::in||ios::out);
int i;
book ptr[2];
for(i=0;i<2;i++)
{
ptr[i].getdetails();
fin.write((char *) &ptr[i],sizeof(ptr[i]));
}
fin.seekg(0);
cout<<PRINTING BOOK DETAILS<<endl;
for(i=0;i<2;i++)
{
fin.read((char *) &ptr[i],sizeof(ptr[i]));
ptr[i].printdetails();
}
fin.close();
return 0;
}
Output of the Program
ENTER BOOK NAME
C++
ENTER AUTHOR NAME
Balagurusamy
ENTER COST OF THE BOOK
Anna University Chennai
136
DCS 115
200
ENTER PUBLISHER ID
101
ENTER BOOK NAME
JAVA
ENTER AUTHOR NAME
H.SCHILDT
ENTER COST OF THE BOOK
400
ENTER PUBLISHER ID
102
NOTES
When we are working with files a number of errors may occur. The most common
errors that may occur while working with files are listed below
Attempting to perform read or write operation on a file that does not exist.
Attempting to process the file even after the last byte file of the file is
reached.
Attempting to write information to a file when opened in read mode.
Attempting to store information in file, when there is no disk space for storing
more data.
Attempting to create a new file with a file name that already exits.
137
DCS 115
NOTES
To overcome from these errors The C++ I/O system maintains status information about
the outcome of each I/O operation. The current I/O status of an I/O stream is described
in an object of type iostate, which is an enumeration data type defined by ios that
includes the members listed in the Table 7.2:
Table 7.2 Error bits in iostate
ERROR FLAG NAME
goodbit
failbit
eofbit
MEANING
No errors occurred
A non fatal I/O error has occurred
End of file has been encountered
There are two ways in which you can obtain the I/O status information. First, we call
the rdstate( ) function, which is a member of ios. It has this prototype:
iostate rdstate( );
It returns the current status of the error flags. rdstate( ) returns goodbit when no error
has occurred. Otherwise, an error flag is returned. The other way you can determine
whether an error has occurred is by using one of these ios member functions:
bool bad( );
bool eof( );
bool fail( );
bool good( );
The eof( ) function returns true if end of file is reached. The bad( ) function returns true
if badbit is set. The fail( ) function returns true if failbit is set. The good( ) function
returns true if there are no errors. Otherwise, they return false.
We can use all these functions in our file-handling program to minimize the errors. The
Example 10 illustrates the usage error bits in file handling.
Example 10:
This program given below contains all error handling mechanisms.
#include<iostream.h>
int main()
{
ifstream in;
in.open(text);
138
DCS 115
char ch;
if(!in)
{
cout<<CANNOT OPEN FILE<<endl;
return 0;
}
if(in.bad())
{
cout<<FATAL ERROR IN FILE<<endl;
}
cout<<READING CONTENT FROM THE FILE<<endl;
NOTES
while (in)
{
in.get(ch); //get a character to the file
cout<<ch;
}
in.close();
}
This program initially checks whether the file pointed by the stream in exits, if so
it will check whether there is any fatal error by using the faction bad().If there is
no error the entire content of the file is read and displayed.
Have you Understood Questions?
1.
2.
Summary
DCS 115
NOTES
Random access file is one that allows accessing records randomly in any order
The tell function is use to give the current position of the file.
The seek function is used to move the file pointer to the specified position.
The read and write functions are used perform I/O operations in a binary
file.
The C++ I/O system maintains status information about the outcome of
each I/O operation.
The eof( ) function returns true if end of file is reached.
The bad( ) function returns true if badbit is set.
The fail( ) function returns true if failbit is set.
The good( ) function returns true if there are no errors.
Exercises
Short Questions
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
Long Questions
1.
Explain random access files also explain how the file pointer is
manipulated
2.
Write short notes on reading and writing objects in binary files.
3.
Explain in detail about error handling functions in files
4.
Write short motes on sequential file organization
Programming Exercises
1.
2.
140
DCS 115
3.
4.
Create a class called sales with your own data members and functions.
Create object for the class and write the object to the binary file called
sales.dat.
Modify program 1 by including all error handling facilities.
NOTES
141
DCS 115
NOTES
References
1.
2.
3.
4.
5.
6.
Thinking in C++
Author: Bruce Eckel
Publisher : Prentice Hall 2000
142
DCS 115
NOTES
CHAPTER 8
TEMPLATES
Function Templates
Class Templates
Function Templates with Multiple Parameters
Class Templates with Multiple Parameters
C++ Function Templates Overloading
Member Function Templates
8.1 Introduction
Generic programming is an approach where generic types are used as parameters.
Generic data types are those that can act like a place holders for other data types.
In C++ generic programming is done with the help of templates. Template is one
of the important features available in C++. Using templates it is possible to create
generic classes and generic functions hence templates provides support for generic
programming.
C++ templates are those that can handle different data types without separate
code for each of them. In generic functions or generic classes, the type of data
that is operated upon is specified as a parameter. This allows us to use one function
or class with several different types of data without having to explicitly recode a
specific version for each type of data type. Thus, templates allow you to create
reusable code.
8.2 Learning Objectives
DCS 115
NOTES
144
DCS 115
int main()
{
int a=10,b=20;
add(a,b);
float c=12.5,d=13.8;
add(c,d);
}
NOTES
In this example the keyword template is used to create template function add().
Here the variable T is used as a placeholder name for the data type .The function
add() performs the addition of two numbers. In the main program the function
add is called with two different set of data types i.e. int and float. Since add() is a
template function the complier creates two version of add() function one to perform
addition of integers and another to perform addition of two floats.
Example 2:
This example of function templates takes input parameters and return values.
//FUNCTION TEMPLATES WITH RETURN VALUES
#include <iostream.h>
template <class T>
T small(T &a,T &b)
{
if(a>b)
return b;
else
return a;
}
int main()
{
int a,b;
cout<<ENTER TWO INTEGERS<<endl;
cin>>a>>b;
cout<<SMALLEST INTEGER IS <<small(a,b);
double m,n;
cout<<ENTER TWO REAL NUMBERS<<endl;
cin>>m>>n;
cout<<SMALLEST REAL NUMBER IS <<small(m,n);
return 0;
}
145
DCS 115
NOTES
8.3.1
A template function can take multiple parameters that may vary in their data
types. The list of parameters that are passed to the template function are separated
using commas. The general form of the template function with multiple parameters
is given below.
template <class T1,class T2,.>
returntype functionname(parameter list of types T1,T2)
{
// body of function
}
Example 3:
The following code snippet gives details regarding the function template with
multiple parameters.
//FUNCTION TEMPLATES WITH MULTIPLE PARAMETERS
#include<iostream.h>
template <class T1,class T2>
void power(T1 &a,T2 &b)
{
T1 p=1;
int i;
for(i=1;i<=b;i++)
{
p=p*a;
}
cout<<a<< RAISED TO THE POWER <<b<< IS = <<p<<\n;
}
void main()
{
power(3.5,5)
power(5,5);
}
In this example the generic function power() raise a base a to the power b.
Here we can note that this function takes two parameters. In the main program
the first line power (3.5.5) will raise the float value 3.5 to the integral power 5 i.e.
it computes 3.55. The second line power(5,5)will raise the integer value 5 to the
Anna University Chennai
146
DCS 115
power 5 i.e. it computes 55.Thus we can see that it is possible to have a template
function with multiple parameters.
NOTES
Example 4:
This example creates a generic function with multiple parameters that performs
recursive binary search on a linear array.
//Generic functions to perform Binary Search
#include<iostream.h>
template <class T1,class T2>
bsearch( T1 &a[], T2 &e, int start, int end)
{
int mid;
if(start>end)
return -1;
mid=(start+end)/2;
if(e==a[mid])
return mid;
else if(e<a[mid])
return bsearch(a,e,start,mid-1);
else
return bsearch(a,e,mid+1,end);
}
void main()
{
int n,pos;
int a[100],element;
cout<<Enter the array limit\n;
cin>>n;
cout<<Enter the array elements;
for(i=0;i<n;i++)
cin>>a[i];
cout<<Enter the element to be searched
cin>>element;
pos=bsearch(a,element,0,n);
if(pos==-1)
cout<<Element not found;
else
cout<<Element is found in position<<pos+1;
}
147
DCS 115
NOTES
8.3.2
You can overload a template function as you do with the normal C++ function. If
you call the name of an overloaded function template, the compiler will try to
deduce its template arguments and check its explicitly declared template
arguments. If successful, it will instantiate a function template specialization.
Errors will be generated if no match is found.
Example 5:
This example performs function templates overloading.
//TEMPLATE FUNCTION OVERLOADING
#include<iostream.h>
template <class T1,class T2>
T add(T1 &a,T2 &b)
{
T c;
c=a+b;
return c;
}
template <class T1,class T2,class T3>
T add(T1 &a,T2 &b,T3 &c)
{
T d;
d=a+b+c;
return d;
}
void main()
{
int x;
x=add(12,13);
float y;
y=add(12.5,10.2.15.8);
cout<<SUM OF TWO INTEGERS<<x;
cout<<SUM OF THREE FLOATS<<y;
}
Two overloaded set of the template function add() exists in this program. If the
add() function is invoked with two parameters then the template function having
two parameters is invoked, if the add() function is called with three parameters
then the template function having three parameters is invoked.
Anna University Chennai
148
DCS 115
You can also overload a template function with a non template function. Always
a non template function takes precedence over template functions. Consider the
example given below.
NOTES
Example 6:
This example performs overloading of template function with a non template
function.
//TEMPLATE FUNCTION OVERLOADING
#include<iostream.h>
template <class T>
void square(T &x)
{
cout<<TEMPLATE FUNCTION;
cout<<SQUARE VALUE IS <<x * x;
}
void square(int x)
{
cout<<NON TEMPLATE FUNCTION;
cout<<SQUARE VALUE IS <<x * x
}
void main()
{
int a=10;
square(a); //INVOKES NON TEMPLATE FUNCTION
float b=12.5;
square(b); //INVOKES TEMPLATE FUNCTION
}
The output of the program will be
Thus we can note that when the function square is called with an integer parameter
it invokes the non template function whereas when the same function is invoked
with a float parameter it calls the template function.
Have you understood?
1.
2.
3.
4.
149
DCS 115
NOTES
8.4
Class Templates
C++ Class Templates are used where we have multiple copies of code for different
data types with the same logic. For example we create a template for an queue
class that would enable us to create queue to hold data items of different data
types like int, float, double etc.,
Templates can be used to define generic classes. A class template definition looks
like a regular class definition, except it is prefixed by the keyword template. A
parameter should be included inside angular brackets. The parameter inside the
angular brackets, can be either the keyword class or typename. This is followed
by the class body declaration with the member data and member functions. The
syntax to declare the class template is given below
//C++ class template
template <class T>
class classname
{
//member variable declarations of type T and other types
//member function declarations
};
Example 7:
The following is a simple example of class templates
//SIMPLE C++ CLASS TEMPLATE
#include<iostream.h>
template <class T>
class calc
{
T a,b;
public:
calc(T x,T y)
{
a=x;
b=y;
}
void add()
{
cout<<SUM IS << a+b;
}
T mul()
{
return a*b;
Anna University Chennai
150
DCS 115
}
};
void main()
{
calc<int> obj(10,10);
obj.add();
int c;
c=obj.mul();
cout<<PRODUCT IS <<c;
}
NOTES
This class template is designed to perform simple addition and multiplication for
all data types. You can note that this template class resembles ordinary c++ class
except the template declaration. Just look at the line that creates the object
calc<int> obj(10,10);
The int parameter within the angular brackets specifies that object obj will be
working on integer parameters. You can note that the member functions are called
in the same way as you do with the ordinary classes.
Example 8:
The program given below creates a generic stack and performs all basic stack
operations.
//GENERIC STACK
#include<iostream.h>
#include<iomanip.h>
#define SIZE 10
template <class T>
class template_stack
{
T stack[SIZE];
int top;
int status,data,choice;
template_stack()
{
top=-1;
}
int push(int data)
{
if(isFull())
151
DCS 115
NOTES
return -1;
stack[top]=data;
top++;
return 1;
}
int pop()
{
int d;
if(isEmpty())
return -1;
d=stack[top];
top;
return d;
}
int peek()
{
if(isEmpty())
return -1;
return stack[top];
}
int isEmpty()
{
if(top==-1)
return 1;
else
return 0;
}
int isFull()
{
if(top==SIZE-1)
return 1;
else
return 0;
}
int size()
{
return top+1;
}
}
void main()
{
template_stack<int> stk;
int status;
152
DCS 115
do
{
NOTES
cout<<1PUSH;
cout<<2POP;
cout<<3PEEK;
cout<<4->SIZE
cout<<5EXIT;
cout<<Enter Ur Choice\n;
cin>>ch;
switch(ch)
{
case 1:
cout<<Enter the data to insert);
cin>>data;
status=stk.push(data);
if(status==-1)
cout<<Full Stack<<endl;
else
cout<<data<< Successfully Inserted;
break;
case 2:
status=stk.pop();
if(status==-1)
cout<<Empty Stack<<endl;
else
cout<< Data Popped is <<status;
break;
case 3:
status=stk.peek();
if(status==-1)
cout<<Empty Stack<<endl;
else
cout<<The Top Element in the Stack is<<status;
break;
case 4:
cout<<The Size of the Stack is <<stk.size();
break;
case 5:
cout<<Bye;
exit(0);
default:
cout<<Invalid Choice<<endl;
}
}while(1);
}
153
DCS 115
NOTES
8.4.1
Like function templates a class template can also take multiple parameters. Thus
it is possible to use more than one generic data type in a class template. The list of
parameters that are passed to the class template are separated using commas. The
general form of the is given below
template <class T1,class T2,.>
class classname
{
}
Example 9:
The following code is an example for class templates with multiple parameters
#include<iostream.h>
#include<iomanip.h>
template <class T1,class T2>
class disp
{
T1 x;
T2 y;
public:
disp(T1 a,T2 b)
{
x=a;
y=b
}
void print()
{
for(int i=0;i<x;i++)
cout<<y<<\t;
}
}
void main()
{
disp<int,char> obj(5,a);
obj.print();
disp<int,float> obj(5,1.1);
obj.print();
}
Anna University Chennai
154
DCS 115
8.4.2
NOTES
So far in our class templates discussions we have used only inline functions in
the class but it is still possible to write a member function definition outside the
template class. The syntax is
template <class T>
returntype classname<T> :: functionname(parameter list)
{
//body of the function
}
Example 10:
The program given in the previous example is modified using member function
templates.
#include<iostream.h>
#include<iomanip.h>
template <class T1,class T2>
class disp
{
T1 x;
T2 y;
public:
disp(T1 a, T2 b);
void print();
};
template <class T1,class T2>
disp<T> :: disp(T1 a,T2 b)
{
x=a;
y=b;
}
template <class T1,class T2>
void disp<T> :: print()
{
for(int i=0;i<x;i++)
cout<<y<<endl;
}
void main()
{
disp<int,char> obj(5,a);
obj.print();
155
DCS 115
disp<int,float> obj(5,1.1);
obj.print();
NOTES
}
156
DCS 115
NOTES
157
DCS 115
NOTES
References
1.
2.
3.
4.
5.
6.
Thinking in C++
Author: Bruce Eckel
Publisher : Prentice Hall 2000
158
DCS 115
NOTES
CHAPTER 9
EXCEPTION HANDLING
Exception Types
Multiple Catch Statements
Exception Handling Mechanism
Catching All Exceptions
Functions Generating Exceptions
Catching All Exceptions
Throwing Mechanisms
Specifying (Restricting) Exceptions
Catching Mechanisms
Rethrowing Exceptions
9.1 Introduction
Generally programmers may commit some errors. Errors can be classified in two
categories. They are Compile time errors and Run time errors. Compile time errors usually comprise of syntax errors such as a missing semicolon, unbalanced
parenthesis etc., they can be easily detected when we compile our program but
Runtime errors are relatively difficult to detect and rectify it. To solve this C++
provides a build-in error handling mechanism that is called exception handling.
Using the C++ exception handling mechanism we can easily identify and respond to run time errors. This chapter briefly explores the various exception handling mechanisms available in C++.
9.2 Learning Objectives
DCS 115
NOTES
Synchronous Exception
Asynchronous Exception.
Exceptions that are within the control of the program are called synchronous
exceptions for example referring to an index of array, out of the range index.
Exceptions that are beyond the control of program is said to be asynchronous
exceptions for example memory overflow interrupt.
C++ exception handling mechanism works only for synchronous exception. To
handle synchronous exceptions we have to follow the following steps
The first step to handle exceptions is to identify the block of code that may cause
error. After identifying it report the error to the error handling routine by throwing it. The error handling routine will receive and process the error.
Have you understood?
1. Give some examples for compile time errors.
2. What are the two categories of exceptions?
3. Mention the steps to handle synchronous exceptions.
9.4 Exception Handling Mechanism
C++ exception handling mechanism is built upon three important keywords. They
are
try
catch
throw
The program statements that we suspect that they may cause runtime are put in
the guarded section called try block. If the exception occurs in the try block it is
thrown to the catch block. The catch block catches the thrown exception and
handles it appropriately. The general form of the try catch structure is
Anna University Chennai
160
DCS 115
try
{
NOTES
//try block
} catch(type1 arg)
{
//catch block
}
When any statement present in the try block causes an exception (i.e error) the
program control leaves the try block without executing further statements and
switches to the catch block. The catch block will have the necessary program
statements to handle the error.
In C++, exceptions are treated as objects. Hence when an exception is created
and thrown the corresponding catch block (the catch that has the type which
matches with the object) will catch the exception and handle it otherwise, the
exception will be left unhandled and an abnormal program termination may occur.
The general form of a throw statement is
throw exception;
throw must be executed either from within the try block or from any function that
the code within the block calls (directly or indirectly).
Example 1:
The following is a simple example with try catch block.
#include<iostream.h>
int main()
{
int i,j;
cout << Starts here\n;
i=10;
j=0;
try
{
// start a try block
cout << Inside try block\n;
if(j==0)
{
throw j; // throw an error
161
DCS 115
NOTES
When the program enters the try block it is said to be in the guarded section. In
this program when the value of j is zero an exception is created and thrown note
that the statements after throw statement in try block is not executed. Once the
exception is thrown the catch block catches the value (here zero) and handles it.
After that the program continues it normal execution. Thus we can see that in
C++ the exceptions are handled using the following steps.
162
DCS 115
Example 2:
NOTES
The function compute() given in this example generates and throws exceptions.
#include<iostream.h>
#include<iomanip.h>
void compute(int a,int b)
{
int c;
if(b==0)
throw b;
c=a/b;
cout<<RESULT OF THE DIVISION<<c;
}
void main()
{
int x,y;
cout<<ENTER TWO NUMBERS<<endl;
cin>>x>y;
try
{
compute(x/y);
}
catch(int k)
{
cout<<DIVIDE BY ZERO EXCEPTION<<endl;
}
}
Here we can note that the call to the function compute() is enclosed within the
try catch block. If the value of the dividend b is zero the function generates an
exception, which is handled in the catch block kept in the main program.
Have you understood?
1. How will you call a function that generates exception?
9.6 Throwing Mechanisms
An exception is thrown by using the throw keyword from inside the try block.
Exception handlers are declared with the keyword catch, which must be placed
immediately after the try block. A throw expression accepts one parameter, which
is passed as an argument to the exception handler. The throw statement will have
the following form
163
DCS 115
NOTES
throw (exception)
throw exception
throw
If an exception is thrown during execution of the guarded section or in any routine the guarded section calls (either directly or indirectly), an exception object is
created from the object created by the throw operand. Now, the compiler looks
for a catch clause that can handle an exception of the type thrown or a catch
handler that can handle any type of exception. The catch handlers are examined
in order of their appearance following the try block. If no appropriate handler is
found, the next enclosing try block is examined. This process continues until the
outermost enclosing try block is examined.
Have you understood?
1. Mention the different form of throw statement
2. How catch handlers are examined in a try block.
9.7 Catching Mechanisms
The general form of the catch statement is
catch(type arg)
{
//catch block
}
The catch statement used is determined by the type of the exception. That is, if
the data type specified by a catch, matches that of the exception, that catch statement is executed (all other are bypassed). When an exception is caught, arg will
receive its value. If you dont need access to the exception itself, specify only
type in the catch clause (arg is optional). Any type of data can be caught, including classes that you create
Have you understood?
1. Give the general form of catch block.
9.8 Multiple Catch Statements
A try can have multiple catches, if there are multiple catches for a try, only one of
the matching catch is selected and that corresponding catch block is executed.
The syntax for try with a multiple catch is given below.
164
DCS 115
NOTES
try
{
any statements
if (some condition) throw value1;
else if (some other condition) throw value2;
...
...
...
else if (some last condition) throw valueN;
}catch (type1 name)
{
any statements
}
catch (type2 name)
{
any statements
}
...
...
...
catch (typeN name)
{
any statements
}
Throw generates the exception specified by the corresponding value. This value
can be of any type and multiple throw statements might occur. When an exception is thrown, it is caught by the corresponding catch statement, which then
processes the exception.
If there are more than one catch statement associated with a try. The type of the
exception determines which catch statement is used. When an exception is caught,
name (the argument of the catch statement) will receive the thrown value. This
thrown value determines which catch block will be executed.
Sometimes the arguments of several catch statements match the type of an exception, in that case the first matching catch handler block is selected and executed.
A simple example for try with multiple catches is given below.
165
DCS 115
NOTES
Example 3:
The following example has a single try with multiple catches.
#include<iostream.h>
#include<iomanip.h>
void multiple_catch(int value)
{
try
{
if (value==0) //throw an int value
throw 1;
else if (value==1) //throw a char
throw a;
else //throw float
throw 1.1;
}
catch(char c)
{
cout<<Character value is thrown <<c;
}
catch(int i)
{
cout<<Integer value is thrown<<i;
}
catch(float f)
{
cout<<Float value is thrown<<f;
}
}
void main()
{
cout<<Main Program<<endl;
multiple_catch(0);
multiple_catch(1);
multiple_catch(5);
}
166
DCS 115
NOTES
DCS 115
NOTES
}
catch( )
{
cout<<Exception is Caught!!! <<endl;
}
}
void main()
{
cout<<Main Program<<endl;
multiple_catch(0);
multiple_catch(1);
multiple_catch(5);
}
Have you understood?
1. Write the syntax of the catch handler that can catch all exceptions
168
DCS 115
#include<iostream.h>
#include<iomanip.h>
void multiple_catch(int value) throw (int,char,double)
{
try
{
if (value==0) //throw an int value
throw 1;
else if (value==1) //throw a char
throw a;
else //throw float
throw 1.1;
}
catch(char c)
{
cout<<Character value is thrown <<c;
}
catch(int i)
{
cout<<Integer value is thrown<<i;
}
catch(float f)
{
cout<<Float value is thrown<<f;
}
}
NOTES
void main()
{
cout<<Main Program<<endl;
multiple_catch(0);
multiple_catch(1);
multiple_catch(5);
}
Have you understood?
1. How will you restrict functions that generates exceptions?
169
DCS 115
NOTES
Errors cane be classified in two categories they are Compile time errors
and Run time errors.
Exceptions can be classified as Synchronous and Asynchronous exceptions.
C++ exception handling mechanism is built upon three important keywords. They are try, catch and throw.
When any statement present in the try block causes an exception (i.e error) the program control leaves the try block without executing further
statements and switches to the catch block.
170
DCS 115
NOTES
Exercises
Short Questions
1.
2.
3.
4.
5.
6.
How does compile time errors differs form run time errors
Memory overflow is an example for ___________
What do you mean by asynchronous exceptions
Write the three keywords used to handle exceptions
Explain guarded section
The number of try and catch statements in a c++ program should be
the same (True/False)
7. How will you catch all exceptions?
8. Is it possible to restrict exceptions generated from a function?
171
DCS 115
NOTES
Long Questions
1. Explain the exception handling statements in detail
2. Explain the different form of throw statement.
3. Discuss restricting exception generated by a function
Programming Exercises
1. Write a program to read array from a keyboard. Accept the index from the
user and retrieve the element present in that index. Include exception handling facilities.
2. Create your own program to handle divide by zero exceptions
Answers to Have you Understood Questions
Section 9.3
1. Syntax errors such as a missing semicolon, unbalanced parenthesis etc.,
2. Exceptions can be classified as Synchronous and Asynchronous exceptions.
3. To handle synchronous exceptions the following steps are involved
Identify the problem(error)
Report the error
Receive the error
Rectify the error.
Section 9.4
1.
2.
When any statement present in the try block causes an exception (i.e error) the program control leaves the try block without executing further
statements and switches to the catch block.
172
DCS 115
NOTES
3. throw exception.
Section 9.5
1. By enclosing the function call in try catch block.
Section 9.6
1. The different form are (1) throw (exception) (2) throw exception (3) throw
2. The catch handlers are examined in order of their appearance following
the try block. If no appropriate handler is found, the next enclosing try
block is examined. This process continues until the outermost enclosing
try block is examined.
Section 9.7
1.
Section 9.8
1. True
2. one
Section 9.9
1.
try
{
//statements
}catch (...)
{
do something
}
Section 9.10
1. The type of exceptions that a function can throw can be restricted to certain types. To accomplish these restrictions, a throw clause must be added
to the function definition. The throw clause specifies the possible list of
types a function can throw.
173
DCS 115
NOTES
Section 9.11
1. The syntax is
try
{
.
.
}
catch (char c)
{
throw; //rethrow same exception
2.
}
No
References
1.
2.
3.
4.
5.
6.
Thinking in C++
Author: Bruce Eckel
Publisher : Prentice Hall 2000
174
DCS 115
NOTES
CHAPTER 10
INTRODUCTION TO JAVA
PROGRAMMING
10.1
Java Features
Operators
Java Virtual Machine
Expressions
Writing Java Source Code
Data Types
Java Tokens
Variables Declaration
Keywords
Constants
Identifiers
Java Statements
Literals
Command Line Arguments
Introduction
DCS 115
NOTES
The earlier versions of java were not so powerful but now Java has became a
common language to develop applications like on line web stores, transactions
processing, database interfaces etc., java has also become quite common on small
platforms such as cell phones and PDAs. Java is now used in several hundred cell
phone models. This chapter explores the various fundamental programming concepts of Java.
10.2
Learning Objectives
10.3
Java Features
Java is a high level language looks much similar to C, C++ but it offers many
unique features that are not available in most of modern programming language. Java language has the following features.
176
DCS 115
NOTES
Platform Independence
Java programs are capable of running on all platforms hence java programs possess Write-Once-Run-Anywhere feature
Object Oriented
Java is purely an object oriented language. In Java no coding outside of class
definitions is allowed, including the main() function. Java supports an extensive
class library available in the core language packages.
Robust
Java is a robust language. It provides the following facilities to ensure reliable
code
Built in Exception Handling
Strong type checking both at compile and runtime.
Local variables must be initialized
Security
Java is a highly secured language. Java programs will run only within the Java
Virtual Machine (JVM) sandbox thus threats from malicious programs is minimized. Java does not support pointers hence direct memory access is not allowed.
Java supports a built in security manager that determines what resources a class
can access such as reading and writing to the local disk.
Automatic Memory Management
Java supports automatic memory management. Java Virtual machine (JVM) performs garbage collection automatically to claim the memory occupied by unused
objects.
Dynamic Binding
Java is a dynamic language. The linking of data and methods occurs only at run
time. In java new classes can be loaded even when the program is on execution.
High Performance
Interpretation of bytecodes slowed performance in early versions, but advanced
virtual machines with adaptive and just-in-time compilation and other techniques
now typically provide improved performance.
177
DCS 115
NOTES
Multithreaded
In java it possible to write programs to handle multiple tasks simultaneously. To
write such programs you have to create light weight processes called Threads
in java. The threads thus created can be executed simultaneously. Multithreaded
programs are useful when you write programs for networking and multimedia.
Some Features in C/C++ Eliminated
Some features in C/C++ are eliminated in java. They are listed below.
No Pointers
No Preprocessor Directives
No Multiple Inheritance in Classes
No template Classes
Have you understood?
1. Explain how java program gets executed.
2. Justify the statement Java programs are secure
3. List out the features that are eliminated in Java but available in C++.
10.4
You have learnt that java is a platform independent and architectural neutral language. These features are provided by the java run time environment called Java
Virtual Machine (JVM).When a java program is compiled it will not produce a
machine code instead it produces an intermediate byte code for the JVM. When
you run the java program the byte code produced for the JVM will be interpreted
by the java run time interpreter. This interpreter converts the byte code to the
executable machine code for the machine that runs the java program. The process
of compilation and execution is shown below.
178
DCS 115
NOTES
JAVA PROGRAM
JAVA COMPILER
BYTE CODE
Compilation Process
BYTE CODE
JAVA INTERPRETOR
MACHINE CODE
Execution Process
The byte code produced by the java compiler for the JVM is common to all
platforms hence byte code is platform independent.
10.4.1 Writing Java Source Code
Writing java source code is similar to writing a source code in C++ but with some
variations. Writing Java source code is dealt in detail in subsequent chapters.
Now lets start our discussion by writing a simple java program.The following is
a simple java program. The source code is written in the file named Welcome.java
1.
2.
3.
4.
5.
class Welcome
{
public static void main(String args[])
{
// The following line is used to display a line of text
System.out.println(Welcome to Java world );
6. }
7. }
To compile this program you have to use the javac compiler. The syntax to
compile is
179
DCS 115
NOTES
javac filename.java
java classname
The First line of this program has the class declaration, as mentioned
earlier every code written in java should be kept inside a class definition.
The third line declares the main() method in java. The main() method in
java should be declared public and static .Usually the return type of the
main method is void.
In java main() method should be declared public because main() method
should be made accessible to all other classes
main() method is declared static because the main() method belongs to
the class not to a specific object
System.out.println() is a statement used to display some text to the user. It
is similar to cout statement in C++.
Example 1:
The code listed below performs addition of two integer numbers.
class sum
{
public static void main(String args[])
{
int i=10,j=25;
k=i+j;
System.out.println(THE SUM IS +k);
}
}
In this example you have declared two integer variables i and j .The + operator
used in the System.out.println() is concatenation operator.
Anna University Chennai
180
DCS 115
NOTES
Java Tokens
As mentioned in chapter 1 tokens are the basic lexical elements of any programming language In Java every statement is made up of smallest individual elements called tokens. Tokens in java include the following
Keywords
Identifiers
Literals
Operators
10.5.1 Keywords
The list is of keywords available in java are given below. Every keyword will
perform a specific operation in java. As mentioned in chapter 1 keywords cannot
be redefined by a programmer; further keywords cannot be used as identifier
name.
Abstract
Assert
Boolean
Break
Byte
Case
Catch
Char
class
const
continue
default
do
double
else
enum
extends
final
finally
float
For
Goto
If
implements
Import
instanceof
Int
Interface
Long
Native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
181
DCS 115
NOTES
10.5.2
Identifiers
Find_3
Message
abc$
A23C
Literals
10.5.4
Integer Literals
(Ex. 123)
Floating point Literals(Ex. 88.223)
Character Literals
(Ex. . , a , \n)
String Literals
(Ex. Hello World)
Boolean Literals
(Ex. True,false)
Operators
Arithmetic Operators
+
-
182
DCS 115
*
/
%
NOTES
Multiplication operator
Division operator
Remainder operator
Unary Operators
+
++
Equal to
Not equal to
Greater than
Greater than or equal to
Less than
Less than or equal to
Conditional Operators
&&
||
?:
Conditional-AND
Conditional-OR
Ternary (shorthand for if-then-else statement)
183
DCS 115
Operator Precedence
NOTES
Operators
Precedence
postfix
expr++ expr
unary
multiplicative
*/%
additive
+-
shift
relational
equality
== !=
bitwise AND
&
bitwise exclusive OR
bitwise inclusive OR
logical AND
&&
logical OR
||
ternary
?:
assignment
184
DCS 115
For Example
x=a+b;
y=a*(b+c)/(m+n)*f
a+=b
NOTES
//Simple expression
//Complex expression
//Similar to a=a+b.
DCS 115
NOTES
double
8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to
1.79769313486231570e+308d (positive or negative).
char
2 bytes, unsigned, Unicode, 0 to 65,535
10.7.1
Variables Declaration
10.7.2 Constants
Constants refer to values that do not change during the execution of the program.
Examples for constants are
1998
25.789
Hello World
a
Integer constant
Floating point constant
String constant
Character constant
Apart from these types of constants java also supports backslash character constants. The Table 10.2 lists all the backslash constants.
BACKSLASH CONSTANT
PURPOSE
\b
Backspace
\f
Form feed
\n
New Line
\r
Carriage return
\t
Horizontal tab
\\
Backslash
Table 10.2 Backslash Constants
Have you understood?
1.
2.
3.
4.
5.
186
DCS 115
NOTES
Example 2:
The Program given below compares two numbers and finds the greater of the two
numbers.
class big
{
public static void main(String args[])
{
int i=30,j=25;
if(i>j)
System.out.println(I IS BIG);
else if(i==j)
System.out.println(I AND J ARE EQUAL);
else
System.out.println(J IS BIG);
}
}
Example 3:
The Code listed below makes use of a switch case construct.
class switch_ex
{
public static void main(String args[])
{
char ch;
System.out.println(COUNTRIES AND THEIR CAPITALS);
System.out.println(I-INDIA,U-USA,J-JAPAN,F-FRANCE);
try
{
ch=(char)System.in.read();
187
DCS 115
switch(ch)
{
case I:
System.out.println(INDIA-NEWDELHI);
break;
case U:
System.out.println(USA-WASHINGTON DC);
break;
case J:
System.out.println(JAPAN-TOKOYO);
break;
case F:
System.out.println(FRANCE-PARIS);
break;
default:
System.out.println(INVALID CHOICE);
}
}catch(Exception err) { System.out.println(ERROR); }
NOTES
}
}
In this example you are reading character input from the keyboard for this you are
using the statement System.in.read().as you know try and catch statements are
used for exception handling.
Now let us write some program using looping statements. The first looping
structure discussed is the while loop. This program prints the multiplication table
for the number 5.
Example 4:
The Program given below prints the multiplication table for 5 using while loop.
class while_test
{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
System.out.println(i + * 5 = +i*5);
i++;
}
}
}
188
DCS 115
Example 5:
NOTES
The Program given below is the do... while version of the previous example
class dowhile_test
{
public static void main(String args[])
{
int i=1;
do
{
System.out.println(i + * 5 = +i*5);
}while(i<=10);
}
}
Example 6:
The Program listed below makes use of a for loop to print the multiplication table
for 5.
class for_test
{
public static void main(String args[])
{
for(i=1;i<10;i++)
{
System.out.println (i + * 5 = +i*5);
}
}
}
Have you understood?
1. Write the syntax for if statement in java.
2. Write the syntax for a for loop.
3. What is the purpose of break and continue statement?
10.9 Command Line Arguments
In Java it is possible to provide input to a program as command line arguments.
The String args[] argument in the main method is used to supply command line
arguments to the program. Java programs accept only strings as command line
arguments. However you can convert these arguments into the desired data types
using the wrapper classes.
189
DCS 115
NOTES
Thus using wrapper classes you can convert the string to the corresponding simpler type. The signature for the Integer wrapper class is
static int parseInt(String s)
For example
Integer.parseInt(10)
will convert the string 10 to integer 10. The Integer wrapper class has a static
method called parseInt to perform this job. Similarly the signature of the Double
wrapper class is
static int parseDouble(String s)
For example
Double.parseDouble(153.18)
will convert the string 153.18 to double 153.18. The Double wrapper class has
a static method called parseDouble to perform this job. Similar methods are available for all the simple types.
The command line arguments passed to program are stored in the String array
args[] . The first element is referenced as args[0] , the next element as args[1] and
so on.
Command line arguments are supplied to the program when you run the program.
For example when you run the program named hello.java
C:\jdk1.5.0\bin> java hello 123 abc 12.88
args[0] contains 123
args[1] contains abc
args[2] contains 12.88
Example 7:
The following example accepts two command line arguments and computes the
sum of two numbers.
class sum
{
190
DCS 115
NOTES
}
Output of the Program
Example 8:
The following example accepts a number n as command line argument and
generates n Fibonacci numbers.
class fib
{
public static void main(String args[])
{
int n;
int a=0,b=1,c;
n=Integer.parseInt(args[0]);
for(int i=0;i<n;i++)
{
c=a+b;
System.out.println(The next number is +c);
191
DCS 115
a=b;
b=c;
NOTES
}
}
}
Example 9:
The following example prints number of command line arguments passed.
class count
{
public static void main(String args[])
{
int n;
n=args.length;
System.out.println(The count is +n);
}
}
Have you understood?
1. How command line arguments are passed to the program
2. How will you convert string 50 to integer
3. How will you find length of command line arguments
192
DCS 115
Summary
NOTES
Java is a high level language looks much similar to C, C++ but it offers
many unique features that are not available in most of modern programming language.
Java compiler converts the source code into intermediate byte code instructions Java Interpreter converts these bytes codes into machine executable statements
Java programs are capable of running on all platforms hence java programs possess Write-Once-Run-Anywhere feature
Java programs will run only within the Java Virtual Machine (JVM) sandbox
Java is a dynamic language. The linking of data and methods occurs only
at run time.
When a java program is compiled it will not produce a machine code
instead it produces an intermediate byte code for the JVM. When you run
the java program the byte code produced for the JVM will be interpreted
by the java run time interpreter.
Java tokens include keyword, identifiers, literals and operators.
In Java expressions are used to implement some computation. Expressions in java can be either a simple expression or a complex expression.
Float and Double data types were represented in IEEE 754 format
Characters are represented as unsigned Unicode values
In Java Constants refer to values that do not change during the execution
of the program
Java supports decision-making statements like (if-then, if-then-else,
switch), the looping statements (for, while, do-while), and the branching
statements (break, continue, return) the syntax and usage of these control
structures are similar to C++.
Exercises
Short Questions
1.
2.
3.
4.
5.
6.
7.
8.
9.
What is JVM?
Write the signature of main() method
Why main() method is declared as static?
The type comparison operator in java is ____________
When Boolean data type is used?
\\ is used as ___________
Mention the range for char data type
How will you make a early exit from a loop in Java?
What is a wrapper class?
193
DCS 115
NOTES
Long Questions
1. Explain the various features of Java in detail
2. Write short notes on JVM
3. Write the syntax and explain the various Java control and looping
statements
Programming Exercises
1. Write a program to print the first n Amstrong numbers (accept n as
command line argument)
2. Write a Java program to compute the sum of the series 1! +2! +3!
+. +n!
3. Write a Java program to find the sum of digits of a number
4. Write a Java program to find area of a triangle
Answers to Have you Understood Questions
Section 10.3
1. Java compiler converts the source code into intermediate byte code instructions Java Interpreter converts these bytes codes into machine executable statements
2. Java programs will run only within the Java Virtual Machine (JVM) sandbox thus threats from malicious programs is minimized. Java does not
support pointers hence direct memory access is not allowed. Java supports a built in security manager that determines what resources a class
can access such as reading and writing to the local disk. Thus we can say
java programs are secure.
3. (1) Pointers (2) Preprocessor directives (3) Multiple inheritance (3)
Tempalte classes
Section 10.4
1. When a java program is compiled it will not produce a machine code
instead it produces an intermediate byte code for the JVM.
2. To compile you have to use javac compiler,to run you have to use java
inter
preter.
3. System.out.println()
Section 10.5
1. Java tokens include keyword, identifiers, literals and operators.
2. c
194
DCS 115
3.
NOTES
Section 10.6
1. In Java expressions are used to implement some computation. Expressions in java can be either a simple expression or a complex expression.
Section 10.7
1.
2.
3.
4.
5.
Section 10.8
1. The if-else statement is used for making decisions. The syntax is
if ( expression)
statement1
else
statement2
2. The for statement syntax is given below
for (expr1; expr2; expr3)
{
statements;
}
3. The break statement provides an early exit from for, while, and do, just as from
switch. Continue causes the next iteration of the enclosing for, while, or do loop
to begin
Section 10.9
1. The String args[] argument in the main method is used to supply
command line arguments to the program.
2. Integer.parseInt(50)
3. By using args.length (args is the string array)
195
DCS 115
NOTES
References
1.
2.
http:\\www.sun.com
3.
Thinking in Java
Author: Bruce Eckel
Publisher : Prentice Hall 2000
4.
5.
196
DCS 115
NOTES
CHAPTER 11
OBJECT OREINTED CONCEPTS IN
JAVA
Classes
Objects
Adding Variables to Classes
Adding Methods to Classes
Constructors
Access Specifiers
Default Access
Method Overloading
Constructer Overloading
Static Data Members
Static Methods
Inheritance
Super Keyword
Multilevel Inheritance
Method Overriding
Uses of Super Keyword
Abstract Methods and Classes
Final Keyword
Finalizer Methods
11.1 Introduction
Java is purely an object oriented language. In Java no coding outside of class
definitions is allowed, including the main() function. Java supports all the primary concepts of object orientation like encapsulation, abstraction, inheritance
and polymorphism. This chapter introduces you to implement all the object oriented features supported by java. This chapter provides the necessary background
to understand the advanced concepts presented in the subsequent chapters.
11.2
Learning Objectives
To introduce classes and objects in Java
To discuss about adding methods to classes
To introduce the concept of constructors
To discuss the various access specifiers available in Java.
To present the constructor and method overloading features
To discuss static data members and methods.
To understand the concept of inheritance
To learn the importance of super keyword
197
DCS 115
NOTES
11.3
Classes are the basic building blocks of Java programs. Classes are called as
Abstract Data Type (ADT) .Classes describes the structure of the object. Java
classes consist of both attributes and behaviors. Attributes represent the data that
is unique to an instance of a class, while behaviors are methods that operate on
the data to perform useful tasks.
Class Syntax
The syntax to declare a class in Java is:
[public ] [ ( abstract | final ) ] class <classname> [ extends ParentClass ] [
implements interfaces ]
{
// variables and methods declaration
}
Here is an example of a GUI class. GUI is a class that extends the parent class
called Frame and implements two interfaces namely ActionListener and
ItemListener.
public class GUI extends Frame implements ActionListener, ItemListener
{
//declarations of variables and methods
}
11.3.1 Objects
Objects are the run time instance of a class. Classes describe objects. Many objects can be instantiated from one class. Objects of different classes can be created, used, and destroyed in the course of executing a program.
198
DCS 115
Objects in java are created using the new operator. For example to create an
object for the GUI class we follow the given syntax.
NOTES
//declare
//instantiate
DCS 115
NOTES
There are a number of optional modifiers that you can use when declaring a
method. They are listed in the Table 11.1:
Table 11.1 List of Modifiers in Java
Modifier
Description
Visibility
Can be one of the values: public, protected, or private. Determines what classes can invoke the
method.
static
abstract
final
native
synchronized
throws
Now, consider the product class created previously, we can add two methods
getDetails() and displayDetails() to the class.
class product
{
int prod_id;
double price;
void getDetails(int a,String b,double c)
{
prod_id=a;
price=c;
}
void displayDetails()
{
System.out.println(Product id is +prod_id);
System.out.println(Price is +price);
}
}
Anna University Chennai
200
DCS 115
Example 1:
NOTES
DCS 115
NOTES
}
}
Have you understood?
1.
2.
3.
4.
5.
What is a class?
All classes in java extend __________
What is an object?
Write the syntax of method declaration.
Explain abstract keyword.
11.4 Constructors
Constructors are special type of methods that are invoked when we create objects
for the classes. Constructers will have the same name as that of the class. Constructors and methods differ in two important aspects of the signatures. They are
Modifiers
Return types
Like methods, constructors can have any of the access modifiers: public, protected, private, or none (often called friendly). However constructors cannot be
made abstract, final, native, static, or synchronized.
Methods can have any valid return type, or no return type, in which case the
return type is given as void. Constructors cannot take any return type, even void.
Example 2:
The Calculator class created in example 1 is modified, the setData() method is
replaced with a constructer.
class Calculator
{
int n1,n2,res;
Calculator (int x1,int x2) //Constructor
{
n1=x1;
n2=x2;
}
void add()
{
res=n1+n2;
Anna University Chennai
202
DCS 115
NOTES
}
class Mainprg
{
public static void main(String args[])
{
Calculator cal=new Calculator(20,10); //Calls the constructer
cal.add();
cal.sub();
int y=cal.mul();
System.out.println(The Product is : +y);
double d=cal.div();
System.out.println(The divided value is :+d);
}
}
Have you understood?
1. What is constructer?
2. Differentiate constructors from other methods.
11.5
Access Specifiers
An access specifier in java determines which data member, which method can be
used by other classes. Java supports three access specifiers and a default access
specifier. Access specifiers are also known as access modifiers. The three access
specifiers supported in Java are
The private access specifier
203
DCS 115
NOTES
204
DCS 115
NOTES
DCS 115
NOTES
either in type of their arguments or the number of their arguments or both. The constructer
that takes no parameter is called default constructer. Below is the example of constructer
overloading.
Example 4:
The program given below makes use of constructer overloading concept.
class dimension
{
int x1,y1;
dimension() //default constructor
{
x1=0;
y1=0;
}
dimension(int a)
{
x1=a;
y1=0;
}
dimension(int a,int b)
{
x1=a;
y1=b;
}
void display()
{
System.out.println( x1 is :+x1);
System.out.println( y1 is :+y1);
}
}
class Mainprg
{
public static void main(String args[])
{
dimension d1=new dimension(10,50); //Calls constructer with two
parameter
dimension d2=new dimension(10);
//Calls constructer with one
parameter
dimension d3=new dimension();
//Calls default constructer
d1.display();
d2.display();
d3.display();
}
}
206
DCS 115
NOTES
Each object of a given class has its own copy of all the data defined by the class.
Sometimes it is desirable for all the objects of a particular class to share data. In
Java this can be achieved by defining the corresponding class members as static
using the keyword static. Since static variables are common all the instances of
the class, static variables can also be called as class variables.
for a static data member there will be only one copy of the class member
shared by all objects of the class.
A static data member is like a global variable, but has class-level scope.
A static method can access only static data and can call only other static
methods. A non-static member function can access all of the above including the static data member.
A static method can be called, even when a class is not instantiated, a nonstatic member function can be called only after instantiating the class as
an object.
Example 5:
This program makes use of static data members and methods class test
{
static int increment(int k)
{
k++;
return k;
207
DCS 115
NOTES
}
static int decrement(int j)
{
j;
return j;
}
}
class static_test
{
public static void main(String args[])
{
int a=static_test.increment(10);
System.out.println(Incremented Value is : +a);
int b=static_test.decrement(20);
System.out.println(Decremented Value is : +b);
}
}
In Java class libraries many static methods are found. For example in java.lang
package, we have a class called Math all the methods declared in the Math
class are static.
Example 6:
This program makes use of some static methods available in Math class.
class Math_test
{
public static void main(String args[])
{
System.out.println(Sin 30 is +Math.sin(30));
System.out.println(Square root of 25 is +Math.sqrt(25));
System.out.println(Absolute value for -15 is +Math.abs(-15));
System.out.println(Log value for 88.87 is +Math.log(88.87));
System.out.println(3 Power 5 is + Math.pow(3,5));
}
}
208
DCS 115
NOTES
Inheritance
Inheritance is a feature by which new classes are derived from the existing classes.
Inheritance allows re-using code without having to rewrite from scratch. Inheritance is a compile-time mechanism in Java that allows you to extend a class (called
the base class or superclass) with another class (called the derived class or subclass). In Java, inheritance is used for two purposes:
Class inheritance - create a new class as an extension of another class,
primarily for the purpose of code reuse. That is, the derived class inherits
the public methods and public data of the base class. Java only allows a
class to have one immediate base class, i.e., single class inheritance
Interface inheritance Interface inheritance is used to achieve multiple
inheritance. It is discussed in detail in chapter 14.
The Syntax for class inheritance is given below
[public ] class <classname> extends ParentClass
{
//variables and methods declaration
}
In keyword extends is used to implement inheritance in Java. In Java the following forms of class inheritance is supported.
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance.
Example 7:
The program listed below is a single inheritance program.
class rectangle
{
int l;
int b;
rectangle(int x,int y)
209
DCS 115
NOTES
l=x;
b=y;
}
void rect_area()
{
System.out.println(Area of Rectangle is + l*b);
}
}
class cube extends rectangle
{
int h;
cube(int x,int y,int z)
{
super(x,y);
h=z;
}
void cube_volume()
{
System.out.println(Volume of the Cube is + l*b*h);
}
}
class Mainprg
{
public static void main(String args[])
{
cube c=new cube(10,20,30);
c.rect_area();
c.cube_area();
}
}
Output of the Program
Area of Rectangle is 200
Volume of the Cube is 6000
210
DCS 115
NOTES
Java uses a unique keyword called super to call the super class constructers. In
the previous example we have used super keyword to pass parameters to the
super class constructer from the sub class constructer. The following is the syntax
of super keyword
super()
(or)
super(parameter list)
With super(), the superclass no-argument constructor is called. With
super(parameter list), the superclass constructor with a matching parameter list is
called. The parameters in the super keyword must match the parameters in the
super class constructer When super keyword is used it must be the first statement
in the sub class constructor.
11.8.2 Multilevel Inheritance
As mentioned earlier java supports multilevel inheritance. The syntax for multilevel inheritance is given below.
class super1
{
}
class sub1 extends super1
{
}
class sub2 extends sub1
{
}
Example 8:
This program listed below is a simple example for multilevel inheritance.
//Super Class
class data1
{
211
DCS 115
int a;
data1(int x)
{
a=x;
}
NOTES
//Sub Class1
class data2 extends data1
{
int b;
data2(int x,int y)
{
super(x);
b=y;
}
}
//Sub Class2
class data3 extends data2
{
int c;
data3(int x,int y,int z)
{
super(x,y);
c=z;
}
void compute()
{
System.out.println(The Product is +a*b*c);
}
}
//Main Program
class Mainclass
{
public static void main(String args[])
{
data3 d=new data3(1,2,3);
d.compute();
}
}
212
DCS 115
NOTES
double getArea()
{
return Math.PI*radius*radius;
}
}
class Cylinder extends Circle
{
double length;
Cylinder(double radius, double l)
{
super(radius);
length=l;
}
double getArea()
{
213
DCS 115
NOTES
214
DCS 115
NOTES
double radius;
Circle(double r)
{
radius =r;
}
double getArea()
{
return Math.PI*radius*radius;
}
}
class Cylinder extends Circle
{
double length;
Cylinder(double radius, double l)
{
super(radius);
length=l;
}
double getArea()
{
return 2* super.getArea() +2*Math.PI*radius*length;
}
}
class Areaprg
{
public static void main(String args[])
{
double res;
Circle c=new Circle(3.3);
res=c.getArea();
System.out.println(Area of Circle is +res);
Cylinder cy=new Cylinder(3.3,5.2);
res=cy.getArea();
System.out.println(Area of Cylinder is +res);
}
}
Super keyword can also be used to refer superclass variables. Here is an example.
Example 11:
The Coding given below illustrates the use of super keyword to refer superclass
variables.
215
DCS 115
NOTES
class data1
{
int a;
data1(int x)
{
a=x;
}
}
//Sub Class1
class data2 extends data1
{
int b;
data2(int x,int y)
{
super(x);
b=y;
}
void display()
{
System.out.println(Value of a is +super.a);
System.out.println(Value of b is +b);
}
}
class Mainprg
{
public static void main(String args[])
{
data2 d=new data2(10,20);
d.display();
}
}
216
DCS 115
NOTES
DCS 115
NOTES
}
Have you understood?
1. How will you declare an abstract method?
2. Is it possible to instantiate an abstract class?
11.12 Final Keyword
Java supports an important keyword called Final. The keyword Final is used in
three different context. Final keyword can be used along with
1
2
3
Variables
Methods
Classes
218
DCS 115
NOTES
}
11.12.1 Finalizer Methods
Before an object is garbage collected, the runtime system calls its finalize () method. The purpose of finalize () method is to release system resources
before the object gets garbage collected. The signature of finalize method is given
below.
protected void finalize () throws throwable
Finalize () method in java has the following properties
every class inherits the finalize() method from java.lang.Object
the method is called by the garbage collector when it determines no
more references to the object exist
the Object finalize method performs no actions but it may be overridden by any class
normally it should be overridden to clean-up non-Java resources ie
closing a file
Have you understood?
1. How will you declare a constant?
2. Mention the three ways in which final keyword can be used.
3. What is the purpose of finalize() method?
Summary
Java is purely an object oriented language. In Java no coding outside of
class definitions is allowed, including the main() function.
By default all classes in java will extend java.lang.Object.
Objects are the run time instance of a class. Classes describe objects.
Objects in java are created using the new operator.
When a method is declared as native ,its implementation can be given
in another language.
Constructors are special type of methods that are invoked when we
create objects for the classes. Constructers will have the same name as
that of the class.
Java supports public, private and protected access specifiers
If none of access specifiers are specified to a method or a variable, then
the scope is considered to be friendly, this is the default access scheme
in Java.
219
DCS 115
NOTES
In Java two or more methods can share the same name as long as either the
type of their arguments differs or the number of their arguments differs - or
both. When two or more methods share the same name, they are said overloaded.
Constructer overloading is a concept in which you have multiple
constructers that differ either in type of their arguments or the number
of their arguments or both.
Static variables are common all the instances of the class, static variables
can also be called as class variables.
Static methods are called without the object.
Inheritance is a feature by which new classes are derived from the
existing classes.
The keyword extends is used to implement inheritance in Java.
Java uses a unique keyword called super to call the super class
constructers.
If you include a method definition that has the same name and exactly
the same number and types of parameters as a method already defined
in the super class, this new definition replaces the old definition of the
method. This concept is called method overriding.
Abstract methods are those that will have only method declaration
without any implementation.
Final keyword when used with a variable, it becomes a constant
When a method declaration is prefixed with the Final keyword the
method cannot be overridden by the subclass method.
When a class is declared as Final then the class cannot be subclassed.
Before an object is garbage collected, the runtime system calls its
finalize () method. The purpose of finalize () method is to release
system resources before the object gets garbage collected.
Exercises
Short Questions
1.
2.
3.
4.
5.
6.
7.
8.
9.
220
DCS 115
Long Questions
1.
2.
3.
4.
5.
6.
NOTES
Programming Exercises
1. Create a class in Java to implement a Stack
2. Create a class called Product with prod_name, prod_id, cost, quantity as
data members create necessary methods and constructers for the class
3. Implement the inheritance scheme given below in Java.
Answers to Have you Understood Questions
Section 11.3
1. Classes are the basic building blocks of Java programs. Classes are
called as Abstract Data Type (ADT) .Classes describes the structure of
the object.
2. java.lang.object
3. Objects are the run time instance of a class. Classes describe objects.
4. [modifiers] return_type <method_name> (parameter_list)
[throws_clause ]
{
//method body
}
4. A method without implementation must be declared as abstract.
Section 11.4
1. Constructors are special type of methods that are invoked when we
create objects for the classes. Constructers will have the same name as
that of the class.
2. Constructors cannot be made abstract, final, native, static, or synchronized and it cannot have return type.
Section 11.5
1. The private access specifier , The public access specifier ,The protected
access specifier
221
DCS 115
NOTES
2. friendly scope.
Section 11.6
1. When two or more methods share the same name but differ in their
signature, they are said overloaded.
2. Constructer overloading is a concept in which you have multiple
constructers that differ either in type of their arguments or the number
of their arguments or both.
Section 11.7
1. static variables are common all the instances of the class, static variables
can also be
called as class variables for a static data member there
will be only one copy of the class member shared by all objects of the
class A static data member is like a global variable, but has class-level
scope.
2. (1) A static method can access only static data and can call only other
static methods. A non-static member function can access all of the above
including the static data member. (2) A static method can be called, even
when a class is not instantiated, a non-static member function can be called
only after instantiating the class as an object.
3. By calling Math.sqrt() function.
Section 11.8
1. Inheritance is a feature by which new classes are derived from the
existing classes The two forms of inheritance are (1) class inheritance
(2) interface inheritance.
2. (1) Single (2) Multilevel (3) Hierarchical
3. Java uses a unique keyword called super to call the super class
constructers.
4. super() or super(parameters)
Section 11.9
1. If you include a method definition that has the same name and exactly
the same number and types of parameters as a method already defined
in the super class, this new definition replaces the old definition of the
method. This concept is called method overriding.
Section 11.10
1. (a) To call a superclass constructer (b) To call a superclass method over-
222
DCS 115
ridden by the subclass method (c) To refer the superclass variable from the
subclass.
NOTES
Section 11.11
1. By prefixing the method declaration with abstract.
2. No
Section 11.12
1. By declaring the variables as final.
2. Final keyword can be used with variables, methods and classes
3. The purpose of finalize () method is to release system resources before
the object gets garbage collected
References
1.
2.
http:\\www.sun.com
3.
Thinking in Java
Author: Bruce Eckel
Publisher : Prentice Hall 2000
4.
5.
6.
Java in a Nutshell
Author:David Flanagan
Publisher :OReilly1999
223
DCS 115
NOTES
CHAPTER 12
ARRAYS AND VECTORS
Arrays
Initializing a Two Dimensional Arrays
Java Array Declaration
Vectors
Java Array Initialization
Vector Creation
Two Dimensional Arrays
Methods in Vector
12.1 Introduction
This Chapter introduces you to understand two important and frequently used
data structures in Java The first data structure this chapter introduces to you is
Arrays. You have already learnt about arrays in C++. Like C++ arrays in Java are
used to hold values that are of the same type, but however Java handles arrays in
a different manner. The creation and processing of arrays are discussed in detail
in this chapter.
The second important data structure discussed in this chapter is the vector. Vector
is a class available in the java.util package. Vectors are commonly used instead
of arrays. Vectors in Java is used to create a generic and dynamic array that hold
objects of any type. The creation and processing of vectors are discussed in detail
in this chapter.
12.2
Learning Objectives
To introduce the concept of arrays
To show how to declare ,initialize and process single dimensional array
To show how to declare ,initialize and process two dimensional array
To introduce the concept of vectors
To show how to declare a vector
To discuss various methods available in vector class.
224
DCS 115
12.3
Arrays
NOTES
Arrays are data structures used to hold values that are of the same type. Arrays are
fixed-length structures for storing multiple values of the same type. An array
implicitly extends java.lang.Object so an array is an instance of Object. The structure of java arrays is shown below.
The array a shown in the diagram has nine elements. Like C, C++ the index of
an array in java starts with zero. All the elements in an array as accessed with the
help of array index. The notation a[i] refers to the i-th element of the array.
12.3.1
An array variable is declared in the same way that any Java variable is declared.
It has a data type and a valid Java identifier. The data type is the type of the
elements contained in the array. The [] notation is used to denote that the variable
is an array. Java has a unique way of declaring array.
1
2
3
4
int data[];
data=new int[50];
int[] data;
data=new int[50];
int[] data=new int[50];
int data[]=new int[50];
All the four statements declare an one dimensional array called data with the size
50. Similarly we can declare array for various data types. Some examples
1
2
12.3.2
String args[]
double points[]
Java Array Initialization
Once an array is declared we can initialize it with some initial values. The syntax
is
type arrayname[]={list of values };
225
DCS 115
NOTES
For example
int data[] = { 5,10,15,20,25 };
When we initialize an array, we will not specify the size of the array. The java
compiler automatically calculates the size the array.
Example 1:
The following program computes the sum and average of an array
class Array
{
public static void main(String args[])
{
int data[]= { 5,10,15,20,25 };
int sum=0;
double avg;
for(int i=0;i<data.length;i++)
sum+=data[i];
avg=sum/data.length;
System.out.println( The Sum of the Array is +sum);
System.out.println( The Average of the Array is +avg);
}
}
Output of the Program
The Sum of the Array is 75
The Average of the Array is 15
NOTE:
The size of the array can be found using the variable length. In the
previous example data.length returns the length of the array data.
Example 2:
A simple bubble sort algorithm using single dimensional array is illustrated below.
class Bubble
Anna University Chennai
226
DCS 115
NOTES
DCS 115
NOTES
Example 3:
The below program performs transpose of a 3x3 matrix.
class Transpose
{
public static void main(String args[])
{
int[][] a = { {1,2,3}, {4,5,6}, {7,8,9} };
int [][] b=new int[3][3];
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
{
b[i][j]=a[j][i];
}
System.out.println(Transpose Of the Matrix is );
for (int i=0;i<3;i++)
Anna University Chennai
228
DCS 115
NOTES
What is an Array ?
Arrays in java extend _________
How will you access 10th element of an array a?
Write the statement to declare an integer array k with 50 elements.
How will you initialize 2D array?
Vectors
Vector is a class available in the java.util package. Vectors are commonly used
instead of arrays, because they expand automatically when new data is added to
them. Vectors can hold only Objects and not primitive types (eg, int). If you want
to put a primitive type in a Vector, you have to convert the primitive type to object
and then add it to the vector.
You must import either import java.util.Vector; or import java.util.*; to work
with the vector. Vectors are implemented with an array, and when that array is full
and an additional element is added, a new (bigger) array must be allocated and
copy the elements from the old array to the new array, if you knew the final size,
it is better to use an array but however if you want to create an array that dynamically grow and shrink in size,Vector is a better choice.
12.4.1 Vector Creation
To create a Vector Java supports two types of constructers. The first constructer
creates a vector with a default size 10. The general form is
Vector v=new Vector();
Here v is the object of type vector.The second form of constructer creates a vector
with a specified size. The general form is
Vector v=new Vector(30);
229
DCS 115
NOTES
The constructer given above creates a vector with an initial size 30.
12.4.2 Methods in Vector
Vector class in java supports many methods. Some important methods available
in Vector class are tabulated in the Table 12.1.
Method
Description
v.add(o)
v.add(i, o)
v.clear()
v.contains(o)
v.firstElement()
v.get(i)
v.lastElement()
v.listIterator()
v.remove(i)
Removes the element at position i, and shifts all following elements down.
v.set(i,o)
v.size()
v.toArray(Object[])
230
DCS 115
To get the elements from the Vector, You have to use the ListIterator class. This
class supports two important methods to access Vector elements. They are
NOTES
hasNext(), this method returns true ,if the Vector object still has some
more elements.
next() , this method returns the next available element present in the
Vector object.
Example 4:
This example program makes use of some commonly used vector methods
import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
Vector v=new Vector();
v.add(new Integer(10));
v.add(new Double(55.10));
v.add(new String(Vector));
v.add(new Integer(100));
System.out.println( The First Element is +v.firstElement());
System.out.println( The Last Element is +v.lastElement());
System.out.println( The Size of the Vector is +v.size());
System.out.println( Vector Elements is );
ListIterator i=v.listIterator();
while(i.hasNext())
{
System.out.println(The Element is +i.next());
}
System.out.println(Removing Second Element + v.remove(2));
System.out.println(Adding a New Element in Third Position);
v.add(new String(JAVA));
System.out.println(The New Set of Elements);
i=v.listIterator();
while(i.hasNext())
{
System.out.println(The Element is +i.next());
}
}
}
231
DCS 115
NOTES
Summary
Arrays are data structures used to hold values that are of the same type.
Arrays are fixed-length structures for storing multiple values of the
same type.
Like C, C++ the index of an array in java starts with zero.
The [] notation is used to denote that the variable is an array.
To declare two dimensional arrays you need two dimensions. The first
dimension represents the row size the second dimension represents the
column size.
Anna University Chennai
232
DCS 115
NOTES
Exercises
Short Questions
1. Write the different ways of creating an Array
2. How will you initialize a 1D array
3. Is the following array declaration correct?
int[][] a=new int[5][]
4. What is Vector?
5. Write the syntax of remove() method.
6. What is the purpose of contains() method?
Long Questions
1. Explain how arrays are declared and handled in Java
2. What is Vector? How it is created? Explain few methods available in
Vector
Programming Exercises
1. Write a program to perform matrix multiplication
2. Write a program to check whether a given matrix is upper triangular
3. Write a program to a create a vector of size 10 and perform the following operations
(a) add two float numbers
(b) add a string and then two integers
(c) remove the fourth element
(d) find the size
(e) print the first and last element
(f) display the content of the vector
233
DCS 115
NOTES
2.
http:\\www.sun.com
3.
Thinking in Java
Author: Bruce Eckel
Publisher : Prentice Hall 2000
4.
5.
6.
Java in a Nutshell
Author:David Flanagan
Publisher :OReilly 1999
234
DCS 115
NOTES
CHAPTER 13
STRING HANDLING
13.1
String Class
Methods for Type Conversion
Methods for Comparing and Concatenation of Strings
Miscellaneous methods
Methods for Handling Individual Characters
StringBuffers
Methods for Searching Strings
Creation of StringBuffer
Methods for Extracting Substrings
Methods in StringBuffer
Methods for Case Conversion
Introduction
Learning Objectives
To introduce String class in Java
To discuss methods used for comparing and concatenation of Strings
To present methods for handling individual characters
To show methods for searching Strings
To discuss methods for extracting substrings
To show methods used for case conversion
To discuss miscellaneous String handling methods
To discuss methods used for Type Conversion
235
DCS 115
NOTES
String str=Hello
String str=new String(Hello );
char str[]={H,e,l,l,o};
The String class in java supports a variety of methods to process strings. The
class String includes methods for handling individual characters of the string, for
comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase,
for representing objects and other data types as strings, for converting strings to
bytes. Some frequently used methods in String class are given below.
13.3.1
Strings in java can be compared using the = operator and equals() method. In java
Strings can be concatenated using + operator and concat() method.
Example 1:
The following code performs comparision and concatenation of strings
class example1
{
public static void main(String args[])
{
String s1=Java;
String s2=Java;
String s3=C++;
String obj=new String(Java);
if(s1==s2)
System.out.println(s1 and s2 are Equal);
else
System.out.println(s1 and s2 are not Equal);
if(s1==obj)
System.out.println(s1 and obj are Equal);
else
Anna University Chennai
236
DCS 115
NOTES
if(s1.equals(obj))
System.out.println(Now !! s1 and obj are Equal);
else
System.out.println(s1 and obj are not equal);
System.out.println(s1 + s3 =+s1+s3);
System.out.println(s2 + s3 =+s2.concat(s3));
}
}
Output of the Program
s1 and s2 are Equal
s1 and obj are not Equal
Now !! s1 and obj are Equal
s1 + s3 =JavaC++
s2 + s3 =JavaC++
13.3.2
The Table 13.1 list all the methods to handle individual characters
Method
Purpose
charAt(intindex)
getChars(intsrcBegin,intsrcEnd,
char[]dst,intdstBegin)
indexOf(intch)
indexOf(intch, intfromIndex)
lastIndexOf(intch)
237
DCS 115
NOTES
Purpose
startsWith(Stringprefix)
238
DCS 115
Example 3:
NOTES
13.3.4
Purpose
substring(intbeginIndex)
substring(intbeginIndex,
DCS 115
NOTES
13.3.5
The Table 13.4 list all the methods to convert the case of a character
Method
Purpose
toLowerCase()
toUpperCase()
240
DCS 115
13.3.6
NOTES
The Table 13.5 list all the methods to convert the data type
Table 13.5 Methods to perform type conversion
Method
Purpose
valueOf(type)
getBytes(Stringenc)
Example 6:
The following performs type conversion
class example6
{
public static void main(String args[])
{
String str=This is a test;
int i=100;
System.out.println(Bytes Representation +str.getBytes());
System.out.println(String value of integer 100 : +String.valueOf(i));
}
}
241
DCS 115
NOTES
13.3.7
Miscellaneous methods
Purpose
trim()
length()
Example 7:
The following program finds the length of the string an eliminates white space from the
front and the end of a String.
class example7
{
public static void main(String args[])
{
String str=JAVA ;
str=str.trim();
System.out.println(Length of the String is +str.length());
}
}
StringBuffers
StringBuffer class is a mutable class unlike the String class which is immutable. Both the
size and character string of a StringBuffer can be changed dynamically. String buffers
are preferred when frequent modification of character strings is involved like appending,
Anna University Chennai
242
DCS 115
NOTES
in terms of computational complexity and memory space hence StringBuffer class must
be used only in situations where String class cannot be used. Strings can be obtained
from string buffers.
13.4.1
Creation of StringBuffer
//Default Capacity 16
The first constructer creates a StringBuffer that has the storage capacity to store
100 characters. The second constructer creates a StringBuffer that has the default
storage capacity to store 16 characters. The last constructer creates a StringBuffer
with a String parameter, it creates a StringBuffer with a capacity 24 i.e default
capacity + 8 (the length of String parameter).
13.4.2 Methods in StringBuffer
StringBuffer supports many methods that are available in String Class, apart from
that StringBuffer supports some unique methods. The Table 13.7 list some frequently used methods.
Method
Purpose
capacity()
length()
toString()
DCS 115
NOTES
reverse()
append(String str)
Example 8:
The following illustrates the various StringBuffer methods.
public class StringBufferMethods
{
public static void main(String[] args)
{
//Examples of Creation of Strings
StringBuffer strBuf1 = new StringBuffer(APPLE);
StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100
StringBuffer strBuf3 = new StringBuffer();
//Default Capacity 16
//Print the Capacity of StringBuffers
System.out.println(strBuf1 capacity : +strBuf1.capacity());
System.out.println(strBuf2 capacity : +strBuf2.capacity());
System.out.println(strBuf3 capacity : +strBuf3.capacity());
//toString Method
System.out.println(strBuf1 toString() is : +strBuf1.toString());
//append Method
strBuf2.append(HandBook);
System.out.println( strBuf2 is appended with :+
strBuf2.toString());
//insert Method
strBuf2.insert(1, A);
System.out.println(strBuf2 when A is inserted at 1 :
+strBuf2.toString());
strBuf2.insert(2, n);
System.out.println(strBuf2 when n is inserted at 2 :
Anna University Chennai
244
DCS 115
+strBuf2.toString());
NOTES
//delete Method
strBuf2.delete(2, n);
System.out.println(strBuf2 when n is deleted at 2 :
+strBuf2.toString());
//reverse Method
strBuf2.reverse();
System.out.println(Reversed strBuf2 : +strBuf2);
}
}
Output of the Program
strBuf1 capacity : 21
strBuf2 capacity : 100
strBuf3 capacity : 16
strBuf1 toString() is : APPLE
strBuf2 is appended with :HandBook
strBuf2 when A is inserted at 1 : HAandBook
strBuf2 when n is inserted at 2 : HAnandBook
strBuf2 when n is deleted at 2 : HA
Reversed strBuf2 : AH
Summary
Handling character strings in Java is supported through two final
classes: String and StringBuffer.
The String class implements immutable character strings, which are read-only
once the string has been created and initialized, whereas the StringBuffer
class implements dynamic character strings.
Strings in Java are 16-bit Unicode
Strings in java can be compared using the = operator and equals() method.
245
DCS 115
NOTES
246
DCS 115
NOTES
2.
http:\\www.sun.com
3.
Thinking in Java
Author: Bruce Eckel
Publisher : Prentice Hall 2000
247
DCS 115
NOTES
4.
5.
6.
Java in a Nutshell
Author:David Flanagan
Publisher :OReilly 1999
248
DCS 115
NOTES
CHAPTER 14
I N T E R F A C E S
14.1
Some languages support multiple inheritance in which a child class may derive
some of its features from more than one parent class. This feature is not directly
supported by java. However, java does provide a mechanism called an interface
whereby the properties of one class can be used by another without formal inheritance. This chapter introduces you to interfaces and its relative components. You
will learn about the differences between classes and interfaces. This chapter then
introduces you how to define and implement an interface. Finally interface inheritance is discussed in this chapter.
14.2
1
2
3
4
5
14.3
Learning Objectives
To introduce interface concept in Java
To present the difference between an interface and a class
To show how to define an interface
To discuss how to implement an interface
To introduce interface inheritance concept.
Interfaces and Classes
Interfaces are used to define a standard behavior that can be implemented by any
class in a class hierarchy. An interface declares a set of methods with their signatures. These methods will not have implementation part hence all the methods
declared in an interface are abstract methods. All the methods in the interface are
public by default. An interface can also have set of instance variables however all
these variables are constant by default.
249
DCS 115
NOTES
Interfaces are almost similar to classes but however there exist few differences
between them. These differences are listed in a Table 14.1.
S/N INTERFACES
CLASSES
1.
2.
3.
4.
5.
Defining an Interface
250
DCS 115
14.3.2
Implementing Interfaces
NOTES
After creating an interface we can create classes that implement the interface. A
class that is implementing a interface should have the following properties.
1
2
A class that implements the interface must override all the methods
present in the interface
If a class overrides only a partial set of methods in the interface then in
that case the class must be declared as abstract
The general syntax for a class that implements an interface is given below.
[accessmode] class classname [extends superclass] implements
interface1,interface2.
{
//body of the class.
}
An example is given below
class tick implements clock
{
public void getCurrentTime()
{
//body of the method.
}
public void setCurrentTime()
{
//body of the method.
}
public void showClock()
{
//body of the method.
}
}
Example 1:
A simple example is given below that give complete details about how to create
and make use of an interface.
interface arithmetics
{
public int result;
251
DCS 115
NOTES
}
252
DCS 115
NOTES
DCS 115
xvalue=a;
}
void disp()
{
System.out.println(XVALUE IS +xvalue);
System.out.println(YVALUE IS +yvalue);
NOTES
}
public static void main(String args[])
{
client obj=new client();
obj.getx(10);
obj.gety(10);
obj.disp();
}
}
Have you understood?
1.
2.
3.
4.
254
DCS 115
NOTES
An interface can also inherit properties of more than one interface. In this case
also we have to use the keyword extends. Here is the example
Example 4:
In this program the interface inf3 inherits the properties of inf1 and inf2
interface inf1
{
public void meth1();
}
interface inf2
{
public void meth2();
}
interface inf3 extends inf1,inf2
{
public void meth3();
}
class client implements inf3
{
255
DCS 115
client()
{
NOTES
256
DCS 115
NOTES
int BAD=0;
int GOOD=1;
}
class test implements constants
{
int mark;
ex1(int a)
{
mark=a;
}
int check()
{
if(mark>=50)
return GOOD;
else
return BAD;
}
public static void main(String args[])
{
test e=new test(77);
int x=e.check();
if(x==GOOD)
System.out.println(Well Done !!!!);
else
System.out.println(Better Luck Next Time !!!!);
}
}
Have you understood?
1. An interface is having only final variables then these variables can act
as____________
Summary
1
Interfaces are used to define a standard behavior that can be
implemented by any class in a class hierarchy. Interfaces are used to
achieve multiple inheritance
2
All the methods in an interface are public methods and all the
variables are final.
257
DCS 115
NOTES
A class that implements the interface must override all the methods
present in the interface
A class can implement more than one interface
An interface can inherit the properties of another interface
An interface can also inherit properties of more than one interface. In
this case also we have to use the keyword extends.
The final variables in interface can act as shared constants.
Exercises
Short Questions
1.
2.
3.
4.
258
DCS 115
Section 14.4
NOTES
2.
http:\\www.sun.com
3.
Thinking in Java
Author: Bruce Eckel
Publisher : Prentice Hall 2000
4.
5.
6.
Java in a Nutshell
Author:David Flanagan
Publisher :OReilly 1999
259
DCS 115
NOTES
CHAPTER 15
PACKAGES
15.1 Introduction
Code reuse is an import concept in object-oriented programming. One tool that
can help us increase the reusability of our code is the package statement. Programmers bundle groups of related types into packages. A Java package is a mechanism for organizing java classes and interfaces. Packages are also called as containers of classes.Java packages can be stored in compressed files called JAR
files, allowing classes to download faster as a group rather than one at a time.
Programmers also typically use packages to organize classes belonging to the
same category or providing similar functionality.
A package in java can contain the following members
Classes
Interfaces
Enumerations
Annotations
This chapter introduces you to both the categories of packages. You will also
learn how to create your own package and use it in your programs. This chapter
also presents the various access specifiers used in the package.
260
DCS 115
15.2
15.3
Learning Objectives
NOTES
Java langauage has a rich set of built in API packages from which you can access
interfaces and classes, and then fields, constructors, and methods.The Figure 15.1
gives the list of Java API packages.
lang
io
util
image
JAVA
awt
applet
peer
net
261
DCS 115
NOTES
java.io
Package that provides classes to manage input and output streams to read
data from and write data to files, strings, and other sources.
java.util
Package that contains miscellaneous utility classes, including generic data
structures, bit sets, time, date, string manipulation, random number generation, system properties, notification, and enumeration of data structures.
java.net
Package that provides classes for network support, including URLs, TCP
sockets, UDP sockets, IP addresses, and a binary-to-text converter.
java.awt
Package that provides an integrated set of classes to manage user interface components such as windows, dialog boxes, buttons, checkboxes,
lists, menus, scrollbars, and text fields. (AWT = Abstract Window Toolkit)
java.awt.image
Package that provides classes for managing image data, including color
models, cropping, color filtering, setting pixel values, and grabbing snapshots.
java.awt.peer
Package that connects AWT components to their platform-specific implementations (such as Motif widgets or Microsoft Windows controls).
java.applet
Package that enables the creation of applets through the Applet class. It
also provides several interfaces that connect an applet to its document
and to resources for playing audio.
15.3.1 Using Java API Packages
In Java packages are organized in a hierarchical structure. The Java Package name
consists of words separated by periods. The first part of the name contains the
262
DCS 115
name java. The remaining words of the Java Package name reflect the contents of
the package. The Java Package name also reflects its directory structure. For
example the statement
NOTES
java.awt
represents the awt (Abstract Window Toolkit) package. As mentioned earlier the
first part of the package name starts with the word Java. The second part of the
package name awt stands for the contents of the package, in this case the Abstract Window Toolkit.
To import a class from the package into our program you have to use the import
statement. The syntax is
import packagename.classname
or
import packagename.*;
1. The first form of the syntax imports the specific class from the package
.For example the statement import java.util.Date imports the Date class
available in the java.util package into our program.
2. The second form of the syntax import all the classes available in the specified package. For example java.io.* will import all the classes available
in the io package.
It is always good to import only the classes you need. Bringing in an entire package does not alter the size of the class file, but does lengthen the compile time.
Have you understood?
1. What do you mean by a Package?
2. Mention the two types of packages available in Java.
3. Which statement you will use to import a package to your program?
15.4
You know that java supports a rich set of built in packages. Apart from these
packages Java allows us to create our own user defined packages. We can create
our own package and use it in our programs. Creation of package in java is easy.
The various steps involved in creation of package are listed below.
1. The package has to be declared at the beginning of the program. The syntax is
package packagename;
263
DCS 115
For example
NOTES
2.
3.
4.
5.
package mypack;
The second step is to define classes and interfaces and put it inside the
package. A package can contain any number of classes; however one of
the classes should have the public access specifier. For example
package mypack
public class sample
{
//body of the class
}
Add methods and variables to class as required
Create a subdirectory with name of the package and put it under the current working directory.
Save the class in the subdirectory and compile the program.
Example 1:
A simple program to illustrate the creation of user-defined package is given below.
package mypack;
public class sample
{
public sample()
{
System.out.println(This is from the constructer);
}
public void test()
{
System.out.println(This is from the package mypack);
}
}
Create a directory with the name mypack and put inside the current working directory. Save the program with the name sample.java put in the sub directory
mypack and compile the program. Once a package is created, you can import the
package and use it in your program. Consider the code listing given below.
import mypack.sample
class Client
{
public static void main(String args[])
{
Anna University Chennai
264
DCS 115
NOTES
}
}
The program Client imports the classes from package mypack. The program
Client.java should be saved in the directory for which mypack is a subdirectory.
After that compile and execute the program
Output of the Program
This is from the constructer
This is from the package mypack
Example 2:
In Java it is possible to access a class in one package from another package.
package pack1;
class base
{
public String str=JAVA;
protected int i=20;
public void print_string()
{
System.out.println(The String is +str);
}
public void print_int()
{
System.out.println(The Integer is +i);
}
}
The class base is available in the package pack1. Now lets create another package pack2 which contains a class that access the class base
package pack1;
import pack1.*;
class X
{
265
DCS 115
NOTES
}
Thus in Java it is possible to access a class in one package from another package.
yes
yes
yes
yes
no
yes
yes
yes
no
yes
yes
yes
no
no
Yes/No *
yes
no
no
no
yes
Note:
Class subB has access only to the inherited from Base protected
elements, i.e. its own elements, but the protected data of other Base instances
is not accessible from SubB.
266
DCS 115
Example 3:
NOTES
This example program illustrates the access rights for different scopes available
in java.
Consider a class base available in the package pack1.
package pack1;
public class Base
{
public String publicStr = public ;
protected String protectedStr = protected
String defaultStr = default;
private String privateStr = private
267
DCS 115
NOTES
268
DCS 115
NOTES
Hiding Classes
When a package is imported to your program all the public classes will be imported to your program. Sometimes it may be desired to hide some classes in the
package because accessing them may lead to some problems. To hide such classes
these classes must be declared with a access specifier other than public. These
non public classes will be hidden when the package is imported to another program. Consider the example
package pack1;
public class Publicclass
{
//body of the class
}
class Defaultclass
{
//body of the class
}
In this example the class Publicclass with the public scope is visible to programs
importing the package pack1. The class Defaultclass with no access specifier is
hidden to programs importing the package pack1. Thus,
269
DCS 115
NOTES
import pack1.*;
class test
{
public static void main(String args[])
{
Publicclass p1;
//OK
Defaultclass d1;
//ERROR
..
..
}
}
Have you understood?
1.
Summary
A Java package is a mechanism for organizing java classes and interfaces. Packages are also called as containers of classes.
A package in java can contain classes,interface,enumerations and annotations
The Java Package name consists of words separated by periods. The
first part of the name contains the name java. The remaining words of
the Java Package name reflect the contents of the package
To import a class from the package into our program you have to use
the import statement.
A package can contain any number of classes; however one of the
classes should have the public access specifier.
A private variable cannot be accessed by a sub class even if the subclass resides in the same package
In a subclass of another package only public and protected variables
are accessible.
Only public variables are accessible by a non subclass residing in some
other package.
These non public classes in a package will be hidden when the package is imported to another program.
Exercises
Short Questions
1. List the members of a package
2. What is a JAR file?
Anna University Chennai
270
DCS 115
NOTES
Long Questions
1. Explain the various steps involved in creating a user defined package
2. Give a brief note on access specifiers applied to packages.
Programming Exercises
1. Create a package with a class called Bank. Add constructors and methods
to compute simple and compound interest. Import the package into another program and make use of the methods. Apply appropriate access
specifiers to the variables and methods.
Answers to Have you Understood Questions
Section 15.3
1. A Java package is a mechanism for organizing java classes and interfaces.
Packages are also called as containers of classes.
2. Buit in Packages (or) Java API packages and User defined packages
3. import statement
Section 15.4
1.Yes
2.public or protected
3.public.
Section 15.5
1. By making that class non public.
References
1.
271
DCS 115
NOTES
2.
http:\\www.sun.com
3.
Thinking in Java
A uthor: Bruce Eckel
Publisher : Prentice Hall 2000
4.
5.
6.
Java in a Nutshell
A uthor: David Flanagan
Publisher: O Reilly 1999
272
DCS 115
NOTES
CHAPTER 16
MULTITHREADED PROGRAMMING
16.1
Threads in Java
Sleep Method
Creating Threads
Yield Method
Extending Thread class
Stop Method
Implementing Runnable Interface
Thread Priority
Life Cycle of Thread
Synchronization
Thread Methods
Introduction
The earliest computers did only one job at a time. All programs were run sequentially, one at a time; and each had full run of the computer. However two programs couldnt be run at once. This kind of processing is called batch processing.
It is one of the earliest computing technologies
Time sharing systems were invented after batch processing to allow multiple people
to use the computer at the same time. On a time sharing system many people can
run programs at the same time. The operating system is responsible for splitting
the time among the different programs that are running.
Once systems allowed different users to run programs at the same time the next
step is to allow the same user run multiple programs simultaneously. Each running program (generally called a process) had its own memory space, its own set
of variables, its own stack and heap, and so on. The ability to execute more than
one task at the same time is called Multitasking.
The terms multitasking and multiprocessing are often used interchangeably, although multiprocessing sometimes implies that more than one CPU is involved.
In multitasking, only one CPU is involved, but it switches from one program to
273
DCS 115
NOTES
another so quickly that it gives the appearance of executing all of the programs at
the same time.
The systems terminology of multitasking is multithreading. In multithreading a
process is divided into two or more sub processes, these sub processes are allowed to execute simultaneously. For example a program, can print a file at the
same time it can downloads a page and formats the page as it downloads. Threads
are also called as lightweight processes. This chapter introduces to multithreaded
programming. You will learn how to create multiple threads in your program and
execute them simultaneously. This chapter also discuss about life cycle of a thread.
This chapter also introduces you to thread priority and synchronization.
16.2
1
2
3
4
5
6
7
8
16.3
Learning Objectives
To introduce thread concept
To present the two ways of creating threads
To show how to create threads by extending Thread class
To show how to create threads by implementing runnable interface
To discuss life cycle of thread
To discuss some thread methods
To present thread priority
To introduce synchronization concept
Threads in Java
274
DCS 115
interpreter performs switching of control between the running threads. This concept is known as context switching in a thread.
NOTES
MAIN THREAD
Start
Start
Start
CHILD
THREAD1
Start
CHILD
THREAD2
CHILD
THREAD3
CHILD
THREAD n
..
Creating Threads
To create threads, Java has a class called Thread and this class is available in the
java.lang package. Java supports two different ways of creating threads. They are
1
2
In both the cases we have to override the method called run(). The run() method
will contain the code required by the thread. The syntax of run() method is given
below.
public void run()
{
// body of method
}
275
DCS 115
NOTES
}
Step 3:
Create the object for the threaded class and start the thread using start() method.
For example
myclass mc=new myclass()
mc.start()
Example 1:
The following is a simple example for multithreaded program
class Two_table extends Thread
276
DCS 115
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println(i + * 2 = + i*2)
}
}
NOTES
}
class Three_table extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println(i + * 3 = + i*3)
}
}
}
class Four_table extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println(i + * 4 = + i*4)
}
}
}
class mainprg
{
public static void main(String args[])
{
Two_table two=new Two_table();
Two.start();
Three_table three=new Three_table();
Three.start();
Four_table four=new Four_table();
four.start();
}
}
The output of the program is given here.
277
DCS 115
NOTES
From the output we can note that all the three threads were executed simultaneously.
16.4.2 Implementing Runnable Interface
The next method of creating a thread is to create a class and making that class to
implement runnable interface. Since java does not support multiple inheritance
directly we often use runnable interface for creating threads. The various steps
for creating a multithreaded program in this method are listed below.
Step1:
Create a class that implements runnable interface. For example
class myclass implements Runnable
{
// Body of the class
}
278
DCS 115
Step 2:
NOTES
Override the run() method and write the code required by the thread
class myclass implements Runnable
{
}
Step 3:
Create the object for the Thread and pass the object of the class myclass as a
parameter. For example
myclass mc=new myclass()
Thread t=new Thread(mc);
Example 2:
The program given in the example1 is modified by implementing the runnable
interface.
DCS 115
for(int i=1;i<=10;i++)
{
System.out.println(i + * 3 = + i*3)
}
NOTES
}
}
280
DCS 115
NOTES
16.5
When a new thread is created it passes through various states before it gets terminated and this process is called the Life Cycle of the Thread. The following figure
shows the states a thread can pass in during its life and illustrates which method
calls cause a transition to another state.
281
DCS 115
NOTES
Runnable
Suspend
New Thread
Not Running
Start
Running
Notify
Once the Thread class is instantiated a new thread is created and its life
cycle begins
A newly created thread enters the active running state when the start()
method of the thread is invoked
A running thread may be blocked, when blocked it enters the inactive not
running state and waits until it is notified to run. A thread may be blocked
because
o It has been put to sleep for a set amount of time
o It is suspended with a call to suspend() and will be blocked until a
resume() message
o The thread is suspended by call to wait(), and will become runnable
on notify or notifyAll message.
Once the thread completes its run() method or when killed by some other
process it enters the dead state, that is the end of threads life cycle.
Have you understood?
1. What do you mean by life cycle of a thread ?
2. List out the various thread states ?
3. How will you make a suspended thread to run ?
16.6
Thread Methods
Apart from the start() and run() method, a thread class supports the following
methods that causes the state transition of a thread.
282
DCS 115
sleep() method
yield method()
stop() method
16.6.1
NOTES
Sleep Method
The sleep method is static and pauses execution for a set number of milliseconds,
here is an example of putting a Thread to sleep. The sleep method throws
InterruptedException. Here is an example for sleep method.
Example 3:
The following program illustrates sleep method of Thread class.
public class ThreadSleep extends Thread
{
public void run()
{
try
{
for(int i=0;i<5;i++)
{
this.sleep(1000);
System.out.println(looping for + i + time);
}
}catch(InterruptedException ie){}
}
public static void main(String args[])
{
ThreadSleep t = new ThreadSleep();
t.start();
}
}
16.6.2 Yield Method
Java Thread class has a static method called yield which causes the currently
running thread to yield its hold on CPU cycles. This thread returns to the ready
to run state and the thread scheduling system has a chance to give other threads
the attention of the CPU. If no other threads are in a ready to run state the thread
that was executing may restart running again. Here is an example for yield method
283
DCS 115
NOTES
Example 4:
The following program illustrates yield method of Thread class.
class ThreadYeild extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println(looping for + i + time);
if(i==4) yield();
}
}
}
16.6.3 Stop Method
Stop method in java forces the thread to stop executing.
Example 5:
The following program illustrates stop method of Thread class.
class ThreadStop extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println(looping for + i + time);
if(i==4) stop();
}
}
public static void main(String args[])
{
ThreadStop st=new ThreadStop();
st.start();
}
}
The output of the code is given below.
284
DCS 115
NOTES
Thread Priority
When a Java thread is created, it inherits its priority from the thread that created
it.Each Thread has a priority, ranging between Thread.MIN_PRIORITY and
Thread.MAX_PRIORITY (defined as 1 and 10 respectively). The higher the integer, the higher the priority. At any given time, when multiple threads are ready
to be executed, the runtime system chooses the Runnable thread with the highest priority for execution. Only when that thread stops, yields, or becomes not
runnable for some reason the lower priority thread start executing. If two threads
of the same priority are waiting for the CPU, the scheduler chooses one of them
to run in a round-robin fashion. Here are some important points regarding thread
priority.
By default, each new thread has the same priority as the thread that
created it. The initial thread associated with a main by default has
priority Thread.NORM_PRIORITY (5).
Example 6:
This program creates threads with different priorities.
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
285
DCS 115
System.out.println(i+ From A )
NOTES
}
}
}
class B extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(i+ From B )
}
}
}
class C extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(i+ From C)
}
}
}
class mainprg
{
public static void main(String args[])
{
A a=new A();
A.setPriority(Thread.MIN_PRIORITY);
a.start();
B b=new B();
b.setPriority(b.getPriority()+1);
b.start();
C c=new C();
c.setPriority(Thread.MAX_PRIORITY);
four.start();
}
}
286
DCS 115
NOTES
Synchronization
Generally in a multithreaded environment all the threads share some critical resources such as a block of code. In many situations these resources has to be
exclusively accessed, otherwise strange bugs can arise. Java provides a way to
lock the shared resources for a thread which is currently executing it, and making
other threads that wish to use it wait until the first thread is finished. These other
threads are placed in the waiting state.
To lock such shared resources java supports synchronization of threads i.e. providing an exclusive access to a thread currently accessing the shared resource.
Java has a keyword called synchronized that has to be prefixed before the method
declaration that contains the code to access the shared resource. For example
synchronized void access_resource()
{
//block of the code to be synchronized.
.
.
}
287
DCS 115
NOTES
288
DCS 115
NOTES
Exercises
Short Questions
1.
2.
3.
4.
5.
6.
7.
8.
Long Questions
1. Briefly explain the different ways of creating threads with examples
2. Explain the Life cycle of Threads
3. Explain the Synchronization concept
Programming Exercises
1. Create a multithreaded program by extending Thread classes. Create two
simultaneously executing thread , one thread to display hello and another
thread to display world
2. Create a multithreaded program by implementing the runnable interface.
Create two simultaneously executing thread , one thread to generate odd
numbers and another thread to generate even numbers
3. Modify program 2 by assigning priorities to threads.
289
DCS 115
NOTES
290
DCS 115
NOTES
References
1.
2.
http:\\www.sun.com
3.
Thinking in Java
Author: Bruce Eckel
Publisher : Prentice Hall 2000
4.
5.
6.
Java in a Nutshell
Author:David Flanagan
Publisher :OReilly 1999
291
DCS 115
NOTES
NOTES
292
DCS 115
NOTES
NOTES
293
DCS 115
NOTES
294