DCS115
DCS115
Information Technology
(DISTANCE MODE)
DCS 115
Object Oriented Programming
I SEMESTER
COURSE MATERIAL
Reviewer
Editorial Board
Copyrights Reserved
(For Private Circulation only)
ACKNOWLEDGEMENT
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
UNIT I
UNIT II
UNIT III
UNIT IV
UNIT V
TEXT BOOKS
REFERENCES
1. Herbert Schildt, “C++ : The Complete Reference”, Tata McGraw Hill, 1999.
2. Herbert Schildt, “Java 2 : The Complete Reference”, Fourth Edition, Tata McGraw
Hill, 2001.
3. Kamthane, A.N., “Object Oriented Programming with ANSI and Turbo C++, Pearson
Education, Delhi, 2003.
DCS 115 OBJECT ORIENTED PROGRAMMING
Page Nos.
CHAPTER 2 - FUNCTIONS 21
CONVERSIONS 65
CHAPTER 5 - INHERITANCE 83
Page Nos.
DCS 115 OBJECT ORIENTED PROGRAMMING
NOTES
CHAPTER 1
INTRODUCTION TO C++
PROGRAMMING
Structure of the Unit
1.1. Introduction
Since C++ is a superset of C, all elements of the C language are also contained
in the C++ language. Therefore, it is possible to write C++ programs that look just like
C programs. You can still use functions such as printf( ) and scanf( ), C++ I/O is
performed using I/O operators instead of I/O functions.
Example 1:
The following C++ program makes use of the basic Console I/O statements to read
and print two integer variables.
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
The end manipulator is similar to the newline character \n.Thus the statement
cout<<a<<endl<<b<<c<<,endl ;
will print the value of a,b and c in newline.
H E l l o
Apart from these manipulators C++ allows us to create our own manipulators.
1. The width of an integer variable has to bet set to 5.How will you set it?
2. Write the manipulator that will cause a line break.
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.
1.5.3 Constants
Constants refer to values that do not change during the execution of the program.
Examples for constants are
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 () [], ->, ., typeid, casts,
Right to left ! (negation), ~ (bit-not)
Right to left new, delete ++, —, - (unary) , * (unary), &
(unary), sizeof
Left to right *, /, % (modulus)
Signed integer:
The signed integer types are short int (abbreviation short), int and long int
(abbreviation long). Optionally the keyword signed can be used in front of these
definitions, e.g. signed int. The size of these variables depends on the
implementation of the compiler. The only rule for the length of short, int, long is:
short<= int<=long, i. e. they may have all the same size. Examples for signed
integer variable declarations are listed below.
int x,y
long int a;
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
Char 1 1
Short int 2 2
Int 4 4
Float 4 4
Double 8 8
long double 8 12
The members of the structures are accessed using dot operator. Example
a.x=10, b.x=20.
If a structure pointer is created then the members are accessed using -> operator.
For example
a->x=10 ,b->x=20.
A union is a user defined data type that may hold (at different times) objects of
different types and sizes, with the compiler keeping track of size and alignment
requirements. Unions provide a way to manipulate different kinds of data in a
single area of storage, without embedding any machine-dependent information in the NOTES
program.The syntax is based on structures:
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.
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 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 God’s Own Country”;
and
cin>>money;
if(money==rupees)
{
//do this
NOTES }
are perfectly valid.
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].
Pointers
A pointer is a variable that contains the address of a variable. Pointers in C++ are
declared and initialized as in C.
Examples
int a= 1, b= 2
int *ip; /* ip is a pointer to int */
ip = &a /* ip now points to a*/
b= *ip; /* bis now 1 */
*ip = 0; /* a is now 0 */
From these examples you can see that the declaration and usage of pointer in C and
C++ are similar. Pointers are extensively used in C++ for dynamic memory management
and to achieve run time polymorphism.
Functions
If-Else
The if-else statement is used for making decisions. The syntax is
if (expression)
statement1
else
statement2
True False
Expression
Statements Statements
Example
if(a>b)
c=a;
else
c=b;
Flow Chart
True False
a>b
C=a C=b
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
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
The last else part handles the default case where none of the other conditions is
satisfied.
Switch Statement
switch (expression)
{
case const-expr:
statements
switch(k)
{
case 1:
cout<< “ The value of k is 1” ;
break;
case 2:
cout<< “ The value of k is 1” ;
break;
case 3:
cout<< “ The value of k is 1” ;
break;
default:
cout<<” The value of k is other than 1,2,3” ;
}
Here based on the value of k case 1, case 2 or case 3 will be executed .I f the value
of k is other than 1, 2 and 3 then default case will be executed. The break statement
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
While Loop
Do…While Loop
For Loop
While Loop
NOTES statements ;
}
Example
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
expr1
while (expr2)
{
statement
expr3 ;
}
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.
Example NOTES
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 do-
while, 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);
Example
i=0; //initialization
do
{
cout<<i;
i+=2; //increment
}while(i<100); //condition.
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.
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.
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
i=i+2
in which the variable on the left side is repeated immediately on the right, can be
written in the compressed form
a+= 2
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
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.
Summary
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++.
Programming Exercises
1. Write a program to read a set of integers from the keyboard and determine
whether they are ODD or EVEN
2. Write a program to find the sum of the digits of an number
3. Write a program to generate prime numbers in the range 200-999
4. Write a program to count the number of negative numbers in an array
Section 1.3
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
NOTES 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.
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
NOTES
CHAPTER 2
FUNCTIONS
Function Prototypes Return by Reference
Functions with Return Values Inline Functions
Call by Value Functions with Default Arguments
Call by Reference Function Overloading
2.1 Introduction
NOTES
2.3.1 Function Prototypes
Example 1:
The program given below is a makes use of a simple function that takes a integer
parameter.
#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;
}
This program make use of a function called show( ) with an integer parameter .The NOTES
function just displays the value of x. Since the function is not returning anything its
return type is made void.
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;
}
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.
NOTES parameters. The main effect is that even if the dummy parameters are modified the
corresponding parameter will not change the argument’s 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;
}
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
Example 4:
The following program makes use of call by reference concept to swap the values
of two variables.
#include <iostream.h>
#include <math.h>
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;
}
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<<b;
}
Example 5:
#include<iostream.h>
#include<iomanip.h>
int & check(int & a,int &b)
{
if(a>b)
return a;
else
return b;
}
void main( )
{
int x,y;
cout<<”enter two values “ <<endl;
cin>>x>>y;
check(x,y)=0;
cout<<”After executing check function “<<endl;
cout<<x <<”\t”<<y;
}
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.
NOTES cin>>a;
if(even(a))
cout<<”EVEN NUMBER”;
else
cout<<”ODD NUMBER”;
}
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.
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.
The following point has to be noted while writing functions with default arguments.
int add(int x=100,int y,int z) //default parameters should be assigned from left to NOTES
right
int add(int x,int y=100,int z) //default parameters should be assigned from left to
right
Example 7:
#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);
}
Example 8:
The following example makes use of the function called simpleinterest with default
arguments
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;
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.
simply declare and define all required versions. The compiler will automatically select NOTES
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.
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:
#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;
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;
}
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:
#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,
NOTES Summary
Exercises
Short Questions
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)
1. The advantages of writing functions are (1) Functions provides Reusability (2)
Functions give modular structure to a program (3) Writing functions make
programming easy
2. The syntax to write a function is.
<return type> function name(argument list)
{
//BODY OF THE FUNTION.
}
3. In certain situations, it is more effcient or convenient to be able to modify
the argument(s). To do that, the & symbol specifies that the actual parameter
and dummy the argument correspond to the same value. This is called
passing an argument by reference.
4. By referencing the & symbol before the variable declaration.
Section 2.4
1. Inline functions are like macros. Inline functions will avoid the time
complexity that arises due to context switch over head in a function
call.
2. By prefixing the function declaration with inline keyword
Section 2.5
1. Right to left
Section 2.6
NOTES References
NOTES
CHAPTER 3
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.
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 doesn’t provide something like data hiding which is provided by
the classes
NOTES
Since class is specially designed user defined data type in C++ to bind data and code,
this book focus only on classes.
Class is another user defined data type in C++. A class is the definition of a data
structure and the associated operations that can be done on it .Classes in C++ are also
called as Abstract Data Type (ADT) .Classes bind the data with its associated code. In
C++, a class is declared using the class keyword. The syntax of a class declaration is
similar to that of a structure. Its general form is,
class class-name
{
- // private functions and variables
public:
// public functions and variables
} object-list;
In a class declaration the object-list is optional. Functions and variables declared inside
the class declaration are said to be members of the class. By default, all member
functions and variables are private to that class. This means that they are accessible
only by the members of that class. To declare public class members, the public keyword
is used, followed by a colon. All functions and variables declared after the public specifier
are accessible both by other members of the class and by any part of the program that
contains the class. For Example consider the class given below
class number
{
int a,b;
public:
void get_ab();
void put_ab()
};
This class has two private variable, called a and b, and two public functions get_ab( )
and put_ab( ). Notice that the functions are declared within a class using their prototype
forms. The functions that are declared to be part of a class are called member functions.
NOTES
3.4.1 Defining the Member Functions
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.
For example the function get_ab(),put_ab() of the number class can be written as.
void main( )
{
number ob1, ob2;//these are object of type number
// ... program code
}
Remember that an object declaration creates a physical entity of that type. That
is, an object occupies memory space, but a type definition does not.
Once an object of a class has been created, the program can reference its public
members by using the dot operator in much the same way that structure members are NOTES
accessed. The syntax for accessing the object is given below.
<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;
}
This program creates a class called number with two private data members
and three public member functions. The function get_ab() is an inline function.The
functions add() and mul() are written outside the class. The Program creates one
object called “ob1” through which the member functions are accessed.
Example 2:
#include<iostream.h>
#include<iomanip.h>
class number
{
private:
int a,b;
public:
void get_ab(int x ,int y) // member function with parameters
{
a=x;
b=y;
} NOTES
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;
}
};
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();
}
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;
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();
}
3.5 Constructors
Generally every object we create will require some sort of initialization. C++
allows a constructor function to be included in a class declaration. A class’s
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.
arguments. NOTES
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.
Example 4:
void number::show( )
{
cout << a;
}
void main( )
{
number ob; // automatic call to constructor
ob.show( );
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.
NOTES
3.5.1 Constructors That Take Parameters
It is possible to pass one or more arguments to a constructor function. Simply add
the appropriate parameters to the constructor function’s declaration and definition.
Then, when you declare an object, specify the arguments.
Example 5:
In constructor
Value of a is 4
number ob = number(4);
NOTES
Although the previous example has used a constant value, you can pass an object’s
constructor any valid expression, including variables.
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:
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;
}
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;
}
Default constructer
0
0
In one parameter constructor
5
0
In two parameter constructor
5
10
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.
Example 7:
{ 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;
}
In constructor
Value of a is 4
Copy Constructor
Value of a is 4
1. What is a constructer?
2. Is it possible to overload constructer?
Example 8:
number::number( )
{
cout << “In constructor\n”;
a=100;
}
number::~number( )
{
cout << “ In Destructor...\n”;
}
void number :: show()
{
cout<<”a is “<<a<<”\n”;
}
void main()
{ NOTES
number ob;
ob.show();
}
In constructor
A is 100
In Destructor...
1. What is a destructor?
2. Is it possible to overload destructor?
Objects can be passed to functions as arguments in just the same way that other
types of data are passed. Simply declare the function’s 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:
class number
{
int i;
public:
number(int n) { i = n; }
int product(number o1,number o2);
};
int number :: product(number o1,number o2)
{
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;
}
10
10
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:
#include<iostream.h>
class money
{
int rs;
int ps;
money()
{
rs=0;
ps=0;
}
Total Rupees 22
Total Paise 10
NOTES
3.8 Static Data Members
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 ();
3 objects
Example 12:
#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;
NOTES cout<<count;
}
Note:
The program has some compilation errors hence it will not run
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
};
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.
class sample
{
private:
——
——
public:
——
——
friend void callme( );
};
In the main program the friend function can be called as a ordinary function without
any objects.
void main()
{
sample s;
——-
NOTES ——-
callme( );
}
Example 13:
#include<iostream.h>
class one
{
private:
int a,b;
public:
one()
{
a=20;
b=30;
}
friend float avg(one obj);
};
float avg(one obj)
{
float r;
r=(obj.a+obj.b)/2;
return r;
}
void main()
{
one e;
float m;
m=avg(e);
cout<<” The Average is “<<m;
}
In this example the function avg( ) is declared as friend to the class one. As
mentioned earlier this friend function takes object as a parameter of type the class
“one”. Note that the definition of the function avg( ) is written like a ordinary
function this is because the friend function will not fall in the scope of the class
where it is defined. Finally the function is invoked without the help of the object.
NOTES
3.10.1 Friendly Function for Two Classes
To create friendly classes you need to create a function that is friend to both the
classes. Further you need to do forward declaration of the class that you are going
to define later.
Example 14:
NOTES }
friend float avg(c1 01,c2 02);
};
class c2
{
private:
int y;
public:
c2()
{
cin>>y;
}
friend float avg(ci 01,c2 02);
};
In this example the function avg( ) is declared as friend to the classes c1 and c2.
Since the class c2 is written after class c1 we have to forward declaration for c1.
The friend function avg( ) computes the average of the variables x and y declared
in classes c1 and c2 respectively. Since avg( ) is a friend function it is called
without the help of the object
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 class’s 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
there’s 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
Long Questions
1. Explain how objects can be passed and returned from a function with
an example
2. Explain the concept of constructer overloaing
3. Explain the concept of Friend functions with example.
4. Explain briefly regarding static data members and static functions.
Programming Exercises
Section 3.4
1. 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
2. Just by prefixing the keyword inline before the function prototype.
3. <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.
2. Yes NOTES
3. Copy constructer is used to copy the value of one object to another.
Section 3.6
Section 3.7
1. Value
Section 3.8
1. 0
2. Just by prefixing with the keyword static before variable declaration
3. True.
4. c1::fn()
Section 3.9
1. False
Section 3.10
References
NOTES
CHAPTER 4
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
4.1 Introduction
Almost all operators in C++ can be overloaded, except the following few operators.
return-type class-name::operator#(arg-list)
{
// operation to be performed
}
The return type of an operator function is often the class for which it is
defined ( however, operator function is free to return any type).
The operator being overloaded is substituted for #. For example, if the
operator + is being overloaded, the operator function name would be
operator +.
The contents of arg-list vary depending upon how the operator function is
implemented and the type of operator being overloaded.
There are two important restrictions to remember when you are overloading an
operator:
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 ;
}
};
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)
{ 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();
}
Total Rupees 22
Total Paise 10
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();
}
-10 -10
Similarly when overloading the postfix ++ operator we will write the member
function as
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.
Note:
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()
NOTES {
cout<<”The Object is Incremented to \n”;
cout<<x<<”\n”;
cout<<y;
}
};
Example 5:
The program given below overloads unary postfix — operator to decrement 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—( int );
void display()
{ NOTES
cout<<”The Object is Decremented to \n”;
cout<<x<<”\t”;
cout<<y;
}
};
int main( )
{
point o1(10, 10);
o1—; //decrement an object
o1.display();
}
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
NOTES {
int x,y;
public:
TestClass()
{
x = y = 0;
}
TestClass(int a, int b)
{
x = a;
y = b;
}
void show()
{
};
p = malloc(size);
if(!p)
{
cout<<“Unable to allocate”<<endl;
return;
}
return p;
}
Note:
Example 7:
#include <iostream.h>
class point
{
int x, y;
public:
point( )
{
x = 0; y = 0;
}
point(int i, int j)
{
x = i; y = j;
}
void display()
{
cout << “X IS : “ << x << “, Y IS : “ << y <<“\n”;
}
friend point operator+(point ob1, point ob2);
};
// Overload + using a friend.
point operator+(point ob1, point ob2)
{
point temp;
temp.x = ob1.x + ob2.x;
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
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.
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.
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.
This is done by using constructors in the respective classes. In these types the ‘=’
operator is overloaded.
Example 8:
class length
{
int cm,m;
public:
length(int n) //Constructor
{
m=n/100;
cm=m%100;
}
}
void main()
{
int n;
cin >> n;
NOTES }
The constructor used for type conversions take a single argument whose type is to
be converted.
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.
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;
}
void main()
{
time t1(160);
int n = t1; //Conversion
float x = t1; //Conversion
}
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
NOTES {
int x= m*100 + cm;
length2 tempobj(x);
return tempobj;
}
}
class length2
{
int cm;
public:
length2(int n)
{
cm=n;
}
operator length1() //from length2 type to length1 type
{
length1 tempobj(cm);
return tempobj;
}
}
void main()
{
int x= 125;
length2 obj1(x);
length1 obj2= obj1;
}
Summary
When you overload a unary operator using a member function, the function NOTES
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.
Exercises
Short Questions
Long Questions
Programming Exercises
Section 4.3
1. No
Section 4.4
References
NOTES
CHAPTER 5
INHERITANCE
Overview Of Inheritance Multiple Inheritance
Single Inheritance Multilevel Inheritance
Access Control Hierarchical Inheritance
Inheritance and Access Control Hybrid Inheritance
Inheritance in Private Mode Constructers and Destructors in
Derived Classes
Using Protected Members 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.
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. The parent
class(Original existing class) is said to be the base class the new made class from
it is called a derived class A class that is derived from parent class will posses all
the properties of the base class apart from that it also has its own unique properties.
However the derived class will not inherit constructers, destructors, friend functions
and assignment operators further derived classes cannot remove any data member
present in the base class.C++ supports various types of inheritance scheme. They
are
Single inheritance
Multiple inheritance
Multilevel inheritance
Hierarchical inheritance
Hybrid inheritance
1. What is Inheritance?
2. Mention the various inheritance schemes supported in C++.
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.
Base Class
Derived class
class base
{
——
——
};
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()
{
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.
number2( ) //constructer
void get_b()
void show_b() int b
void get_a()
void show_a( ) None.
An access specifier in C++ determines which data member, which member function
can be used by other classes. The three access specifiers supported in C++ are
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
#include<iostream.h>
}
};
class Derived :public Base
{
public:
void change()
{
privetInt++ //Wrong! Private variables cannot be
accessed
protectedInt++; //OK
publicvar++; //OK
}
}
void main()
{
Note:
The program has some compilation errors hence it will not run.
The Table 5.1 lists the visibility and access rights in C++.
The protection keyword after the ‘:’ operator in the derived class determines the
access by derived class to base class members. For example consider the following
scheme of inheritance.
All public members of the base class become private to the derived class,i.e. only
members of the derived class can access them. All private members of the base
class are private to the base class, i.e. nothing can access them, not even members
of the derived class. All protected members become also private to the derived
class.
All public members of the base class become protected, i.e. only the derived class
(and further derived classes) can access them. All private base class members are
89 Anna University Chennai
DCS 115 OBJECT ORIENTED PROGRAMMING
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.
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
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:
#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)
{
y = n; NOTES
}
void showy( )
{
cout << y << “\n”;
}
};
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:
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.
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:
Example 3:
#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()
{ NOTES
derived obj;
obj.get_a();
obj.get_b();
obj.product();
}
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++.
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, don’t even support
multiple inheritance) and should be avoided. However, sometimes it makes
programming easier. The multiple inheritance diagram is depicted below.
A B C
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
Example 4:
The following code contains the C++ classes for the multiple inheritance
diagram given in fig 5.3
PROMOTION
#include<iostream.h>
#include<iomanip.h>
#include<string.h>
class Expdet
{
protected:
char *name;
int tot_exp;
public:
void expr( )
{
cout<<”Enter your name”<<endl;
cin>>name;
cout<<”Enter Total Experience”<<endl;
cin>>tot_exp;
}
};
class Saldet
{
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( );
}
PERSON
EMPLOYEE
MANAGER
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;
}
The class manager is inherited from the class emp which in turn inherited from
class person .Thus the class emp and manager will posses the following features.
Class emp
void get1() (From person class) name, age (From person class) NOTES
void get2() basic,hra
Class manager
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.
B C D
In hierarchical inheritance it is necessary to create object for all the derived classes
at the lower level because each derived class will have its own unique feature.
Example 6:
#include<iostream.h>
#include<string.h>
class A
{
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;
}
}; NOTES
void main( )
{
B obj1;
C obj2;
D obj3;
B .get( );
B .add( );
C .get( );
C .mul( );
D .get( );
D .division( );
}
12 6
The Sum is 18
The Product is 72
The Quotient is 2.0
Here we can note that objects were created for all the subclasses to access their
member functions.
NOTES
Emp_det
Normal pay
Additional pay
Net pay
Example 7:
The C++ classes for the fig 5.6 are given below.
#include<iostream.h>
class emp_det
{
protected:
int emp_id;
public:
void get_id()
{
cout<<”ENTER EMPID”<<endl;
cin>>emp_id;
}
void disp_id()
{
cout<<” EMPID IS ”<<emp_id<<endl;
}
};
class norm_pay :public emp_det
{
protected:
float bpay;
public:
void get_bpay()
{
cout<<”ENTER BASIC PAY”<<endl;
cin>>bpay;
} NOTES
void disp_bpay()
{
cout<<” BASIC PAY IS = ”<<bpay<<endl;
}
};
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();
NOTES obj.get_addpay();
obj.disp_id();
obj.disp_bpay();
obj.disp_addpay();
obj.display();
}
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
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
class A NOTES
{
public:
A( )
{
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;
}
INSIDE A
INSIDE B
INSIDE C
EXIT C
EXIT B
EXIT A
C++ supports a unique way of initializing class objects when a hierarchy of classes
are created using inheritance. Constructers in an inheritance program can also be
written using the syntax given below.
Note that we have used a colon “:” immediately after the constructer name to
assign initial values. An example is given below.
Example 9:
#include <iostream.h>
#include<iomanip.h>
class A
{
int a;
public:
A (int x )
{
a=x;
cout<<”INSIDE A”;
cout<<” a is “<<a<<endl;
}
~A ( )
{
cout<<”EXIT A”;
}
}; NOTES
class B
{
int b;
public:
B(int y) : b(y)
{
cout<<”INSIDE B”;
cout<<” b is “<<b<<endl;
}
~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);
}
INSIDE A
a is 10
INSIDE B
B is 40
INSIDE C
m is 30 n is 40
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.
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.
Exercises NOTES
Short Questions
Long Questions
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
BOOK DETAILS
AUTHOR DETAILS
PUBLISHER DETAILS
NOTES 3. Implement the inheritance scheme given below with a C++ program
Device
Vehicle
Cars Trucks
Section 5.4
1.
Base Class
Derived class
1. private
2. FALSE
3. Protected
4. private, protected and public
Section 5.6
1. If a derived class directly inherits from more than one base class.then
this scheme of inheritance is said to be multiple inheritance.
2. 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.
NOTES References
6. Thinking in C++
Author: Bruce Eckel
Publisher : Prentice Hall 2000
NOTES
CHAPTER 6
POLYMORPHISM
Binding Virtual Base Classes
Virtual Functions Pure Virtual Function
Virtual Destructors Abstract Classes
6.1 Introduction
6.3 Binding
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”;
}
}; NOTES
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
}
I AM IN BASE
I AM IN BASE
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()
{
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.
A virtual function will be usually called with the help of a pointer. NOTES
A virtual function in the base class must be declared even when no
definitions can be made possible.
Each object with virtual function(s) is provided with a Function Lookup Table.
This table contains information about the virtual functions and is used to determine,
which function is to be called. However, there is only one table for each class and
each object of this class gets a pointer to this table. If a virtual function is
overridden, the pointer in the table points to the derived class function. If it is not
overridden, it points to the base class version.
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.
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.
NOTES
A
B2
B1
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
The key part of this declaration is the setting of the function equal to 0. This tells
the compiler that no body exists for this function relative to the base class. When
a virtual function is made pure, it forces any derived class to override it. If a
derived class does not, a compile-time error results. Thus, making a virtual function
pure is a way to guaranty that a derived class will provide its own redefinition.
Any (non-virtual) class that is derived from an abstract class must implement all
pure virtual functions of the base class. Otherwise it is a virtual class itself. The
following is the example of an abstract class.
Once the abstract class is created the class inheriting it should override all the
pure virtual functions. For example
Summary
Exercises NOTES
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
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.
Section 6.5
1. If we declare the base class as virtual to ensure that all the sub classes
share the same object of the base class
2. They can appear in either order.
Section 6.6
6. Thinking in C++
Author: Bruce Eckel
Publisher : Prentice Hall 2000
NOTES
CHAPTER 7
FILES
File Stream Operations Input And Output Operations With
Binary Files
File I/O Reading And Writing Objects In A
Binary File
Sequential Input And Output Error Handling In File Operations
Operations
Random Access Files
7.1 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.
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
IOSTREAM
1. What is a stream ?
2. What are the two types of streams?
have access to all operations defined by ios. In C++, a file is opened by linking it NOTES
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.
Examples
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
NOTES converted into newlines. However, when a file is opened in binary mode, no
such character translations will occur
ios::trunc: causes the contents of a pre-existing file by the same name to be
destroyed and the file to be truncated to zero length. When you create an
output ios::trunc: causes the contents of a pre-existing file by the same name
to be destroyed and the file to be truncated to zero length. When you create an
output stream using ofstream, any pre-existing file is automatically truncated.
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
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();
}
To view the outputs from file go to command prompt and type the command given NOTES
below.
c:\tc\bin>type student (press enter key)
AHAMED 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:
#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();
}
Example 3:
#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
int main()
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<<”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
cout<<disp; NOTES
}
in.close();
return 0;
}
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.
In C++ every sequential file (including Random access file) will be associated
with two file pointers. They are
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();
}
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.
#include<iostream.h> NOTES
#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();
}
Random access file is one that allows accessing records randomly in any order
hence any ith record can be accessed directly. In order to perform random access
to a file C++ supports the following functions in addition to get() and put() pointers
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.
NOTES The functions seekg() and seekp() have the following prototype
istream &seekg(offset,seekdirection);
ostream &seekp(offset,seekdirection);
From the prototype we can note that both the functions have the same form. The first
parameter offset specifies the number of bytes the file pointer has to move from the
specified position. The second parameter seekdirection may take any one of the
following values.
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.
#include<iostream.h> NOTES
#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();
}
As mentioned earlier a binary file stores the content in binary format and a binary
file can be used to represent any kind of data. Similar to the get and put functions
of the text file we have read and write functions in a binary file. The syntax of
read and write functions is given below.
Example 7:
#include<iostream.h>
#include<fstream.h>
int main()
{
ofstream out;
out.open(“number”,ios::binary); //opens a binary file
int k=55;
out.write((char *)&k,sizeof(k)); //writes integer to the file
out.close();
return 0;
}
Note:
The address of the variable must be casted to the type char *.
Example 8:
#include<iostream.h> NOTES
#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;
}
55
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;
NOTES cin>>aname
cout<<”ENTER COST OF THE BOOK”<<endl;
cin>>cost;
cout<<”ENTER PUBLISHER ID”<<endl;
cin>>pubid;
}
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;
}
200 NOTES
ENTER PUBLISHER ID
101
ENTER BOOK NAME
JAVA
ENTER AUTHOR NAME
H.SCHILDT
ENTER COST OF THE BOOK
400
ENTER PUBLISHER ID
102
This program creates an array of objects for the class book. The first for loop in
the main program reads the details of 2 books. Note that we still use the write()
function with the same syntax to write the object to the file. The second for loop
reads the content from the file and displays the details.
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.
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:
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:
#include<iostream.h>
int main()
{
ifstream in;
in.open(“text”);
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.
Summary
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
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
3. Create a class called sales with your own data members and functions. NOTES
Create object for the class and write the object to the binary file called
“sales.dat”.
4. Modify program 1 by including all error handling facilities.
Section 7.4
1. ifstream, ofstream and fstream.
2. To create an input/output stream we create an object of type fstream.
3. ios::in , ios::out, ios::trunk
Section 7.5
Section 7.6
1. Random access file is one that allows accessing records randomly in any
order
2. seekg and seep
3. Moves the put pointer k bytes ahead from the beginning of the file pointed
by stream out
Section 7.7
Section 7.8
NOTES References
6. Thinking in C++
Author: Bruce Eckel
Publisher : Prentice Hall 2000
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
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.
In many situations, we want to write the same functions for different data types.
For an example consider multiplication of two variables. The variable can be
integer, float or double. The requirement will be to return the corresponding return
type based on the input type. Instead of writing an overloaded function to solve
the above problem we can create a C++ function template. When we use C++
function templates, only one function signature needs to be created. The C++
compiler will automatically generate the required functions for handling the
individual data types. Thus function templates make programming easy.
Here the type T acts as a placeholder name for the data type used by the function,
the variable T belongs to generic data type. The compiler will automatically replace
this placeholder with an actual data type when it creates a specific version of the
function.
Example 1:
The following example declares add() function that will add two values of any
given data type.
//FUNCTION TEMPLATES
#include <iostream.h>
template <class T>
void add(T &a,T &b)
{
T c;
c= a+b;
cout<<”THE SUM IS: “<<c<<endl;
}
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.
#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;
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.
Example 3:
The following code snippet gives details regarding the function template 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
power 5 i.e. it computes 55.Thus we can see that it is possible to have a template NOTES
function with multiple parameters.
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;
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 it’s explicitly declared template
arguments. If successful, it will instantiate a function template specialization.
Errors will be generated if no match is found.
Example 5:
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.
You can also overload a template function with a non template function. Always NOTES
a non template function takes precedence over template functions. Consider the
example given below.
Example 6:
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.
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
Example 7:
void add()
{
cout<<”SUM IS “<< a+b;
}
T mul()
{
return a*b;
} NOTES
};
void main()
{
calc<int> obj(10,10);
obj.add();
int c;
c=obj.mul();
cout<<”PRODUCT IS “<<c;
}
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())
}
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;
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);
}
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
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();
}
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();
};
void main()
{
disp<int,char> obj(5,’a’);
obj.print();
Summary
Generic programming is an approach where generic types are used as
parameters. In C++ generic programming is done with the help of
templates.
A function template or generic function defines a general set of operations
that will be applied to various types of data.
A template function can take multiple parameters that may vary in their
data types.
You can overload a template function as you do with the normal C++
function.
C++ Class Templates are used where we have multiple copies of code for
different data types with the same logic
Templates can be used to define generic classes.
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.
Exercises
Short Questions
5. Create a class template called Rational add perform basic arithmetic NOTES
operations
(Note: Rational number will be in the form a/b (b <> 0) )
Section 8.4
1. C++ Class Templates are used where we have multiple copies of code
for different data types with the same logic
2. The syntax is
template <class T>
class classname
{
//member variable declarations of type T and other types
//member function declarations
};
NOTES References
6. Thinking in C++
Author: Bruce Eckel
Publisher : Prentice Hall 2000
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 er-
rors 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 re-
spond to run time errors. This chapter briefly explores the various exception han-
dling mechanisms available in C++.
• 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.
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 “throw-
ing” it. The error handling routine will receive and process the error.
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
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.
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:
#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
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.
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.
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 state-
ment is executed (all other are bypassed). When an exception is caught, arg will
receive its value. If you don’t need access to the exception itself, specify only
type in the catch clause (arg is optional). Any type of data can be caught, includ-
ing classes that you create
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.
try NOTES
{
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 excep-
tion 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 excep-
tion, in that case the first matching catch handler block is selected and executed.
A simple example for try with multiple catches is given below.
NOTES Example 3:
#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);
}
try
{
//statements
}catch (...)
{
do something
}
Example 4:
The following code snippet contains the catch statement that can catch all excep-
tions.
#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;
NOTES }
catch( …)
{
cout<<”Exception is Caught!!!” <<endl;
}
}
void main()
{
cout<<”Main Program”<<endl;
multiple_catch(0);
multiple_catch(1);
multiple_catch(5);
}
1. Write the syntax of the catch handler that can catch all exceptions
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. The syntax is given below.
Only the types in the comma separated type-list can be thrown by the function.
Throwing any other type will cause abnormal program termination.
Example 5:
#include<iostream.h> NOTES
#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;
}
}
void main()
{
cout<<”Main Program”<<endl;
multiple_catch(0);
multiple_catch(1);
multiple_catch(5);
}
Sometimes an exception handler may not wish to process the exception instead it
wishes to throw the exception. If an exception needs to be rethrown from within
an exception handler, this can be done by calling throw statement without any
parameter. The syntax is
try
{
….
….
}
catch (char c)
{
Exceptions can be rethrown only within the catch block. When we rethrow an
exception the same catch statement will not catch it again.
Summary
• Errors cane be classified in two categories they are Compile time errors
and Run time errors.
• Exceptions can be classified as Synchronous and Asynchronous excep-
tions.
• C++ exception handling mechanism is built upon three important key-
words. They are try, catch and throw.
• When any statement present in the try block causes an exception (i.e er-
ror) the program control leaves the try block without executing further
statements and switches to the catch block.
Exercises
Short Questions
1. How does compile time errors differs form run time errors
2. Memory overflow is an example for ___________
3. What do you mean by asynchronous exceptions
4. Write the three keywords used to handle exceptions
5. Explain guarded section
6. 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?
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 han-
dling facilities.
2. Create your own program to handle divide by zero exceptions
Section 9.3
Section 9.4
2. When any statement present in the try block causes an exception (i.e er-
ror) the program control leaves the try block without executing further
statements and switches to the 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
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 cer-
tain 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.
1. The syntax is
try
{
….
….
}
catch (char c)
{
References
6. Thinking in C++
Author: Bruce Eckel
Publisher : Prentice Hall 2000
NOTES
CHAPTER 10
INTRODUCTION TO JAVA
PROGRAMMING
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
10.1 Introduction
But however due to the sudden explosion of Internet and similar technologies,
Sun Microsystems changed their project objectives and renamed the Oak lan-
guage into Java. In 1994 the project team developed a web browser called
“HotJava” capable of locating and running applets, a java program that can run
on a web browser.
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 con-
cepts of Java.
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 lan-
guage. Java language has the following features.
Java compiler converts the source code into intermediate byte code instructions.
Java Interpreter converts these bytes codes into machine executable statements.
Thus we can say java is both compiled and interpreted language. The two steps of
compilation and interpretation allow for extensive code checking and improved
security
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 highly secured language. Java programs will run only within the Java
Virtual Machine (JVM) sandbox thus threats from malicious programs is mini-
mized. 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.
Java supports automatic memory management. Java Virtual machine (JVM) per-
forms 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
NOTES Multithreaded
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
You have learnt that java is a platform independent and architectural neutral lan-
guage. 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.
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.
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 let’s 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. class Welcome
2. {
3. public static void main(String args[])
4. {
5. // 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
javac welcome.java in the command prompt. This will create a class called
“welcome.class” which contains the byte code representation of the program.
To run the java program you have to use the java interpretor. The syntax to run is
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:
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.
As mentioned in chapter 1 tokens are the basic lexical elements of any program-
ming language In Java every statement is made up of smallest individual ele-
ments 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.
Find_3
Message
abc$
A23C
33pages
bob@gmail
10.5.3 Literals
10.5.4 Operators
Operators Precedence
postfix expr++ expr—
unary ++expr —expr +expr -expr ~ !
multiplicative */%
additive +-
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
10.6 Expressions
1. What is an expression?
boolean
1-bit. May take on the values true and false only.
true and false are defined constants of the language and are not the same
as True and False, TRUE and FALSE, zero and nonzero, 1 and 0 or any
other numeric value. Booleans may not be cast into any other type of
variable nor may any other variable be cast into a boolean.
byte
1 signed byte (two’s complement). Covers values from -128 to 127.
short
2 bytes, signed (two’s complement), -32,768 to 32,767
int
4 bytes, signed (two’s complement). -2,147,483,648 to 2,147,483,647.
Like all numeric types ints may be cast into other numeric types (byte,
short, long, float, double). When lossy casts are done (e.g. int to byte) the
conversion is done modulo the length of the smaller type.
long
8 bytes signed (two’s complement). Ranges from -9, 223, 372, 036, 854,
775, 808 to +9, 223, 372, 036, 854, 775, 807.
float
4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to
3.40282346638528860e+38 (positive or negative).
Like all numeric types floats may be cast into other numeric types (byte,
short, long, int, double). When lossy casts to integer types are done (e.g.
float to short) the fractional part is truncated and the conversion is done
modulo the length of the smaller type.
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
Apart from these types of constants java also supports backslash character con-
stants. The Table 10.2 lists all the backslash constants.
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:
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();
NOTES 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”); }
}
}
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++;
}
}
}
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);
}
}
}
NOTES Thus using wrapper classes you can convert the string to the corresponding sim-
pler type. The signature for the Integer wrapper class is
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
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 avail-
able 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”
Example 7:
The following example accepts two command line arguments and computes the
sum of two numbers.
class sum
{
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);
NOTES a=b;
b=c;
}
}
}
Example 9:
class count
{
public static void main(String args[])
{
int n;
n=args.length;
System.out.println(“The count is “+n);
}
}
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 program-
ming language.
Java compiler converts the source code into intermediate byte code in-
structions Java Interpreter converts these bytes codes into machine ex-
ecutable statements
Java programs are capable of running on all platforms hence java pro-
grams possess Write-Once-Run-Anywhere feature
Java programs will run only within the Java Virtual Machine (JVM) sand-
box
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. Expres-
sions 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. What is JVM?
2. Write the signature of main() method
3. Why main() method is declared as static?
4. The type comparison operator in java is ____________
5. When Boolean data type is used?
6. \\ is used as ___________
7. Mention the range for char data type
8. How will you make a early exit from a loop in Java?
9. What is a wrapper class?
Programming Exercises
Section 10.3
1. Java compiler converts the source code into intermediate byte code in-
structions Java Interpreter converts these bytes codes into machine ex-
ecutable statements
2. Java programs will run only within the Java Virtual Machine (JVM) sand-
box thus threats from malicious programs is minimized. Java does not
support pointers hence direct memory access is not allowed. Java sup-
ports 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
Section 10.5
3. (1)An identifier can contain alphanumeric characters, but it should begin NOTES
with an alphabet (2) Identifiers are case sensitive(i.e. upper and lower
cases are different) (3)Underscore and dollor sign are two special charac-
ter allowed.
4. ~ (bitwise compliment) , & (bitwise AND)
5. TRUE.
Section 10.6
Section 10.7
Section 10.8
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)
NOTES References
2. http:\\www.sun.com
3. Thinking in Java
Author: Bruce Eckel
Publisher : Prentice Hall 2000
NOTES
CHAPTER 11
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 pri-
mary concepts of object orientation like encapsulation, abstraction, inheritance
and polymorphism. This chapter introduces you to implement all the object ori-
ented features supported by java. This chapter provides the necessary background
to understand the advanced concepts presented in the subsequent chapters.
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
Objects are the run time instance of a class. Classes describe objects. Many ob-
jects can be instantiated from one class. Objects of different classes can be cre-
ated, used, and destroyed in the course of executing a program.
Objects in java are created using the “new” operator. For example to create an NOTES
object for the GUI class we follow the given syntax.
GUI obj=new GUI(); //declare and instantiate
OR
A class can contain variables. The variables added to the class are called instance
variables. Variables are declared in the java classes as mentioned below.
class product
{
int prod_id;
String prod_name;
double price;
}
Methods in Java determine the messages an object can receive. Methods in Java
can be created only as part of a class. A method can be called only for an object,
You call a method for an object by naming the object followed by a period (dot),
followed by the name of the method and its argument list, for example:
NOTES There are a number of optional modifiers that you can use when declaring a
method. They are listed in the Table 11.1:
Modifier Description
Visibility Can be one of the values: public, protected, or pri-
vate. Determines what classes can invoke the
method.
static The method can be invoked on the class instead
of an instance of the class.
abstract The method is not implemented. The class must
be extended and the method must be imple-
mented in the subclass.
final The method cannot be overridden in a subclass.
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);
}
}
Example 1: NOTES
The following java program performs the basic calculator functions.
class Calculator
{
int n1,n2,res;
void setData(int x1,int x2)
{
n1=x1;
n2=x2;
}
void add()
{
res=n1+n2;
System.out.println(“The Sum is : “+res);
}
void sub()
{
res=n1-n2;
System.out.println(“The Difference is : “+res);
}
int mul()
{
res=n1*n2;
return res;
}
double div()
{
return n1/n2;
}
}
class Mainprg
{
public static void main(String args[])
{
Calculator cal=new Calculator();
cal.setData(20,10);
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);
NOTES }
}
1. What is a class?
2. All classes in java extend __________
3. What is an object?
4. Write the syntax of method declaration.
5. 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. Con-
structors 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, pro-
tected, 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:
void add()
{
res=n1+n2;
1. What is constructer?
2. Differentiate constructors from other methods.
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
Only objects of the same class can have access rights to a method or data member
declared as private. A method or a data member can be declared as private by
prefixing it with the keyword private. For example
A data member or a method declared as public can be accessed by all classes and
their objects. To declare a data member or a method as public prefix the declara-
tion with the keyword public. For example
Data members, methods that are declared protected are accessible by that class
and the inherited subclasses. Methods and variables can be declared as protected
by prefixing the declaration with the protected keyword.
Example 3:
class numbers
{
void sum(int x,int y)
{
int z=x+y;
System.out.println(“Sum of addition of two numbers : “+z);
}
void sum(int x,int y,int z)
{
int r=x+y+z;
System.out.println(“Sum of addition of three numbers : “+z);
}
}
class test
{
public static void main(String args[])
{
test t=new test();
t.sum(10,20); //Call the method sum with two parameters
t.sum(10,20,30); //Call the method sum with three parameters
}
}
In this program the method sum is overloaded. From the main method when we
call the sum method the corresponding the overloaded version of the sum method
is called.
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:
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();
}
}
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.
To declare a variable as static we have to simply prefix the variable declaration
with the keyword static. For example
static int x;
Like static variables , static methods are called without the object. The differ-
ences between a static methods and non-static methods are as follows.
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 in-
cluding the static data member.
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.
This program makes use of static data members and methods class test
{
static int increment(int k)
{
k++;
return k;
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));
}
}
11.8 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. Inherit-
ance 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 sub-
class). In Java, inheritance is used for two purposes:
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance.
Example 7:
class rectangle
{
int l;
int b;
rectangle(int x,int y)
NOTES {
l=x;
b=y;
}
void rect_area()
{
System.out.println(“Area of Rectangle is “ + l*b);
}
}
{
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();
}
}
super() (or)
super(parameter list)
As mentioned earlier java supports multilevel inheritance. The syntax for multi-
level inheritance is given below.
class super1
{
———
———
}
class sub1 extends super1
{
———
———
}
class sub2 extends sub1
{
———
———
}
Example 8:
//Super Class
class data1
{
NOTES int a;
data1(int x)
{
a=x;
}
}
//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();
}
}
class Circle
{
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()
{
When the overriden method getArea() is invoked for an object of the Cylinder
class, the new overridden version of the method is called and not the old defini-
tion from the superclass Circle.
However, if we want to find the area of both circle and cylinder then we have to
instantiate both the classes and invoke the getArea() method.
We have already learnt the usage of super keyword in invoking the super class
constructer. Super keyword can also be used to call super class method overrid-
den by the subclass method. The previous program is modified with the help of
super keyword.
Example 10:
class Circle
{ 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);
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.
class Mainprg
{
public static void main(String args[])
{
data2 d=new data2(10,20);
d.display();
}
}
Value of a is 10
Value of b is 20
Abstract methods are those that will have only method declaration without any
implementation. Hence we can say abstract methods are incomplete methods. A
method in java can be declared as abstract by prefixing its declaration with the
keyword abstract. For example
The implementations for these abstract methods are provided by overriding the
abstract method using a subclass.
Abstract class is a class that is declared as abstract. An abstract class will have
one or more abstract methods. Abstract classes cannot be instantiated but it can
be inherited by other subclasses. These subclasses will provide the implementa-
tion of all the abstract methods present in the parent class however, if not, the
corresponding subclass must be declared abstract. Here is an example of a ab-
stract class and its corresponding subclass.
Example 12:
Shape()
{
l=10;
}
abstract void area(); //abstract method declaration
}
class Rect extends Shape
{
int b;
Rect()
{
b=10;
}
Java supports an important keyword called Final. The keyword Final is used in
three different context. Final keyword can be used along with
1 Variables
2 Methods
3 Classes
When a method declaration is prefixed with the “Final” keyword the method
cannot be overridden by the subclass method. Thus method overriding can be
prevented. For example
Before an object is garbage collected, the runtime system calls it’s final-
ize () 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.
Summary
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 over-
loaded.
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 it’s
finalize () method. The purpose of finalize () method is to release
system resources before the object gets garbage collected.
Exercises
Short Questions
Programming Exercises
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
Section 11.5
1. The private access specifier , The public access specifier ,The protected
access specifier
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.
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
ridden by the subclass method (c) To refer the superclass variable from the NOTES
subclass.
Section 11.11
Section 11.12
References
2. http:\\www.sun.com
3. Thinking in Java
Author: Bruce Eckel
Publisher : Prentice Hall 2000
6. Java in a Nutshell
Author:David Flanagan
Publisher :O’Reilly1999
NOTES
CHAPTER 12
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.
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.
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 int data[];
data=new int[50];
2 int[] data;
data=new int[50];
3 int[] data=new int[50];
4 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 String args[]
2 double points[]
Once an array is declared we can initialize it with some initial values. The syntax
is
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:
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);
}
}
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 be-
low.
class Bubble
{ NOTES
public static void main(String args[])
{
int a[]= { 23,7,19,46,53,21 };
for(int i=0;i<6;i++)
for(j=i+1;j<6;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
System.out.println (“The Sorted Output is”);
for(int i=0;i<6;i++)
System.out.println(a[i]);
Often data comes in a two dimensional form. For example, data represented in
tables are two dimensional (or more), a computer-generated image is two dimen-
sional, and so on. To handle these data we need 2-D arrays. To declare an 2-D
array in java, the syntax is
int data[][];
data=new int[3][3];
int data[][]=new int[3][3]
The above statement declares a 3x3 matrix. The first dimension represents the
row size the second dimension represents the column size. In Java, a two-dimen-
The expression x[i] selects the ith one-dimensional array; the expression x[i][j]
selects the jth element from that array.
Example 3:
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++)
‘ { NOTES
for (int j=0;j<3;j++)
{
System.out.print(b[i][j]+”\t”);
}
System.out.println();
}
}
}
1. What is an Array ?
2. Arrays in java extend _________
3. How will you access 10th element of an array ‘a’?
4. Write the statement to declare an integer array k with 50 elements.
5. How will you initialize 2D array?
12.4 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.
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
Here v is the object of type vector.The second form of constructer creates a vector
with a specified size. The general form is
NOTES The constructer given above creates a vector with an initial size 30.
Vector class in java supports many methods. Some important methods available
in Vector class are tabulated in the Table 12.1.
Method Description
To add elements to the Vector, you have to use the add() method as mentioned
earlier. For example the statement
v.add(o);
To get the elements from the Vector, You have to use the ListIterator class. This NOTES
class supports two important methods to access Vector elements. They are
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));
}
}
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.
Exercises
Short Questions
Long Questions
Programming Exercises
Section 12.3
1. 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.
2. java.lang.Object
3. a[9] refers 10th element
4. int k[]=new int[50]
5. We can initialize an 2-D array as given below.
int[][] twoD = { {1,2,3}, {4,5,6}, {7,8,9} };
Section 12.4
1. java.util
2. Vectors are commonly used instead of arrays, because they expand auto-
matically when new data is added to them.
3. Cast the float to an object ,then add to the vector
4. Vector v1=new Vector(15)
5. ListIterator
6. By using the size() method.
References
2. http:\\www.sun.com
3. Thinking in Java
Author: Bruce Eckel
Publisher : Prentice Hall 2000
6. Java in a Nutshell
Author:David Flanagan
Publisher :O’Reilly 1999
NOTES
CHAPTER 13
STRING HANDLING
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
13.1 Introduction
String handling is one of the most important facilities supported by programming
languages. Handling character strings in Java is supported through two final
classes: String and StringBuffer. The String class implements immutable charac-
ter strings, which are read-only once the string has been created and initialized,
whereas the StringBuffer class implements dynamic character strings. All string
literals in Java programs are implemented as instances of String class. Strings in
Java are 16-bit Unicode. This chapter provides all necessary details about both
the classes.
13.2 Learning Objectives
1 String str=”Hello”
2 String str=new String(“Hello ”);
3 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 creat-
ing 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.
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:
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
The Table 13.1 list all the methods to handle individual characters
Method Purpose
NOTES lastIndexOf(int chint fromIndex) Returns the index within this string of the
last occurrence of the specified character,
searching backward starting at the speci-
fied index.
replace(char oldChar,char newChar) Returns a new string resulting from replac-
ing all occurrences of oldChar in this string
with newChar
class example2
{
public static void main(String args[])
{
String str=”Anna University”;
System.out.println(“4th Character “+str.charAt(4));
System.out.println(“Index of Character U is “+str.indexOf(‘U’));
System.out.println(“Last Index of Character i is “+str.lastIndexOf(‘i’));
Method Purpose
startsWith(String prefix, int toffset) Tests if this string starts with the specified
prefix beginning a specified index
endsWith(String suffix) Tests if this string ends with the specified suf-
fix
Example 3: NOTES
This example performs searches for a pattern in the given string.
class example3
{
public static void main(String args[])
{
String str=”Anna University”;
System.out.println(“String Starts with Anna : “+str.startsWith(“Anna”));
System.out.println(“Ends With Anna : “+str.endsWith(“Anna”));
}
}
Method Purpose
class example4
{
public static void main(String args[])
{
String str=”Anna University”;
}
}
239 Anna University Chennai
DCS 115 OBJECT ORIENTED PROGRAMMING
The Table 13.4 list all the methods to convert the case of a character
Method Purpose
Example 5:
class example5
{
public static void main(String args[])
{
String str=”Anna University”;
Method Purpose
Example 6:
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));
}
}
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());
}
}
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,
inserting, deleting, modifying etc. A StringBuffer method involves substantial overhead 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.
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).
StringBuffer supports many methods that are available in String Class, apart from
that StringBuffer supports some unique methods. The Table 13.7 list some fre-
quently used methods.
Method Purpose
NOTES replace(int start, int end, String str) Replaces the characters in a substring of this
StringBuffer with characters in the speci-
fied String.
//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 :
“+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);
}
}
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
NOTES Strings can be concatenated using “+” operator and concat() method.
The charAt()method returns the character at the specified index.
The toLowerCase() method converts all of the characters in this String to
lower case
The toupperCase() method converts all of the characters in this String to
upper case
The getBytes() method convert this String into bytes according to the speci-
fied character encoding, storing the result into a new byte array.
The trim() method removes white space from the front and the end of a
String
The length() method returns the length of the String.
StringBuffer class is a mutable class .
The default capacity for a StringBuffer is 16
The capcity() method returns the current capacity of the String buffer.
The character sequence contained in this StringBuffer is replaced by the
reverse of the sequence by using reverse() method
Exercises
Short Questions
Long Questions
1. Explain the different ways of creating Strings and discuss some meth-
ods available in it
2. What is StringBuffer? Mention its advantages. Discuss some methods
available in it
Programming Exercises
1. Write a program to create two strings and perform the following operations
(a) find the length of the string
(b) concatenate the two strings
(c) compare the two strings
Section 13.3
Section 13.4
References
2. http:\\www.sun.com
3. Thinking in Java
Author: Bruce Eckel
Publisher : Prentice Hall 2000
6. Java in a Nutshell
Author:David Flanagan
Publisher :O’Reilly 1999
NOTES
CHAPTER 14
I N T E R F A C E S
14.1 Introduction
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 inher-
itance. 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 inher-
itance is discussed in this chapter.
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 signa-
tures. 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.
NOTES Interfaces are almost similar to classes but however there exist few differences
between them. These differences are listed in a Table 14.1.
interface interfacename
{
// final variables declaration
//methods declaration
}
interface clock
{
public int cur_time;
void getCurrentTime();
void setCurrentTime();
void showClock();
}
1 A class that implements the interface must override all the methods
present in the interface
2 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.
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;
{ NOTES
calculator cal =new calculator(25,5);
cal.add();
cal.sub();
cal.mul();
cal.div();
}
}
Since java does not support multiple inheritance directly often we want to
extend one parent class and implement many interfaces. For example
Here we can note that the class “myclass” inherits the properties of the parent
class Frame and implements to interfaces namely ActionListener and
ItemListener.
Example 2:
In this example the class client extends the class dimension2 and implements
the interface dimension1.
interface dimension1
{
final int xvalue;
public void getx(int);
}
class dimension2
{
int yvalue;
void gety(int b)
{
yvalue=b;
}
}
class client extends dimension2 implements dimension1
{
public void getx(int a)
{
NOTES xvalue=a;
}
void disp()
{
System.out.println(“XVALUE IS “+xvalue);
System.out.println(“YVALUE IS “+yvalue);
}
public static void main(String args[])
{
client obj=new client();
obj.getx(10);
obj.gety(10);
obj.disp();
}
}
You have learnt that in java a class can inherit the properties of other classes,
similar to this an interface can inherit the properties of another interface. The
syntax is the same as for inheriting classes. You have to use the keyword “ex-
tends” to implement the inheritance.
Example 3:
interface inf1
{
int i=100;
public void disp_i();
}
interface inf2 extends inf1
{
double j=55.8;
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();
}
NOTES client()
{
System.out.println(“Constructer for client”);
}
public void meth1()
{
System.out.println(“THIS IS FROM INF1”);
}
public void meth2()
{
System.out.println(“THIS IS FROM INF2”);
}
public void meth3()
{
System.out.println(“THIS IS FROM INF3”);
}
public static void main(String args[])
{
client cli=new client();
cli.meth1();
cli.meth2();
cli.meth3();
}
You have already learnt that an interface can contain variables. All the variables
that are declared in the interface are final variables. Declaring some variables in
an interface is similar to declaring #defined constants in C/C++ languages or
const variables. When you create some variables in an interface without any meth-
ods, then the class implementing that interface will not have any method to over-
ride .Hence the class will import only the constants from the interface. The final
variables in such interface can act as shared constants.
Example 5:
The example given below show the procedure to access interface variables.
interface constants
{ NOTES
int BAD=0;
int GOOD=1;
}
else
System.out.println(“Better Luck Next Time !!!!”);
}
}
1. An interface is having only final variables then these variables can act
as____________
Summary
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
Long Questions
Programming Exercises
Section 14.3
1. Interfaces are used to define a standard behavior that can be
implemented by any class in a class hierarchy. An interface
contains variables declaration and a set of methods with their
signatures.
2. public
3. False
4. abstract
Section 14.5
1. Shared constants ;
References
2. http:\\www.sun.com
3. Thinking in Java
Author: Bruce Eckel
Publisher : Prentice Hall 2000
6. Java in a Nutshell
Author:David Flanagan
Publisher :O’Reilly 1999
NOTES
CHAPTER 15
PACKAGES
· Java API Packages
· User Defined Packages
· Using Java API Packages
· Visibility and Access Rights in Java
· Hiding classes
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. Pro-
grammers bundle groups of related types into packages. A Java package is a mecha-
nism for organizing java classes and interfaces. Packages are also called as con-
tainers 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 con-
tain 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.
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
image
util
JAVA
awt
applet peer
net
java.lang
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
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
java.awt.image
Package that provides classes for managing image data, including color
models, cropping, color filtering, setting pixel values, and grabbing snap-
shots.
java.awt.peer
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.
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
name java. The remaining words of the Java Package name reflect the contents of NOTES
the package. The Java Package name also reflects its directory structure. For
example the statement
· 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 Ab-
stract 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 speci-
fied 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 pack-
age does not alter the size of the class file, but does lengthen the compile time.
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 syn-
tax is
package packagename;
Example 1:
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 di-
rectory. 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[])
{
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
Example 2:
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 let’s create another pack-
age pack2 which contains a class that access the class base
package pack1;
import pack1.*;
class X
{
Thus in Java it is possible to access a class in one package from another package.
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.
Example 3: NOTES
This example program illustrates the access rights for different scopes available
in java.
Now let us create a subclass for the class base in the same package.
package pack1;
public class Derived extends Base
{
public void print()
{
System.out.println(“Same Package Sub class”);
System.out.println( publicStr );
System.out.println( protectedStr);
System.out.println(defaultStr);
System.out.println(privateStr); //will not compile
}
}
From this example we can note that a private variable cannot be accessed by a
sub class even if the subclass resides in the same package.
package pack1;
public class Someclass
{
public void print()
{
System.out.println(“Same Package Some class”);
Base b=new Base ();
System.out.println(b. publicStr );
System.out.println(b.protectedStr);
System.out.println(b.defaultStr);
System.out.println(b.privateStr); //will not compile
}
}
A variable that is declared private cannot be accessed from any other class.
package pack2;
import pack1.Base;
public class Derived1 extends Base
{
public void print()
{
System.out.println (“Other Package Sub Class”);
System.out.println (publicStr);
System.out.println (protectedStr);
System.out.println(b.defaultStr); //will not compile
System.out.println(b.privateStr); //will not compile
}
}
In a subclass of another package only public and protected variables are acces-
sible.
package pack2;
import pack1.Base;
public class Someclass
{
public void print()
{ NOTES
System.out.println (“Other Package Other Class”);
Base b=new Base();
System.out.println (b.publicStr);
System.out.println (protectedStr); //will not compile
System.out.println(b.defaultStr); //will not compile
System.out.println(b.privateStr); //will not compile
}
}
Only public variables are accessible by a non subclass residing in some other
package.
When a package is imported to your program all the public classes will be im-
ported 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 pro-
gram. 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,
Summary
Exercises
Short Questions
Long Questions
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 an-
other program and make use of the methods. Apply appropriate access
specifiers to the variables and methods.
Section 15.3
Section 15.4
1.Yes
2.public or protected
3.public.
Section 15.5
References
NOTES 2. http:\\www.sun.com
3. Thinking in Java
A uthor: Bruce Eckel
Publisher : Prentice Hall 2000
6. Java in a Nutshell
A uthor: David Flanagan
Publisher: O’ Reilly 1999
NOTES
CHAPTER 16
MULTITHREADED PROGRAMMING
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
16.1 Introduction
The earliest computers did only one job at a time. All programs were run sequen-
tially, one at a time; and each had full run of the computer. However two pro-
grams couldn’t 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 run-
ning 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, al-
though multiprocessing sometimes implies that more than one CPU is involved.
In multitasking, only one CPU is involved, but it switches from one program to
NOTES another so quickly that it gives the appearance of executing all of the programs at
the same time.
In a multithreaded program all the threads executes concurrently and share re-
sources. Since one processor is responsible for executing all the threads, the java
interpreter performs switching of control between the running threads. This con- NOTES
cept is known as context switching in a thread.
MAIN THREAD
Start
Start
Start
Start
1. Define Thread.
2. All the child threads are created by __________ thread
3. What do you mean by Context Switch?
16.4 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 Extending the Thread class
2 Implementing the Runnable interface
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
The simple way to create a threaded program is to extend the thread class. Any
class that extends Thread class can access all the methods available in the thread.
The steps to create a threaded program are given below.
Step1:
Create a class that extends thread. For example
Step 2:
Override the run() method and write the code required by the thread
class myclass extends Thread
{
……
……
public void run()
{
//body of the run method.
}
……
……
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:
{ NOTES
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println(i + “ * 2 = “ + i*2)
}
}
}
NOTES
From the output we can note that all the three threads were executed simulta-
neously.
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
Step 2: NOTES
Override the run() method and write the code required by the thread
class myclass implements Runnable
{
……
……
public void run()
{
//body of the run method.
}
……
……
}
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:
When a new thread is created it passes through various states before it gets termi-
nated 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.
NOTES
Suspend
Runnable
New Thread Not Running
Start
Running
Notify
Dead
Apart from the start() and run() method, a thread class supports the following
methods that causes the state transition of a thread.
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
NOTES Example 4:
Example 5:
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 in-
teger, 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 high-
est 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:
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();
}
}
16.8 Synchronization
Generally in a multithreaded environment all the threads share some critical re-
sources 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. pro-
viding 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
NOTES When we declare a method as synchronized, Java creates a monitor (which is the
basis of thread synchronization). A monitor is an object that can block and revive
threads.
Summary
The initial thread associated with a main by default has priority NOTES
Thread.NORM_PRIORITY (value 5)
The current priority of any thread can be accessed via method getPriority.
The priority of any thread can be dynamically changed via method
setPriority
Synchronization of threads is used to provide an exclusive access to a
thread currently accessing the shared resource
A monitor is an object that can block and revive threads.A monitor is
simply a lock that serializes access to an object or a class.
Exercises
Short Questions
Long Questions
Programming Exercises
Section 16.3
Section 16.4
1. Java supports two different ways of creating threads. They are
Section 16.5
Section 16.6
Section 16.7
1. 0,5,10
2. The current priority of the running thread can be accessed via method
getPriority
Section 16.8
1. Synchronization of threads is used to provide an exclusive access to a
thread currently accessing the shared resource
Anna University Chennai 290
DCS 115 OBJECT ORIENTED PROGRAMMING
2. A monitor is an object that can block and revive threads. A monitor is NOTES
simply a lock that serializes access to an object or a class.
References
2. http:\\www.sun.com
3. Thinking in Java
Author: Bruce Eckel
Publisher : Prentice Hall 2000
6. Java in a Nutshell
Author:David Flanagan
Publisher :O’Reilly 1999
NOTES
NOTES
NOTES
NOTES
NOTES