Вы находитесь на странице: 1из 163

CS6456 OBJECT ORIENTED PROGRAMMING

UNIT 1

OVERVIEW

Why Object-Oriented Programming in C++ - Native Types and Statements Functions and Pointers- Implementing
ADTs in the Base Language.

SOFTWARE DEVELOPMENT

Software:

Software is defined as a collection of programs to do a specific task. The person who is using the software is
called end-user.

Objectives of software development:

I. It must satisfy the end-user.

II. Development cost must be minimum.

III. It should take minimum amount of development time.

IV. It should be reliable

V. It should be reusable.

The objectives are:

Correctness

Maintainability

Reusability

Openness and interoperability

Portability

Security

Integrity

User friendliness

Software Evaluation:

1
Machine language it uses 0s and 1s for writing programs. It is very difficult to write and correct errors. It
is machine dependent.

Assembly language it uses symbolic codes for writing programs. It is difficult to write and correct errors. It
is machine dependent.

Procedure oriented programming it uses high level languages like COBOL, PASCAL and C. We use
functions, procedures and different data structures for writing programs.

Object -oriented programming it uses high level languages like c++, java etc. it has a collection of discrete
objects incorporated with data structures and its behavior.

Procedure oriented programming:

Features:

I. Large problems are divided in to smaller problems known as functions or procedures.

II. It is top down programming technique.

III. Data moves freely from one function to another.

IV. Function can share global variables.

V. Data hiding is not possible.

Object oriented programming paradigm:

The given problem is divided into number of entities called objects.

The related functions, data and its structures are all defined inside the objects.

The data inside the objects are called attributes and the related functions are called operations.

The data of an object can be accessed only by the function associated with that object.

Finally all the objects are interfaced to solve the problem.

Consider a problem to design a computer system:

This problem is divided into three objects namely

I. Monitor

II. Keyboard

III. CPU

2
Features of Object oriented programming:

1. Programs are divided in to objects.

2. It is not possible to access data freely.

3. Data hiding is possible.

4. It is bottom-up programming technique.

5. It is easy to add new data and functions.

6. Objects can exchange data through its function

Object oriented programming concepts:

1. Objects

2. Class

3. Data Abstraction

4. Encapsulation

5. Inheritance

6. Polymorphism

7. Dynamic binding

8. Message passing

1. Objects:

Objects are the Basic run time entities.

3
They may represent a person, a place, a bank account that the program has to handle.

An instance of a class is called object.

We can create any number of objects related to the class. Each object contains data and code to manipulate
data. The following fig. shows the two ways to represent objects.

The problem is divided into number of entities called objects.

The data inside the objects are called attributes and related functions are called operations.

Ex: computer

Objects monitor, keyboard and CPU

Object = Data + Methods

NEED FOR OBJECTS:

Modularity - large software projects can be split up in smaller pieces.

Reusability - New software components can be written or developed from existing ones

Everything in the world is an object

A flower, a tree, an animal


A student, a professor
A desk, a chair, a classroom, a building
A university, a city, a country
The world, the universe
A subject such as CS, IS, Math, History,

2. Class:

Class is template for an object. It is a collection of objects with same type of data and functions. We can
create any number of objects related to the class. Data items in a class are called data members. The function with in
a class is called member functions. (User defined class)

Example:

class name fruit

4
fruit mango , apple , orange;

A class must have a valid identifier name; it can begin with an alphabetic character, the underscore, or the
dollar sign.

Syntax for declaring a class:

The class body is declared within curly braces.

class MyClass {

member variables;

member functions () ;

}; // end class MyClass

3&4. Data Abstraction& Encapsulation:

Data abstraction is defined as a grouping of essential details and ignoring background details.

For example cost, size, weight and color are all named collection of data that describes the objects chair in
the class furniture.

Data Encapsulation is a technique used to hiding the informations (data) in an object from other objects.

The wrapping up of data and functions into a single unit is known as encapsulation.

Data hiding

5. Inheritance:

Inheritance is the process by which objects of one class obtain the properties of objects of another class.

The main advantages of the inheritance are

Reusability of the code

To increase the reliability of the code

To add some enhancement to the base class.

5
6. Polymorphism:

Polymorphism means one name, multiple forms. It allows us to have more than one function with the same
name in a program. Operator overloading and function-overloading comes under polymorphism.

Ex. Draw() is defined in all the classes.

7. Dynamic binding:

Binding is defined as the connection between the functions call and its corresponding program code to be
executed .

Types:

1. static binding

2. dynamic binding (late binding)

8. Message passing:

Message passing is a process of locating and executing a function in response to a message.

Locating means matching the given message with the list of available functions.

Basic Syntax

6
C++ program can be defined as a collection of objects that communicate via invoking each other's methods

The C++ language defines several headers, which contain information that is either necessary or useful to your
program. For this program, the header <iostream> is needed.
The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent
addition to C++.
The next line // main () is where program execution begins. is a single-line comment available in C++. Single-
line comments begin with // and stop at the end of the line.
The line int main () is the main function where program execution begins.
The next line cout<< "This is my first C++ program."; causes the message "This is my first C++ program" to be
displayed on the screen.
The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.

Constructors And Destructors In C++:

Constructor

It is a member function having same name as its class and which is used to initialize the objects of that class
type with a legal initial value.
Constructor is automatically called when object is created.
Constructors can be defined either inside the class definition or outside class definition using class name and
scope resolution :: operator.
While defining a constructor you must remember that the name of constructor will be same as the name of
the class, and constructors never have return type.

class A
{
int i;
public:
A(); //Constructor declared
};

7
A::A() // Constructor definition
{
i=1;
}
Destructor

A destructor is a member function having sane name as that of its class preceded by ~(tilde) sign and which
is used to destroy the objects that have been created by a constructor.
It gets invoked when an objects scope is over.
~A() {}
class A
{
A()
{
cout << "Constructor called";
}

~A()
{
cout << "Destructor called";
}
};

int main()
{
A obj1; // Constructor Called
int x=1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
Overloading:

In C++ programming, two functions can have same identifier(name) if either number of arguments or type
of arguments passed to functions are different. These types of functions having similar name are cal led
overloaded functions.

/* Example of function overloading */

int test() { }
int test(int a){ }
int test(double a){ }
int test(int a, double b){ }

All 4 functions mentioned above are overloaded function.


It should be noticed that, the return type of all 4 functions is same,i.e, int.
Overloaded function may or may not have different return type but it should have different
argument(either type of argument or numbers of argument passed).

8
Two functions shown below are not overloaded functions because the y only have same number
of arguments and arguments in both functions are of type int.

int test(int a){ }

double test(int b){ }

/*Calling overloaded function test() with different argument/s.*/

#include <iostream>
using namespace std;
void test(int);
void test(float);
void test(int, float);
int main()
{
int a = 5;
float b = 5.5;

test(a);
test(b);
test(a, b);

return 0;
}

void test(int var) {


cout<<"Integer number: "<<var<<endl;
}

void test(float var){


cout<<"Float number: "<<var<<endl;
}

void test(int var1, float var2) {


cout<<"Integer number: "<<var1;
cout<<" And float number:"<<var2;
}

Templates And Generic Programming:

Templates are the foundation of generic programming, which involves writing code in a way
that is independent of any particular type.
A template is a blueprint or formula for creating a generic class or a function. The library
containers like iterators and algorithms are examples of generic programming and have been
developed using template concept.
There is a single definition of each container, such as vector, but we can define many different
kinds of vectors for example, vector <int> or vector <string>.

9
/* C++ program to display larger number among two numbers using function
templates. */
/* If two characters are passed to function template, character with larger ASCII
value is displayed. */

#include <iostream>
using namespace std;
template <class T>
T Large(T n1, T n2)
{
return (n1>n2) ? n1:n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;
cout<<"Enter two integers: ";
cin>>i1>>i2;
cout<<Large(i1, i2)<<" is larger.";
cout<<"\n\nEnter two floating-point numbers: ";
cin>>f1>>f2;
cout<<Large(f1, f2)<<" is larger.";
cout<<"\n\nEnter two characters: ";
cin>>c1>>c2;
cout<<Large(c1, c2)<<" has larger ASCII value.";
return 0;
}

Standard Template Library

The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provides general-
purpose templatized classes and functions that implement many popular and commonly used algorithms
and data structures like vectors, lists, queues, and stacks.
At the core of the C++ Standard Template Library are following three well-structured components:

Exception in C++

An exception is a problem that arises during the execution of a program.


A C++ exception is a response to an exceptional circumstance that arises while a program is running,
such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++ exception
handling is built upon three keywords: try, catch, and throw.

10
throw: A program throws an exception when a problem shows up. This is done using a throw
keyword.
catch: A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The catch keyword indicates the catching of an
exception.
try: A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.

Benefits of OOPs
1. Reusability: In OOPs programs functions and modules that are written by a user can be reused by other
users without any modification.
2. Inheritance: Through this we can eliminate redundant code and extend the use of existing classes.
3. Data Hiding: The programmer can hide the data and functions in a class from other classes. It helps the
programmer to build the secure programs.
4. Reduced complexity of a problem: The given problem can be viewed as a collection of different objects.
Each object is responsible for a specific task. The problem is solved by interfacing the objects. This technique
reduces the complexity of the program design.
5. Easy to Maintain and Upgrade: OOP makes it easy to maintain and modify existing code as new objects can
be created with small differences to existing ones.
6. Message Passing: The technique of message communication between objects makes the interface with
external systems easier.
7. Modifiability: it is easy to make minor changes in the data representation or the procedures in an OO
program. Changes inside a class do not affect any other part of a program, since the only public interface
that the external world has to a class is through the use of methods;

Native Types and Statements

Program elements

1. Comments

Comments helps anyone reading it's source code


11
C++ supports single-line and multi-line comments. All characters available inside any comment are ignored by C++
compiler.

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

/* This is a comment */
/* C++ comments can also
* span multiple lines
*/

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

#include<iostream>
usingnamespacestd;

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

return0;
}
When the above code is compiled, it will ignore // prints Hello World and final executable will produce the following
result:
HelloWorld

2. Keywords

Primitive Built-in Types:

C++ offer the programmer a rich assortment of built-in as well as user defined data types. Following table lists down
seven basic C++ data types:

Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Wide character wchar_t

Several of the basic types can be modified using one or more of these type modifiers:

signed
unsigned
short
12
long

The following table shows the variable type, how much memory it takes to store the value in memory, and what is
maximum and minimum vaue which can be stored in such type of variables.

Type Typical Bit Width Typical Range


char 1byte -127 to 127 or 0 to 255
unsigned char 1byte 0 to 255
signed char 1byte -127 to 127
int 4bytes -2147483648 to 2147483647
unsigned int 4bytes 0 to 4294967295
signed int 4bytes -2147483648 to 2147483647
short int 2bytes -32768 to 32767

#include<iostream>
usingnamespacestd;

int main()
{
cout<<"Size of char : "<<sizeof(char)<<endl;
cout<<"Size of int : "<<sizeof(int)<<endl;
cout<<"Size of short int : "<<sizeof(shortint)<<endl;
cout<<"Size of long int : "<<sizeof(longint)<<endl;
cout<<"Size of float : "<<sizeof(float)<<endl;
cout<<"Size of double : "<<sizeof(double)<<endl;
cout<<"Size of wchar_t : "<<sizeof(wchar_t)<<endl;
return0;
}

sizeof is a keyword

This example uses endl, which inserts a new-line character after every line and << operator is being used to pass
multiple values out to the screen. We are also using sizeof() function to get size of various data types.

When the above code is compiled and executed, it produces the following result which can vary from machine to
machine:

Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4

3. Identifiers

Its a sequence of letters, digits and underscores. It cannot begin with a digit. The first letter of identifier should
be either a letter or an underscore. But, it is discouraged to start an identifier name with an underscore
though it is legal. Upper and lowercase letters are treated distinct.

13
Eg:

4. Integer literals:
A literal is some data that's presented directly in the code, rather than indirectly through a variable or
function call.
An integer literal can be a decimal, octal, or hexadecimal constant.
A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
85// decimal
0213// octal
0x4b// hexadecimal
30// int
30u// unsigned int

Character literals:

Character literals are enclosed in single quotes.

Escape sequence Meaning


\\ backslash
\' Single quote
\" Double quote
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab

5. Constants:

There are two simple ways in C++ to define constants:

Using #define preprocessor.

14
Using const keyword.

The #define Preprocessor:

Following is the form to use #define preprocessor to define a constant:

#define identifier value

Following example explains it in detail:

#include<iostream>
usingnamespace std;
#define LENGTH 10
#defineWIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area= LENGTH * WIDTH;
cout<< area;
cout<< NEWLINE;
return0;
}

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

50

The const Keyword:


You can use const prefix to declare constants with a specific type as follows:
const type variable = value;

Following example explains it in detail:

#include<iostream>
usingnamespace std;
int main()
{
const int LENGTH =10;
const int WIDTH =5;
const char NEWLINE ='\n';
int area;
area= LENGTH * WIDTH;
cout<< area;
cout<< NEWLINE;
return0;
}

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

50
6. Operators and Punctuators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations

a+=b; is equivalent to a=a+b;

15
a*=a+b; is equivalent to a=a*(a+b);
++i; is equivalent to i=i+1;
--x; is equivalent to x=x-1;
j=++i; is equivalent to i=i+1;j=i;
j=i++; is equivalent to j=i;i=i+1;

Conditional operator. If Condition is true ? then it


Condition ? X : Y
returns value X : otherwise value Y
Simple assignment operator, Assigns values
= C = A + B will assign value of A + B into C
from right side operands to left side operand
Add AND assignment operator, It adds right
+= operand to the left operand and assign the C += A is equivalent to C = C + A
result to left operand
Subtract AND assignment operator, It
-= subtracts right operand from the left C -= A is equivalent to C = C - A
operand and assign the result to left operand
Multiply AND assignment operator, It
*= multiplies right operand with the left C *= A is equivalent to C = C * A
operand and assign the result to left operand
Divide AND assignment operator, It divides
/= left operand with the right operand and C /= A is equivalent to C = C / A
assign the result to left operand
Modulus AND assignment operator, It takes
%= modulus using two operands and assign the C %= A is equivalent to C = C % A
result to left operand

Operators Precedence in C++:

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

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

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

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

16
Unary + - ! ~ ++ - - (type)* &sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift <<>> Left to right

Relational <<= >>= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Traditional conversions

The operand of lower type is promoted to that of higher type

Int< unsigned < long < unsigned long < float < double < long double

Type Conversion types:

Implicit type conversion

Explicit type conversion

Implicit type conversion

It will be done by the compiler, by following the rule of lower type converted to higher type.

Eg: int y = 10;


int z = 10.5;
float x;
x = y+z;
x= 20.5 (result var. x is must be float)
Explicit type conversion

It will be performed by the programmer. According to the need of this in the program.
17
Syntax:

datatype (var)

Eg:

float y = 10.3;

float z = 2.5;

x = int (y + z);

Now the result is of int type

INPUT / OUTPUT STATEMENTS


The iostream library overloads the two bit-shift operators.
<< // "put to" output stream, normally left shift
>> // "get from" input stream, normally right shift

This library also declares three standard streams:


cout // standard out
cin // standard in
cerr // standard error

Input Stream
Syntax:
cin >> var1 >> var2 >>;
cin Keyword, it is an object, predefined in C++ to correspond to the standard input stream.

>> - is the extraction or get from operator

Extraction operation (>>) takes the value from the stream object on its left and places it in
the variable on its right.
Eg: cin>>x;
cin>>a>>b>>c;

Output Stream:
Syntax:
cout<<var1<<var2;
cout - object of standard output stream

<< - is called the insertion or put to operator


It directs the contents of the variable on its right to the object on its left.
Output stream can be used to display messages on output screen.

Eg: cout<<a<<b;
cout<<value of x is<<x;
cout<<Value of x is<<x<<less than<<y;

Enumerated Types:

An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as values
of the type. Each enumerator is a constant whose type is the enumeration.

To create an enumeration requires the use of the keyword enum. The general form of an enumeration type is:

18
enum-name { list of names }var-list;

Here, the enum-name is the enumeration's type name. The list of names is comma separated.

For example, the following code defines an enumeration of colors called colors and the variable c of type color.
Finally, c is assigned the value "blue".

enum color { red, green, blue } c;


c = blue;

By default, the value of the first name is 0, the second name has the value 1, the third has the value 2, and so on. But
you can give a name a specific value by adding an initializer. For example, in the following enumeration, green will
have the value 5.

enum color { red, green=5, blue };


Here, blue will have a value of 6 because each name will be one greater than the one that precedes it.

STATEMENTS

Compound Statement:

It is a series of statements surrounded by { and }.Its chief use is to group statements into an executable unit.

IF STATEMENT:

The syntax of an if statement in C++ is:

if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}

If the boolean expression evaluates to true, then the block of code inside the if statement will be executed. If
boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing
curly brace) will be executed.
Flow Diagram

Example:
#include<iostream>
usingnamespacestd;

int main ()
{

19
// local variable declaration:
int a =10;

// check the boolean condition


if( a <20)
{
// if condition is true then print the following
cout<<"a is less than 20;"<<endl;
}
cout<<"value of a is : "<< a <<endl;

return0;
}

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

ais less than 20;


value of a is:10
IF ELSE STATEMENT:

The syntax of an if...else statement in C++ is:

if(boolean_expression)
{
// statement(s) will execute if the boolean expression is true
}
else
{
// statement(s) will execute if the boolean expression is false
}

If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code
will be executed.

Flow Diagram:

Example:
#include<iostream>
usingnamespacestd;

int main ()
{

20
// local variable declaration:
int a =100;

// check the boolean condition


if( a <20)
{
// if condition is true then print the following
cout<<"a is less than 20;"<<endl;
}
else
{
// if condition is false then print the following
cout<<"a is not less than 20;"<<endl;
}
cout<<"value of a is : "<< a <<endl;

return0;
}

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

aisnot less than 20;


value of a is:100

Switch statement:

Syntax:
The syntax for a switch statement in C++ is as follows:
switch(expression){
case constant-expression :
statement(s);
break;//optional
case constant-expression :
statement(s);
break;//optional

// you can have any number of case statements.


default://Optional
statement(s);
}

Example:
#include<iostream>
usingnamespacestd;
int main ()
{
// local variable declaration:
char grade ='D';

switch(grade)
{
case'A':
cout<<"Excellent!"<<endl;
break;
21
case'B':
case'C':
cout<<"Well done"<<endl;
break;
case'D':
cout<<"You passed"<<endl;
break;
case'F':
cout<<"Better try again"<<endl;
break;
default:
cout<<"Invalid grade"<<endl;
}
cout<<"Your grade is "<< grade <<endl;
return0;
}

This would produce the following result:

You passed
Your grade is D
While loop:

A while loop statement repeatedly executes a target statement as long as a given condition is true.
Syntax:

The syntax of a while loop in C++ is:

while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and
true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.

Flow Diagram:

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is
false, the loop body will be skipped and the first statement after the while loop will be executed.
Example:
#include<iostream>
usingnamespacestd;

int main ()
22
{
// Local variable declaration:
int a =10;

// while loop execution


while( a <20)
{
cout<<"value of a: "<< a <<endl;
a++;
}

return0;
}

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

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

FOR loop:

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific
number of times.
Syntax:

The syntax of a for loop in C++ is:

for(init; condition; increment )


{
statement(s);
}

Here is the flow of control in a for loop:

The init step is executed first, and only once. This step allows you to declare and initialize any loop control
variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop
does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the incrementstatement. This
statement allows you to update any loop control variables. This statement can be left blank, as long as a
semicolon appears after the condition.

The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop,
then increment step, and then again condition). After the condition becomes false, the for loop terminates.

Flow Diagram:

23
Example:
#include<iostream>
usingnamespacestd;

int main ()
{
// for loop execution
for(int a =10; a <20; a = a +1)
{
cout<<"value of a: "<< a <<endl;
}
return0;
}

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

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
do while loop:

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its
condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
Syntax:

The syntax of a do...while loop in C++ is:

do
{
statement(s);

24
}while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once
before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This
process repeats until the given condition becomes false.

Flow Diagram:

Example:
#include<iostream>
usingnamespacestd;

int main ()
{
// Local variable declaration:
int a =10;

// do loop execution
do
{
cout<<"value of a: "<< a <<endl;
a = a +1;
}while( a <20);

return0;
}

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

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

Break statement:

25
The break statement has the following two usages in C++:
When the break statement is encountered inside a loop, the loop is immediately terminated and program
control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).

If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the
innermost loop and start executing the next line of code after the block.

Syntax:The syntax of a break statement in C++ is:


break;

Flow Diagram:

Example:
#include<iostream>
usingnamespacestd;

int main ()
{
// Local variable declaration:
int a =10;

// do loop execution
do
{
cout<<"value of a: "<< a <<endl;
a = a +1;
if( a >15)
{
// terminate the loop
break;
}
}while( a <20);

return0;
}

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

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Functions and Pointers

FUNCTIONS:
26
Functions in C++
A function is a group of statements that is executed when it is called from some point of the program.

A function can be invoked by a function call. The communication between a calling function and called
function takes place through parameters.

Need for a Function

Monolethic program (a large single list of instructions) becomes difficult to understand. For this reason
functions are used. A function has a clearly defined objective (purpose) and a clearly defined interface with
other functions in the program. Reduction in program size is another reason for using functions. The
functions code is stored in only one place in memory, even though it may be executed as many times as a
user needs.

ADVANTAGES:

Dividing the programs into functions is a major principle of oops which reduce the size of program.

Debugging is easier.

Types :

1) Pre defined function

Ex :sqrt() , toupper() , tolower() , pow()

2) User defined function

Ex : Add() , change() , multiply()

Syntax:
return-type function_name ( parameter1, parameter2, ...)

Statements

Syntax

Void func (int a, int b) // prototype

-------

Void func(inta,int b)//func definition, formal parameters(a,b)

Statements

int main ()

func(x,y); // function calling

return 0;
27
}

FUNCTION DEFINITION AND DECLARATION

The function definition contains the code for the function. The general syntax of a function definition in C++ is shown
below:

Function declaration:

Return Type name_of_the_function (argument list)

Function definition:

Return Type name_of_the_function (argument list)

//body of the function

Here, the type specifies the type of the value to be returned by the function. It may be any valid C++ data type.
When no type is given, then the compiler returns an integer value from the function.

Example Program:

#include <iostream>

int addition (int c, int d); //function declaration

int addition (int c, int d) //function definition

int r;

r=c+d;

return (r);

int main()

int z;

z = addition (5,3);

cout<< "The result is " << z;

return 0;

OUTPUT:

The result is 8

Parameters

28
1. Actual Parameter

These are the parameters transferred from the calling function to the called function.

2. Formal Parameter

These are the parameters which is used in the called function.

Function Prototypes:

1. Function with no arguments and no return values.

2. Function with arguments and no return values.

3. Function with arguments and return values.

4. Function with no arguments and with return values.

Parameter Passing Methods:

It is a mechanism for communication of data between the calling function and the called function.

Call by value:- changes in the called function does not change the contents of argument
variable in the calling function.

Call by reference:- Any modifications made through the formal parameter is also reflected
in the actual parameter.

Call by address:-Instead of passing a value, the address of the variable is passed. The address
of the argument is copied into a memory location instead of the value. Any modifications
made through the formal parameter is also reflected in the actual parameter.

CALL BY VALUE:

#include <iostream.h>

voidmain()

intx,y,change(int,int);

cout<<"\nEnter value of x:";

cin>>x;

cout<<"\nEnter value of y:";

cin>>y;

cout<<"\nbefore swap "<<x<<"\t"<<y;

change(x,y);

cout<<"\n\n after swap in main"<<x<<"\t"<<y;

getch();

29
int change(inta,int b)

int c;

c=a;

a=b;

b=c;

cout<<"\n\nafter swap"<<a<<"\t"<<b;

return 0;

OUTPUT:

Before swap 5,6

after swap 6,5

after swap in main 5,6

CALL BY ADDRESS:

#include <iostream.h>

void main()

intx,y,change(int*,int*);

cout<<"\nEnter value of x:";

cin>>x;

cout<<"\nEnter value of y:";

cin>>y;

cout<<"\nbeforeswapping : "<<x<<"\t"<<y;

change(&x,&y);

cout<<"\n\nafter swapping in main : "<<x<<"\t"<<y;

getch();

int change(int *a,int *b) *a-shows the value of address a

int c;
30
c=*a;/* save the value at address a */
*a=*b;/* put b into a */
*b=c;/* put a into b */

return 0;

OUTPUT:

before swapping :5 6

after swapping in main : 6 5

CALL BY REFERENCE:

#include <iostream.h>

change(int& x, int& y) ;

void main()

intx,y;

cout<<"\nEnter value of x:";

cin>>x;

cout<<"\nEnter value of y:";

cin>>y;

cout<<"\nbeforeswapping : "<<x<<"\t"<<y;

change(x,y);

cout<<"\n\nafter swapping in main : "<<x<<"\t"<<y;

getch();

int change(int&a,int&b)

int c;

c=a;

a=b;

b=c;

cout<<"\n\nafter swapping : "<<a<<"\t"<<b;


31
return 0;

OUTPUT:

before swapping :5 6

after swapping: 6 5

after swapping in main : 6 5

Function Overloading

Function overloading is the process of calling the several functions with the same name. A function can be
invoked by a function call. The communication between the calling function and called function takes place
through parameters.

Compiler classifies the overloaded function by its name and type of arguments in the function declaration.

Advantages:

1. Modularity.

2. Reduction in the amount of work and development time.

3. program and function debugging is easier.

4. used to eliminate the different function names with the same operation(ie)reusability of the code.

Function components:

Every function has the following elements:

Function declaration or prototype.

Function parameters(formal parameters)

Function call

Function definition

SYNTAX:

Void func (int a,int b);------------------prototype

----

Void func (int a,int b)--------------------function definition &a,b are formal parameters

---

void main()

---
32
---

func(x,y);---------------function call &x,y are actual parameters

Example:

#include<iostream.h>

#include<conio.h>

int add(int);

int add(int,int);

float add(float,int,int);

int main()

clrscr();

cout<<"\n addition1:"<<add(10)<<"\n";

cout<<"\n addition2:"<<add(5,8)<<"\n";

cout<<"\n addition3:"<<add(6.3,5,5);

return 0;

int add (int s)

return(s+s);

int add (int r, int h)

return(r+h);

float add(float f,intb,int h)

return(f+b+h);

OUTPUT:

addition1: 20

addition2: 13
33
addition4: 16.3

Default arguments:
A default argument is an argument to a function that a programmer is not required to specify.

Function assigns the default value to the parameters if it is not specified or if there is no matching arguments
in the function call.

Example:

#include<iostream.h>

int sum(int x=14,int y=28,int z=30);

void main()

cout<<"sum()="<<sum()<<endl; // x=14 y=28 z=30

cout<<"sum(18)="<<sum(18)<<endl; // x=18 y=28 z=30

cout<<"sum(18,25)="<<sum(18,25)<<endl; // x=18 y=25 z=30

intsum(int x, int y, int z)

return(x+y+z);

OUTPUT:

sum()= 72

sum()= 76

sum()= 73

Example:2

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

void main()
{
float amount;
clrscr();
float value(float p,intn,float r=0.15);
voidprintline(char ch='*',intlen=40);
printline();
amount=value(5000.0,5);
cout<<"\n"<<"Amount = "<<amount<<"\n";
printline('=');
getch();
}

34
float value(float p,intn,float r)
{
int year=n,tot;
float sum=p;
cout<<year<<sum<<r;
tot=p*n*r;
return(tot);
}

voidprintline(char ch,intlen)
{
for(int i=0;i<=len;i++)
cout<<ch;
}

OUTPUT:

***************************************
5 5000.0 0.15
Amount = 3750

INLINE FUNCTION:

When a function is called , the series of instructions executed

Jumps to function

Saving in registers

Push the argument to stack

Returning to calling functions

To avoid this we are going to inline functions. Inline function is used when the function body is small. If the function
body is too long, compiler ignores the request and compile as normal functions.

An inline function is one in which the function code replaces the function call directly. Inline functions are
those whose function body is inserted in place of the function call statement during the compilation process.

To avoid the slowdown processing of the program, inline function is used. When a function declared
as an inline, the actual coding is inserted in the place of function call while compiling.

To make a function as inline , the keyword inline must be declared before function definition.

The inlining does not work for the following situations :

1. For functions returning values and having a loop or a switch or a goto statement.
2. For functions that do not return value and having a return statement.
3. For functions having static variable(s).
4. If the inline functions are recursive (i.e. a function defined in terms of itself).

The benefits of inline functions are as follows :

1. Better than a macro.


2. Function call overheads are eliminated.
3. Program becomes more readable.
4. Program executes more efficiently.
Advantage:
35
Execution time of the function is less than the time required to establish linkage between the calling and
called function.

Flexibility and modularity of function

Achieve computational speedup.

Syntax:

inline function header

Function body

Example:

#include<iostream.h>

#include<conio.h>

inline float cube(int a)

return(a*a*a);

int main()

int a;

clrscr();

cout<<enter the value;

cin>>a;

cout<<cube is:<<cube(a);

getch();

return 0;

OUTPUT:

Enter the value 5


Cube is 125
STORAGE CLASSES:

A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program.

These are the following storage classes, which can be used in a C++

36
auto
register
static
extern
The auto Storage Class
The auto storage class is the default storage class for all local variables.
{
int month;
auto int month;
}

The example above defines two variables with the same storage class, auto can only be used within functions, i.e.,
local variables.

The register Storage Class


The register storage class is used to define local variables that should be stored in a register instead of RAM.
This means that the variable has a maximum size equal to the register size (usually one word) and can't have the
unary '&' operator applied to it (as it does not have a memory location).
{
register int miles;
}

The register should only be used for variables that require quick access such as counters.

It should also be noted that defining 'register' does not mean that the variable will be stored in a register.

It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.

The static Storage Class


The static storage class instructs the compiler to keep a local variable in existence during the life-time of the
program instead of creating and destroying it each time it comes into and goes out of scope.
#include<iostream>

// Function declaration
voidfunc(void);

staticint count =10;/* Global variable */

main()
{
while(count--)
{
func();
}
return0;
}
// Function definition
voidfunc(void)
{
staticint i =5;// local static variable
i++;
std::cout<<"i is "<< i ;
std::cout<<" and count is "<< count <<std::endl;
}

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

i is6and count is9


i is7and count is8
iis8and count is7
iis9and count is6
iis10and count is5
iis11and count is4
iis12and count is3
iis13and count is2
iis14and count is1
iis15and count is0

The extern Storage Class


The extern storage class is used to give a reference of a global variable that is visible to ALL the program
files. When we use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage
location that has been previously defined.
When you have multiple files and you define a global variable or function, which will be used in other files also,
then extern will be used in another file to give reference of defined variable or function.

The extern modifier is most commonly used when there are two or more files sharing the same global variables or
functions as explained below.

First File: main.cpp

#include<iostream>

int count ;
externvoidwrite_extern();

main()
{
count=5;
write_extern();
}

Second File: support.cpp

#include<iostream>

externint count;

voidwrite_extern(void)
{
std::cout<<"Count is "<< count <<std::endl;
}
NAMESPACES:

Namespaces allow to group entities like classes, objects and functions under a name.
The format of namespaces is:
namespace identifier

entities

}
38
They provide a way to avoid name collisions (of variables, types, classes or functions) without some of the
restrictions imposed by the use of classes, and without the inconvenience of handling nested classes
// namespaces

#include <iostream>

using namespace std;

namespace first

int var = 5;

namespace second

doublevar = 3.1416;

int main ()

cout<< first::var<<endl;

cout<< second::var<<endl;

return 0;

Namespace std:

All the files in the C++ standard library declare all of its entities within the std namespace.
That is why we have generally included the using namespace std; statement in all programs that used any
entity defined in iostream.
using

The keyword using is used to introduce a name from a namespace into the current declarative region

// using

#include <iostream>

using namespace std;

namespace first

int x = 5;

int y = 10;

39
}

namespace second

double x = 3.1416;

double y = 2.7183;

int main ()

using namespace first;


cout<< x <<endl;
cout<< y <<endl;
cout<< second::x <<endl;
cout<< second::y <<endl;
return 0;
}

Output:

5
10
3.1416
2.7183
In this case, since we have declared that we were using namespace first, all direct uses of x and y without
name qualifiers where referring to their declarations in namespace first.

ARRAY:

The array, stores a fixed-size sequential collection of elements of the same type.

An array is used to store a collection of data.

All arrays consist of contiguous memory locations.

The lowest address corresponds to the first element and the highest address to the last element.

Declaring Arrays:
typearrayName[arraySize];

This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be
any valid C++ data type. For example, to declare a 10-element array called balance of type double, use this
statement:
double balance[10];

Initializing Arrays:

We can initialize C++ array elements either one by one or using a single statement as follows:

double balance[5]={1000.0,2.0,3.4,17.0,50.0};

40
The number of values between braces { } cannot be larger than the number of elements that we declare for the array
between square brackets [ ].

balance[4]=50.0;

The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th, i.e.,
last element because all arrays have 0 as the index of their first element which is also called base index. Following is
the pictorial representaion of the same array we discussed above:

Accessing Array Elements:

An element is accessed by indexing the array name.

This is done by placing the index of the element within square brackets after the name of the array. For example:

double salary = balance[9];

The above statement will take 10th element from the array and assign the value to salary variable. Following is an
example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays:

#include<iostream>
usingnamespacestd;

#include<iomanip>
usingstd::setw;

int main ()
{
int n[10];// n is an array of 10 integers

// initialize elements of array n to 0


for(int i =0; i <10; i++)
{
n[ i ]= i +100;// set element at location i to i + 100
}
cout<<"Element"<<setw(13)<<"Value"<<endl;

// output each array element's value


for(int j =0; j <10; j++)
{
cout<<setw(7)<< j <<setw(13)<< n[ j ]<<endl;
}

return0;
}

This program makes use of setw() function to format the output. When the above code is compiled and executed, it
produces the following result:

Element Value
0 100
41
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
C++ Multi-dimensional Arrays:
Syntax:

type name[size1][size2]...[sizeN];

For example, the following declaration creates a three dimensional 5 .10 . 4 integer array:

Int threedim[5][10][4];

Two-Dimensional Arrays:

To declare a two-dimensional integer array of size x,y, we would write something as follows:

typearrayName[ x ][ y ];

Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y number of columns. A 2-
dimensional array a, which contains three rows and four columns can be shown as below:

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the
array, and i and j are the subscripts that uniquely identify each element in a.
Initializing Two-Dimensional Arrays:

Multidimensioned arrays may be initialized by specifying bracketed values for each row. Following is an array with 3
rows and each row have 4 columns.

int a[3][4]={
{0,1,2,3},/* initializers for row indexed by 0 */
{4,5,6,7},/* initializers for row indexed by 1 */
{8,9,10,11}/* initializers for row indexed by 2 */
};

It can also be represented as

int a[3][4]={0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements:


#include<iostream>
usingnamespacestd;
42
int main ()
{
// an array with 5 rows and 2 columns.
int a[5][2]={{0,0},{1,2},{2,4},{3,6},{4,8}};

// output each array element's value


for(int i =0; i <5; i++)
for(int j =0; j <2; j++)
{
cout<<"a["<< i <<"]["<< j <<"]: ";
cout<< a[i][j]<<endl;
}

return0;
}

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

a[0][0]:0
a[0][1]:0
a[1][0]:1
a[1][1]:2
a[2][0]:2
a[2][1]:4
a[3][0]:3
a[3][1]:6
a[4][0]:4
a[4][1]:8

Pointer to an Array:
Here balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the
following program fragment assigns p the address of the first element of balance:
double*p;
double balance[10];

p = balance;

#include<iostream>
usingnamespacestd;

int main ()
{
// an array with 5 elements.
double balance[5]={1000.0,2.0,3.4,17.0,50.0};
double*p;

p = balance;

// output each array element's value


cout<<"Array values using pointer "<<endl;
for(int i =0; i <5; i++)
{
cout<<"*(p + "<< i <<") : ";
43
cout<<*(p + i)<<endl;
}

cout<<"Array values using balance as address "<<endl;


for(int i =0; i <5; i++)
{
cout<<"*(balance + "<< i <<") : ";
cout<<*(balance + i)<<endl;
}

return0;
}

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

Array values using pointer


*(p +0):1000
*(p +1):2
*(p +2):3.4
*(p +3):17
*(p +4):50
Array values using balance as address
*(balance +0):1000
*(balance +1):2
*(balance +2):3.4
*(balance +3):17
*(balance +4):50

Passing Arrays as Function:


Function

doublegetAverage(intarr[],int size)
{
int i, sum =0;
doubleavg;

for(i =0; i < size;++i)


{
sum+=arr[i];
}

avg=double(sum)/ size;

returnavg;
}

Now, let us call the above function:

#include<iostream>
usingnamespacestd;

// function declaration:
doublegetAverage(intarr[],int size);

44
int main ()
{
// an int array with 5 elements.
int balance[5]={1000,2,3,17,50};
doubleavg;

// pass pointer to the array as an argument.


avg=getAverage( balance,5);

// output the returned value


cout<<"Average value is: "<<avg<<endl;

return0;
}

Result:

Average value is:214.4

POINTER:

A pointer is a variable whose value is the address of another variable.

Syntax:

type *var-name;

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

steps for using a pointer:

(a) we define a pointer variables

(b) assign the address of a variable to a pointer

(c) finally access the value at the address available in the pointer variable.

#include <iostream>

using namespace std;

int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";


cout << var << endl;

45
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}

When the above code is compiled and executed, it produces result something as follows:

Value of var variable: 20


Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

Relationship between Arrays and Pointers:

A pointer that points to the beginning of an array can access that array by using either pointer arithmetic or array-
style indexing. Consider the following program:

#include <iostream>

using namespace std;


const int MAX = 3;

int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;

// let us have array address in pointer.


ptr = var;
for (int i = 0; i < MAX; i++)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;

// point to the next location


ptr++;
}
return 0;
}

Result:

Address of var[0] = 0xbfa088b0


Value of var[0] = 10
Address of var[1] = 0xbfa088b4
Value of var[1] = 100

46
Address of var[2] = 0xbfa088b8
Value of var[2] = 200

Pointer based call by reference:

#include <iostream>
#include <ctime>

using namespace std;


void getSeconds(unsigned long *par);

int main ()
{
unsigned long sec;

getSeconds( &sec );

// print the actual value


cout << "Number of seconds :" << sec << endl;

return 0;
}

void getSeconds(unsigned long *par)


{
// get the current number of seconds
*par = time( NULL );
return;
}

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

Number of seconds :1294450468

The function which can accept a pointer, can also accept an array as shown in the following example:

#include <iostream>
using namespace std;

// function declaration:
double getAverage(int *arr, int size);

int main ()
{
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;

// pass pointer to the array as an argument.


avg = getAverage( balance, 5 ) ;

// output the returned value


cout << "Average value is: " << avg << endl;

47
return 0;
}

double getAverage(int *arr, int size)


{
int i, sum = 0;
double avg;

for (i = 0; i < size; ++i)


{
sum += arr[i];
}

avg = double(sum) / size;

return avg;
}

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

Average value is: 214.4

Free store operators new and delete:

Memory in your C++ program is divided into two parts:

The stack: All variables declared inside the function will take up memory from the stack.
The heap: This is unused memory of the program and can be used to allocate the memory dynamically when
program runs.

We can allocate memory at run time within the heap for the variable of a given type using a special operator in C++
which returns the address of the space allocated. This operator is called new operator.

If we are not in need of dynamically allocated memory anymore, we can use delete operator, which de-allocates
memory previously allocated by new operator.
Syntax:

new data-type;

Here, data-type could be any built-in data type including an array or any user defined data types include class or
structure.
we can define a pointer to type double and then request that the memory be allocated at execution time. We can do
this using the newoperator with the following statements:

double* pvalue = NULL; // Pointer initialized with null


pvalue = new double; // Request memory for the variable

We can free up the memory that it occupies in the free store with the delete operator as follows:

delete pvalue; // Release memory pointed to by pvalue

48
Program:
#include <iostream>
using namespace std;

int main ()
{
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable

*pvalue = 29494.99; // Store value at allocated address


cout << "Value of pvalue : " << *pvalue << endl;

delete pvalue; // free up the memory.

return 0;
}

Result:

Value of pvalue : 29495

Dynamic Memory Allocation for Arrays:

Consider we want to allocate memory for an array of characters, i.e., string of 20 characters. Using the same syntax
what we have used above we can allocate memory dynamically as shown below.

char* pvalue = NULL; // Pointer initialized with null


pvalue = new char[20]; // Request memory for the variable

To remove the array

delete [] pvalue; // Delete array pointed to by pvalue

for a multi-dimensional array

double** pvalue = NULL; // Pointer initialized with null


pvalue = new double [3][4]; // Allocate memory for a 3x4 array

syntax to release the memory for multi-dimensional array

delete [] pvalue; // Delete array pointed to by pvalue

Aggregate Type Struct:

Structures are used to represent a record. If we want to keep track of books in a library we declare the attributes
about each book:

Title
Author
Subject
Book ID
Defining a Structure:

49
To define a structure we must use the struct statement. The struct statement defines a new data type, with more
than one member. The format of the struct statement is this:

struct [structure tag]


{
member definition;
member definition;
...
member definition;
} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or
any other valid variable definition. At the end of the structure's definition, before the final semicolon, we can specify
one or more structure variables but it is optional.
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
}book;

Accessing Structure Members:


To access any member of a structure, we use the member access operator (.). The member access operator is coded
as a period between the structure variable name and the structure member that we wish to access. You would
use struct keyword to define variables of structure type. Following is the example to explain usage of structure:
#include <iostream>
#include <cstring>

using namespace std;

struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( )
{
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

50
// Print Book1 info
cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;

// Print Book2 info


cout << "Book 2 title : " << Book2.title <<endl;
cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;

return 0;
}

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

Book 1 title : Learn C++ Programming


Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700

Structures as Function Arguments:


#include <iostream>
#include <cstring>

using namespace std;


void printBook( struct Books book );

struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( )
{
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
51
// Print Book1 info
printBook( Book1 );

// Print Book2 info


printBook( Book2 );

return 0;
}
void printBook( struct Books book )
{
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}

Result:

Book title : Learn C++ Programming


Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700

Pointers to Structures:

We can define pointers to structures in very similar way as you define pointer to any other variable as follows:

struct Books *struct_pointer;

Now, we can store the address of a structure variable in the above defined pointer variable. To find the address of a
structure variable, place the & operator before the structure's name as follows:

struct_pointer = &Book1;

To access the members of a structure using a pointer to that structure, you must use the -> operator as follows:

struct_pointer->title;

Program:

#include <iostream>
#include <cstring>

using namespace std;


void printBook( struct Books *book );

struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;

52
};

int main( )
{
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// Book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info, passing address of structure


printBook( &Book1 );

// Print Book1 info, passing address of structure


printBook( &Book2 );

return 0;
}
// This function accept pointer to structure as parameter.
void printBook( struct Books *book )
{
cout << "Book title : " << book->title <<endl;
cout << "Book author : " << book->author <<endl;
cout << "Book subject : " << book->subject <<endl;
cout << "Book id : " << book->book_id <<endl;
}

Result:

Book title : Learn C++ Programming


Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700

Complex numbers:

/* Example program for binary operator overloading*/

#include<iostream.h> void main( )


class complex {
{ complex c1,c2 , c3;
float x,y; c1. setdata( 10, 3.5);
public: c2. setdata( 5.5, 2.5);
53
void setdata( float r, float i) c3= c1 + c2;
{ cout<< Ist complex number:;
x= r; c1. display( );
y= i; cout<< IInd complex number:;
} c2. display ( );
complex operator + ( complex c2) cout<< added complex number:;
{ c3. display ( );
complex temp; }
temp. x= x + c2. x;
temp. y= y + c2. y; OUTPUT:
return(temp); Ist complex number
} 10 + i 3.5
void display( ) IInd complex number:
{ 5.5 + i 2.5
cout<<x << +i<<y; added complex number
} 15. 5 + i 6.0
};

Unions
Unions allow one portion of memory to be accessed as different data types. Its declaration and use is similar to the
one of structures, but its functionality is totally different:

union type_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;
This creates a new union type, identified by type_name, in which all its member elements occupy the same physical
space in memory. The size of this type is the one of the largest member element. For example:

1 union mytypes_t {
2 char c;
3 int i;
4 float f;
5 } mytypes;

declares an object (mytypes) with three members:

1 mytypes.c
2 mytypes.i
3 mytypes.f

Example:

#include <iostream.h> union Emp


{
int num;
54
double sal;
};

int main()
{
Emp value;
value.num = 2;
cout << "Employee Number::" << value.num << "\nSalary is:: " << value.sal << endl;
value.sal = 2000.0;
cout << "Employee Number::" << value.num << "\nSalary is:: " << value.sal << endl;
return 0;
}

Result:

Employee number is::2


Salary is::2.122e-314
Employee number is::0
Salary is::2000

In the above example, only "value.num" is assigned, but still the "val.sal" gets a value automatically, since the
memory locations are same.

55
UNIT II

BASIC CHARACTERISTICS OF OOP


Data Hiding and Member Functions- Object Creation and Destruction- Polymorphism data abstraction: Iterators
and Containers.

Class:
A Class : is a way to bind the data and its associated functions together.
A class is used to specify the form of an object and it combines data representation and methods for
manipulating that data into one neat package.
The data and functions within a class are called members of the class.
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a
pair of curly braces.
A class definition must be followed either by a semicolon or a list of declarations.
Classes in C++ are introduced by the keyword class.
A form of struct, classes have a default privacy specification of private, in contrast to structures defined with
struct, which have a default privacy specification of public.
Thus, struct and class can be used interchangeably with the appropriate access specifications.
Syntax:

class class-name
{
access:specifier
private data and functions
}

For example, we defined the Box data type using the keyword class as follows:
classBox
{
public:
double length;// Length of a box
double breadth;// Breadth of a box
double height;// Height of a box
};

The keyword public determines the access attributes of the members of the class that follow it.
A public member can be accessed from outside the class anywhere within the scope of the class object.

We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Thus
we declare two objects of class Box:

Box Box1;// Declare Box1 of type Box


Box Box2;// Declare Box2 of type Box

Both of the objects Box1 and Box2 will have their own copy of data members.

Accessing the Data Members:

The public data members of objects of a class can be accessed using the direct member access operator (.).

#include<iostream>
56
usingnamespace std;

classBox
{
public:
double length;// Length of a box
double breadth;// Breadth of a box
double height;// Height of a box
};

int main()
{
BoxBox1;// Declare Box1 of type Box
BoxBox2;// Declare Box2 of type Box
double volume =0.0;// Store the volume of a box here

// box 1 specification
Box1.height =5.0;
Box1.length =6.0;
Box1.breadth =7.0;

// box 2 specification
Box2.height =10.0;
Box2.length =12.0;
Box2.breadth =13.0;
// volume of box 1
volume=Box1.height *Box1.length *Box1.breadth;
cout<<"Volume of Box1 : "<< volume <<endl;

// volume of box 2
volume=Box2.height *Box2.length *Box2.breadth;
cout<<"Volume of Box2 : "<< volume <<endl;
return0;
}

Output:

Volume of Box1 : 210


Volume of Box2 : 1560

Member functions

Member functions are the functions, which have their declaration inside the class definition and works on the data
members of the class. The definition of member functions can be inside or outside the definition of class.

If the member function is defined inside the class definition it can be defined directly, but if its defined outside the
class, then we have to use the scope resolution :: operator along with class name along with function name.

Example :
class Cube
{
public:
int side;
int getVolume(); // Declaring function getVolume with no argument and return type int.
};

57
If we define the function inside class then we don't not need to declare it first, we can directly define the function.
class Cube
{
public:
int side;
int getVolume()
{
return side*side*side; //returns volume of cube
}
};

But if we plan to define the member function outside the class definition then we must declare the function inside
class definition and then define it outside.
class Cube
{
public:
int side;
int getVolume();
}

int Cube :: getVolume() // defined outside class definition


{
return side*side*side;
}

The main function for both the function definition will be same. Inside main() we will create object of class, and will
call the member function using dot . operator.
int main()
{
Cube C1;
C1.side=4; // setting side value
cout<< "Volume of cube C1 ="<< C1.getVolume();
}

Access Specifier: Private and Public:

In C++, structures have public and private members.


Access specifiers defines the access rights for the statements or functions that follows it until another access
specifier or till the end of a class.
The three types of access specifiers are "private", "public", "protected".
private:
o The keyword private followed by a colon is used to declare subsequent members to have private
access.
o The members declared as "private" can be accessed only within the same class and not from outside
the class.
o Class member functions can use private members, and friend functions of the class can use private
members.

public:
The members declared as "public" are accessible within the class as well as from outside the class.
protected:

58
The members declared as "protected" cannot be accessed from outside the class, but can be
accessed from a derived class. This is used when inheritaance is applied to the members of a class.

Data hiding:

Data hiding prevents the functions of a program to access directly the internal representation of a class type. The
access restriction to the class members is specified by the labeled public, private, and protected sections within the
class body. The keywords public, private, and protected are called access specifiers.

A class can have multiple public, protected, or private labeled sections. Each section remains in effect until either
another section label or the closing right brace of the class body is seen. The default access for members and classes
is private.

classBase{

public:

// public members go here

protected:

// protected members go here

private:

// private members go here

};

The public members:

A public member is accessible from anywhere outside the class but within a program. We can set and get the
value of public variables without any member function.
#include<iostream>

usingnamespace std;

classLine
{
public:
double length;
voidsetLength(doublelen);
doublegetLength(void);
};

// Member functions definitions


doubleLine::getLength(void)
{
return length ;
}

voidLine::setLength(doublelen)
{
length=len;
}

59
// Main function for the program
int main()
{
Lineline;

// set line length


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

// set line length without member function


line.length=10.0;// OK: because length is public
cout<<"Length of line : "<<line.length<<endl;
return0;
}

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

Length of line : 6
Length of line : 10

The private members:

A private member variable or function cannot be accessed, or even viewed from outside the class. Only the
class and friend functions can access private members.
By default all the members of a class would be private, for example in the following class width is a private member,
which means until we label a member, it will be assumed as private member:
classBox
{
double width;
public:
double length;
voidsetWidth(doublewid);
doublegetWidth(void);
};

We define data in private section and related functions in public section so that they can be called from outside of
the class

#include<iostream>

usingnamespace std;

classBox
{
public:
double length;
voidsetWidth(doublewid);
doublegetWidth(void);

private:
double width;
};

// Member functions definitions


doubleBox::getWidth(void)
60
{
return width ;
}

voidBox::setWidth(doublewid)
{
width=wid;
}

// Main function for the program


int main()
{
Boxbox;

// set box length without member function


box.length=10.0;// OK: because length is public
cout<<"Length of box : "<<box.length<<endl;

// set box width without member function


// box.width = 10.0; // Error: because width is private
box.setWidth(10.0);// Use member function to set it.
cout<<"Width of box : "<<box.getWidth()<<endl;

return0;
}

Result:

Length of box : 10
Width of box : 10

The protected members:

A protected member variable or function is very similar to a private member but it provided one additional
benefit that they can be accessed in child classes which are called derived classes.

Following example is similar to above example and here width member will be accessible by any member function of
its derived class SmallBox.
#include<iostream>
usingnamespace std;

classBox
{
protected:
double width;
};

classSmallBox:Box// SmallBox is the derived class.


{
public:
voidsetSmallWidth(doublewid);
doublegetSmallWidth(void);
};

// Member functions of child class


doubleSmallBox::getSmallWidth(void)
61
{
return width ;
}

voidSmallBox::setSmallWidth(doublewid)
{
width=wid;
}

// Main function for the program


int main()
{
SmallBox box;

// set box width using member function


box.setSmallWidth(5.0);
cout<<"Width of box : "<<box.getSmallWidth()<<endl;

return0;
}

Result:

Width of box : 5

Class Scope:

Classes provide an encapsulation technique.


Conceptually, it makes sense that all names declared within a class be treated within their own scope, as
distinct from external names, namespace names, function names, and other class names, creating a need for
a scope resolution operator.

Scope Resolution Operator

The scope resolution operator, the highest-precedence operator in the language, comes in two forms.
The unary form is used to uncover or to access a name that has external scope and has been hidden by local
or class scope.
The binary form places the class or namespace identifier before the operator and the identifier after the
operator.

Nested Classes:

A class can be created inside of another class. A class created inside of another is referred to as nested
Nesting allows local hiding of names and local allocation of resources.
This is often desirable when a class is needed as part of the implementation of a larger construct.

62
Static Member:

Static members are special members, initialized to zero when the first object of its class is created. No other
initialization is permitted. Only one copy of the member is created for the entire class and is shared by all the objects
of that class. It is visible only with in the class, but life time is entire program.

Ex, static int number;

Outside the class we have to give the definition for static data members

Syntax: int student::number;

Example:
#include<iostream.h>
class item
{
static int count;
public:
voidsetdata()
{
count++;
}
voidshowcount()
{
cout<<"\ncount";
cout<<count<<"\n";
}
};
int item::count;
int main()
{
itema,b,c;
a.showcount();
b.showcount();
c.showcount();
a.setdata();
b.setdata();
c.setdata();
a.showcount();
b.showcount();
c.showcount();
63
return 0;
}
OUTPUT:
0
0
0
3
3
3

Static Member Function

1. A static member function can have access to only other static members declared in the class.
2. A static member function can be called using the class name
class name :: function name

static void showcount (void)


{
cout<< count: << count << \n;
}
3. static member function is similar to non member function. The only difference is that it is known
only in our class.
4. Remember non member functions can be know to all the classes of the program.
Example program:
#include<iostream.h>
class test
{
int code;
staticint count;
public:
voidsetcode(void)
{
code=++count;
}
voidshowcode(void)
{
cout<<" object number:"<<code;
}
static void showcount(void)
{
cout<< "count:" <<count ;
}
};
int test::count;
intmain()
{
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();

64
t1.setcode();
test::showcount();
t2.setcode();
test::showcount();
t2.showcode();
return 0;
}
OUTPUT:
count:2
count:3
count:4
object number:4

Const member functions:


If a member function does not alter any data in the class, then we declare it as a const member function
void display() const
{
cin>>number;
cout<<number is<<number;
}
const qualifier appended both declaration and definition.
Compiler will generate an error msg if such functions try to alter the data.
constant objects:
const classname objectname;
Ex, const student obj;
It calls only constant member functions, it cannot access any non-member functions.

#include<iostream.h>
#include<conio.h>
class test
{
public:
int a;
void display()const;
};
void test::display()const
{
// a=a+10; error code cannot be modified
cout<<endl<<"Accessing value of a using constant member
function:"<<a<<endl;

void main()
{
test t;
clrscr();
t.a=10;
t.display();
getch();
}
Output:

65
Accessing value of a using constant member function:10

this POINTER:

C++ has access to its own address through an important pointer called this pointer. Using the keyword this
we can access the data member in the object.
this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may
be used to refer to the invoking object.
Friend functions do not have this pointer, because friends are not members of a class. Only member
functions have this pointer.
This pointer cannot access static data member functions.

Syntax:
i). Accessing members of the current object using this pointer:
this->datamember_name;
this->member_function( );
Ex: this->rollno=101;
this->display();

#include<iostream.h>
class assign
{
intx,y;
public:
assign(inta,int b)
{
x=a;
y=b;
}
assign operator =(assign ob)
{
y=ob.y;
return *this;
}
void display()
{
cout<<the output is:;
cout<<x<<endl<<y;
}
};
void main( )
{
assign A(20,30),B(100,200);
A=B;
A.display();
}
OUTPUT:
The output is:
20
200

66
OBJECT CREATION AND DESTRUCTION

The Class Constructor:


A class constructor is a special member function of a class that is executed whenever we create new objects of that
class.

A constructor will have exact same name as the class and it does not have any return type at all, not even void.
Constructors can be very useful for setting initial values for certain member variables.

Rules to be followed to construct constructor:

Constructor should be declared in the public section

They are invoked automatically when the objects are created.

They do not have return value specification, not even void is allowed.

It has the same name as class name.

Types of constructors

1. Default constructors constructor without parameter

2. Parameterized constructors constructor with parameter

3. Copy constructors copying the value of one constructor to another by passing object as a reference

Syntax

Class classname

public:

classname()

//constructor body

};

#include<iostream>

usingnamespace std;

class Line
{
public:
voidsetLength(doublelen);
doublegetLength(void);
Line();// This is the constructor

67
private:
double length;
};

// Member functions definitions including constructor


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

voidLine::setLength(doublelen)
{
length=len;
}

doubleLine::getLength(void)
{
return length;
}
// Main function for the program
int main()
{
Lineline;

// set line length


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

return0;
}

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

Object is being created


Length of line : 6

Parameterized Constructor:

A default constructor does not have any parameter, but if you need, a constructor can have parameters. This helps
you to assign initial value to an object at the time of its creation as shown in the following example:

#include<iostream>

usingnamespace std;

classLine
{
public:
voidsetLength(doublelen);
doublegetLength(void);
Line(doublelen);// This is the constructor

private:
double length;
};

// Member functions definitions including constructor

68
Line::Line(doublelen)
{
cout<<"Object is being created, length = "<<len<<endl;
length=len;
}

voidLine::setLength(doublelen)
{
length=len;
}

doubleLine::getLength(void)
{
return length;
}
// Main function for the program
int main()
{
Lineline(10.0);

// get initially set length.


cout<<"Length of line : "<<line.getLength()<<endl;
// set line length again
line.setLength(6.0);
cout<<"Length of line : "<<line.getLength()<<endl;

return0;
}

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

Object is being created, length = 10


Length of line : 10
Length of line : 6

COPY CONSTRUCTOR

A copy constructor takes a reference to an object of the same class as itself as an argument.
student(student &a)
{
id=a.id;
}
A copy constructor is used to declare and initialize an object from another object (ie, all the datas should be
copied from one object to another object)
For example:
student obj1(50);
student obj2(obj1);
The above statement defines the object obj2 and at the same time initializes or copies the values of
obj1
Another form of this statement is
student obj2=obj1;
The process of initializing through a copy constructor is known as copy initialization.
#include<iostream.h>

class code
69
{
int id;
public:
code(int a)
{
id=a;
}
code( code &x)
{
id=x.id;
}
void display()
{
cout<<id;
}
};
void main( )
{
code A(100);
code B(A);
code C=A;
cout<< Id of A object is:;
A.display();
cout<< Id of B object is:;
B.display();
cout<< Id of C object is:;
C.display();
}
OUTPUT:

Id of A object is:100

Id of B object is:100

Id of C object is:100

DESTRUCTOR:

When an object is no longer needed it can be destroyed.

A class can have another special member function called destructor, which is called when the object is
destroyed.

Destructor is a member function having the character ~(tilde) followed by the name of its class and brackets.

It should be declared as follows,

~classname( );

The destructor can be called automatically when the object goes out of scope and is no longer needed.

General format

classclassname

{
70
// private members

public:

~classname( ); // destructor prototype or declaration

};

class name :: ~ classname( )

// destructor body definition

Rules for defining the destructor

The destructor name is same as the class name but prefixed by a tilde(~).

Unlike constructor, destructor does not take any arguments

The destructor has no return type like the constructor, since it is invoked automatically whenever the object
goes out of scope.

There can be only one destructor in each class. The overloading is not possible.

Destructor must be declared in the public section of a class, so that it is accessible to all its users.

#include<iostream>

classLine
{
public:
voidsetLength(doublelen);
doublegetLength(void);
Line();// This is the constructor declaration
~Line();// This is the destructor: declaration

private:
double length;
};

// Member functions definitions including constructor


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

voidLine::setLength(doublelen)
{
length=len;
}

71
doubleLine::getLength(void)
{
return length;
}
// Main function for the program
int main()
{
Lineline;

// set line length


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

return0;
}

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

Object is being created


Length of line : 6
Object is being deleted

FRIEND FUNCTION:

A friend function is a special type of function which has given a special permission to access both private a protected
data members and member function.

A class can allow non-member functions (friend) and classes to access its own private data members,
by making them friends.

The friend function has its argument as objects. User can declare the friend function as either private
or public.

The friend function can be invoked without the use of object.

Syntax:

friend return_typefunction_name(list of argument);

Where the arguments are the object of corresponding class.

#include<iostream>

usingnamespacestd;

classBox
{
double width;
public:
friendvoidprintWidth(Boxbox);
voidsetWidth(doublewid);
};

// Member function definition


voidBox::setWidth(doublewid)
{
width=wid;
}
72
// Note: printWidth() is not a member function of any class.
voidprintWidth(Boxbox)
{
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout<<"Width of box : "<<box.width<<endl;
}

// Main function for the program


int main()
{
Boxbox;

// set box width without member function


box.setWidth(10.0);

// Use friend function to print the wdith.


printWidth( box );

return0;
}

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

Width of box : 10

Example program to find the mean using friend Example program to find the complex number using
function: friend function:

#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
class sample class over
{ {
private: float x,y;
int a; public:
int b; void setdata( float a, float b)
public: {
void setvalue() x= a;
{ y= b;
a=20; }
b=25; friend over operator +(over o1, over o2);
} void display( )
friend float mean(sample s); {
}; cout<<x<<"+"<<y;
float mean(sample s) }
{ };
return float(s.a+s.b)/2; over operator +(over o1,over o2)
} {
void main() over temp;
{ temp.x= o1.x + o2.x;
clrscr(); temp.y= o1.y + o2.y;
sample x; return(temp);
x.setvalue(); }
cout<<"mean value"<<mean(x)<<"\n"; void main( )
getch(); {
} over o1,o2 , o3;
73
o1. setdata( 11.5, 2.5);
o2. setdata( 6.5, 4.5);
OUTPUT: o3= o1+o2;
meanvalue=22.5 cout<<"\nthe result is:";
o3. display ( );
}

OUTPUT:

the result is:


18+7

OPERATOR OVERLOADING :

Operator overloading is the process of making an operator to perform different task.


The operator overloading is a mechanism of giving special meaning to an operator.
Operator overloading is a method to achieve POLYMORPHISM concept.

Defining operator overloading:

To define an additional task to an operator, we must specify what it means in relation to the class to which
the operator is applied. This is done with the help of a special function called operator function which describe the
task.
General format of operator function:

return_type classname :: operator op (arg list)


{
// function body;
}
In this argument list, the member function has no argument for unary operators and only one for binary
operators.

Types of operator overloading:


1. Unary operator overloading
2. Binary operator overloading

Unary operator overloading:

The operator which takes only one operand for performing the job is called unary operator.

Consider the unary minus ( - ) operator : Normally this operator can be used change the sign of an
operand when applied to a basic data item:

The normal unary operator can be overloaded by using the special member function called operator op (
).

The overloaded unary operator can be applied to an object.

The unary minus when applied to an object should change the sign of each data members

/* Example program for unary operator overloading*/ /* Example program for increment operator
#include<iostream.h> overloading*/
class over #include<iostream.h>
{ class over
int x, y, z; {
public: int x, y, z;
74
void setdata( int a,int b, int c) public:
{ void setdata( int a,int b, int c)
x= a; {
y= b; x= a;
z= c; y= b;
} z= c;
void operator ( ); }
void display( ); void operator ++( );
}; void display( );
void over : : operator ( ) };
{ void over : : operator ++( )
x = -x; {
y = -y; x = ++x;
z = -z; y = ++y;
} z = ++z;
void over : : display( ) }
{ void over : : display( )
cout<< x<<endl<<y<<endl<<z; {
} cout<< x<<endl<<y<<endl<<z;
void main( ) }
{ void main( )
over u; {
u. setdata( 20,-50,30); over u;
cout<<before calling unary-function; u. setdata( 20,50,30);
u. display( ); cout<<before calling increment function;
-u; u. display( );
cout<<after calling unary-function; ++u;
u.display( ); cout<<after calling increment function;
} u.display( );
OUTPUT: }
before calling unary function OUTPUT:
20 -50 30 after calling increment function
after calling unary function 20 50 30
-20 50 -30 after calling increment function
21 51 31

Binary operator overloading:

The operator takes two operand to perform its operation is called binary operator.
Consider the example of binary operator +, which will be used for adding two data member normally.
Now using overloading process we can overload the + operator by operator op special member
function.
Then the overloaded binary operator can be used for adding the object( user defined types)
Rules for overloading binary operator:

The binary overloaded operator function takes the first object as implicit operand and the second
operand must be passed explicitly.
The data members of the first objects are accessed without using the dot operator.
The second argument members can be accessed using the dot operator is the argument is an object.

/* Example program for binary operator overloading*/

#include<iostream.h> void main( )


class complex {
{ complex c1,c2 , c3;
float x,y; c1. setdata( 10, 3.5);
75
public: c2. setdata( 5.5, 2.5);
void setdata( float r, float i) c3= c1 + c2;
{ cout<< Ist complex number:;
x= r; c1. display( );
y= i; cout<< IInd complex number:;
} c2. display ( );
complex operator + ( complex c2) cout<< added complex number:;
{ c3. display ( );
complex temp; }
temp. x= x + c2. x;
temp. y= y + c2. y; OUTPUT:
return(temp); Ist complex number
} 10 + i 3.5
void display( ) IInd complex number:
{ 5.5 + i 2.5
cout<<x << +i<<y; added complex number
} 15. 5 + i 6.0
};

STANDARD TEMPLATE LIBRARY(STL)

STL is defined as a collection of generic classes and functions. The STL is a set of abstract datatypes,
functions, and algorithms designed to handle user-specified datatypes. This is the part of ANSI standard C++ class
Library.

STL components are now part of the standard C++ library and are defined in the namespace std, using the using
namespace directive.

ADVANTAGES:

1. To save the time and effort


2. to reuse the same code etc

Components of STL

The three key components of STL are

Containers
Algorithms
Iterators

Relationship between the three STL Components:

76
The three components work in conjunction with one another to provide support to a variety of programming
solutions. Algorithms employ iterators to perform operations stored in containers.

A container is an object that actually stores data .For example an array of elements.
Algorithms in the STL are procedures that are applied to containers to process their data, for example search
for an element in an array, or sort an array.
Iteratorsare a generalization of the concept of pointers, they point to elements in a container, for example
you can increment an iterator to point to the next element in an array

CONTAINER:

Containers are objects that hold data, either built-in data types like int and float, or class objects. STL containers
are implemented by template class. Each container class defines the set of functions that can be used to manipulate
its contents. STL defines ten containers which are grouped into three categories.

Three major categories of containers


Sequence containers
Associative containers
Derived containers

77
SEQUENCE CONTAINER:

A sequence container stores elements in a linear sequence like a line. Each element is related to other elements
by its position along the line. All elements can be expanded and supported to each other.

STL provides three types of sequence Containers:

Vector - it allows insertion and deletion at back it permits direct access to any element. And the header file
used is < vector >. The iterator used is Random access.

Deque - double ended queue it allows insertion and deletion at both ends, permits direct access to any
element and the header file is < deque>. The iterator used is Random access.
List A bidirectional linear list allows insertion and deletion anywhere ,and the header file is < list >. The
iterator used is Bidirectional.

Elements in all these containers can be accessed using an iterator.

ASSOCIATIVE CONTAINER:

These containers are designed to support direct access to elements using keys. They are not sequential. Four types of
associative containers are

Set:- An associate container for storing unique sets.The iterator used is bidirectional
access and the header file is < set >. No duplicates allowed.

Multiset :- Used for storing non unique set (duplicates allowed.) the header file is
< set >. The iterator used is bidirectional access.

Map:- Used for storing unique key/value header file is <map>. The iterator used is
bidirectional access. Each key is associated with only one value (one to one

mapping)

Multimap:- An associate container for storing key/value pairs in which one key may be associated with
more than one value. (on eto many mapping) The header file used is <map> and the iterator used is
Bidirectional.

78
All these containers store data in a structure called tree which provides fast searching,insertion, and
deletion.Set and multiset can store a number of items and provide operations for manipulating them using the values
as the keys. Map and multimap are used to store pair of items, one called the key and other called value.Map allows
only one key for a given value. Multimap permits multiple keys.

DERIVED CONTAINER:

The derived container can be created from different sequence of containers. STL provides three
derived containers namely stack queue and priority queue. These are also known as container adaptors.

Stack - Last in first out no iterator- header file is < stack >
Queue - First in first out no iterator- header file is < queue>
priority queue - first element out is always with the highest priority- header file is <queue>- no iterator

Derived containers do not support iterators and we cannot use them for data manipulation. It support two member
functions pop() and push() for implementing deleting and insertion operations.

ALGORITHMS:

Algorithms are defined as the step by step process for manipulating functions. STL provides more than sixty
standard algorithms which are used to support complex operation

Types:

1. retrieve or non mutating algorithm-(e.g) find(), search()


2. Mutating algorithm:- copy(), replace()
3. sorting algorithm: -sort(), merge()
4. set algorithm:- set_union(), set_difference()
5. relational algorithm:- min(), equal()

ITERATORS:

Iterators behave like pointers and are used to access individual elements in a container.
They are often used to traverse from one element to another & vice versa.
Types:

1. Input
2. Output
3. Forwrad
4. Bidirectional
5. Random

The input and output support the least functions. They can be used only to traverse in a container.
The forward iterator supports all operations of input and output iterators and also retains its
position in the container.
A bidirectional iterator supporting all forward iterator operations provides the ability to move in the
backward direction in the container.
A random access container combines the functionality of a bidirectional iterator with an ability to
jump to an arbitary location.

UNIT III
ADVANCED PROGRAMMING
79
Templates, Generic Programming, and STL-Inheritance-Exceptions-OOP Using C++.
TEMPLATES:

Templates
Templates enables us to define generic classes and functions
Supports generic programming
Generic Programming
Is an approach where generic types are used as parameters in algorithms
Generic programs work for a variety of suitable data types and data structures
A template can be used to create a family of classes or functions
Example:
template for an array enable us to create arrays of various data types such as int array and float
array
template for a function, say mul() helps us for multiplying int, float and double type values
Template is defined with a parameter that would be replaced by a specified data type at the time of
actual use of the class or function, the templates are sometimes called parameterized classes or function

Template Definition:
template<class T>
The prefix tells the compiler that we are going to declare a template and use T as a type name in the
declaration
The type T may represent a class name as well
A class created from a class template is called a template class.

Syntax for defining an object of a template class is:

classname<type> objectname(arglist);
This process of creating a specific class from a class template is called instantiation.

/* Example program for template using single /* Example program for template using single
parameters*/ parameters*/

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


# include <string.h> # include <string.h>
template<class T > template<class T >
Class sample Class sample
{ {
Private: Private:
T value; T a;
Public: T b;
Void read() Public:
{ Void read()
Cout<<enter values; {
Cin>>value; Cout<<enter values;

80
} Cin>>a>>b;
Void display() }
{ Void display()
Cout<<value=<<value; {
} Cout<<value=<<a<<b;
}; }
void main() };
{ void main()
Sample<int>s1; {
Sample <float>s2; Sample<int>s1;
S1.read(); Sample <float>s2;
S1.display(); S1.read();
S2.read(); S1.display();
S2.display(); S2.read();
S2.display();
}
Output: }
Enter values 10 Output:
Value=10 Enter values 10 20
Enter values 10.5 Value=10 20
Value=10.5 Enter values 10.5 20.5
Value=10.5 20.5

CLASS TEMPLATES WITH MULTIPLE PARAMETERS

Can use more than one generic data type in a class template
They are declared as a comma separated list within the template specification

/* Example program for template using Multiple /* Example program for template using Multiple
parameters*/ parameters*/

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


#include<conio.h> # include <string.h>
Template<class T1, class T2> template<class T1,class T2>
Class test class sample
{ {
T1 a; private:
T2 b; T1 a, z;
public: T2 b;
test(T1 x, T2 y) public:
{ void read()
a=x ; {
b=y ; cout<<enter values;
} cin>>a>>b;
void show() z=a+b;
{ }
cout<<a<<\n<<b<<endl; void display()

81
} {
}; cout<<value=<<z;
void main() }
{ };
test <int, float>test1(123,1.2); void main()
test <float,char>test1(12.3,w); {
test1.show(); sample<float ,int>s1;
test2.show(); s1.read();
getch(); s1.dispaly();
} getch():
}

Output: Output:

123 1.2 Enter values 10.3 20


12.3 w Value=30.3

FUNCTION TEMPLATES

template<class T>
returntype functioname (T arg)
{
// ....
// Body of function
// with type T
// wherever appropriate
// ....
}
# include <iostream.h> # include <iostream.h>
# include <string.h> # include <string.h>
template<class T > template<class T >
void display(T x) void display(T x, T y)
{ {
cout << x; cout << x<<y;
} }
int main() int main()
{ {
display(1999); display(1999.2000);
display(12.34) display(12.34,10.5)
display(w); display(w,s);
return 0; return 0;
} }

OUTPUT: OUTPUT:
1999 1999 2000
12.34 12.34 10.5
w ws

Example for swapping two int and float values:

82
FUNCTION TEMPLATES WITH MULTIPLE PARAMETERS
Syntax:
template<class T1,class T2, .>
returntype functioname (T1 arg, T2 arg ,..)
{
// ....
// Body of function
// with type T
// wherever appropriate
// ....
}

# include <iostream.h>
# include <string.h>
template<class T1, class T2>
void display(T1 x, T2 y)
{
cout << x << " " << y << "\n";
}
void main()
{
display(1999, "EBG");
display(12.34, 1234);
getch();
}
OUTPUT:
1999 EBG
12.34 1234

MEMBER FUNCTION TEMPLATES

83
/* Example program for member function template<class T >
templates*/ void sample<t>::display()
{
# include <iostream.h> cout<<value=<<value;
# include <string.h> }
template<class T > void main()
Class sample {
{ sample<int>s1;
Private: sample <float>s2;
T value; s1.read();
public: s1.dispaly();
void read() s2.read();
void display() s2.dispaly();
};
}
template<class T > Output:
void sample <t>:: read() Enter values 10
{ Value=10
cout<<enter values; Enter values 10.5
cin>>value; Value=10.5
}

INHERITANCE :

REUSABILTY mechanism.
The reusable property will reduce the debugging time.
The time overhead and cost overhead will be reduced.
Definition:
The mechanism of deriving the new class from an old one is called inheritance. The old class is called as base
class and the new class is called as derived class.

Types of Inheritance:

1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hybrid inheritance

SINGLE INHERITANCE
The new class can be derived from only one base class is called single inheritance.

84
The general format is
class derived_classname : visibility mode baseclassname
{
..... // body of derived class
};
Visibility mode is optional; it may be either private or public. The default visibility mode is private.

EXAMPLE:
class abc : private xyz
{
// body of abc
};
class abc : public xyz
{
//body of abc
};
class abc : xyz // private derivation by default
{
//body of abc
};

EXAMPLE PROGRAM FOR SINGLE INHERITANCE:

#include <iostream.h> void display( )


#include<conio.h> {
class A cout<<"data1="<<data1<<endl;
{ cout<<"\n data2="<< data2;
protected: }
int data1; };
public:
void getdata(int x) void main( )
{ {
data1 = x; B s;
} s.getdata(10);
}; s.setdata(20);
class B: public A s.display( );
{ }
private: OUTPUT:
int data2;
public: data1=10
void setdata(int y) data2=20
{
data2 = y;
}

MULTILEVEL INHERITANCE
The multilevel inheritance is defined as, the new class is derived from another derived class. It is
represented as,

Here the class a serves as a base class for the derived class b which in turn serves as a base class for the
derived class c. The derived class is defined as,

SYNTAX:
class a
{
//body of base class a
85
};
class b : public a
{
//body of intermediate base class b
};
class c : public b
{
//body of derived class
};

MULTIPLE INHERITANCE

A class with several base class is called multiple inheritance.

/* Example program for Multiple Inheritance*/ Example Program For Multilevel inheritance
#include<iostream.h> #include <iostream.h>
#include<conio.h> class student
class A {
{ protected:
protected: int rollno:
int rollno; public:
public: void getroll(int x)
void getroll(int x) {
{ rollno = x;
rollno=x; }
} };
}; class test: public student
class B {
{ protected:
protected: float sub1, sub2;
int sub1,sub2; public:
public: void getmark(int y, int z)
void getmark(int y,int z) {
{ sub1 = y; sub2= z;
sub1=y; }
sub2=z; };
86
} class result : public test
}; {
class C:public A,public B float total;
{ public:
int total; void display( )
public: {
void display() total = sub1 + sub2;
{ cout<<rollno<<sub1<<sub2;
total=sub1+sub2; cout<<total;
cout<<"rollno:"<<rollno; }
cout<<"sub1:"<<sub1; };
cout<<"sub2:"<<sub2; void main( )
cout<<"total:"<<total; {
} result s;
}; s.getroll(101);
void main() s.getmark(90, 100);
{ s.display( );
clrscr(); }
C s;
s.getroll(435);
s.getmark(100,90);
s.display();
getch();
}

OUTPUT:
rollno: 435
sub1: 100
sub2: 90
total: 190

HYBRID INHERITANCE
Combination of multiple and multi level inheritance is called hybrid inheritance.

Example program for Hybrid inheritance:

#include <iostream.h> public:


#include<conio.h> void getscore(int a)
class student {
{ score=a;
protected: }
int rollno: };
public:
void getroll(int x) class result : public test, public sports
87
{ {
rollno = x; float total;
} public:
}; void display( )
class test: public student {
{ total = sub1 + sub2;
protected: cout<<rollno<<sub1<<sub2;
float sub1, sub2; cout<<total;
public: }
void getmark(int y, int z) };
{ void main( )
sub1 = y; sub2= z; {
} result s;
}; s.getroll(101);
s.getmark(90, 100);
class sports s.getscore(2000);
{ s.display( );
protected: getch();
int score; }

VIRTUAL BASE CLASSES

In this method, the child inherits the traits of grandparent via two separate paths. Members of grand
parent are inherited into child twice

Duplication of inherited members to these multiple path can be avoided by making the common
base class as virtual base class

EXAMPLE:
class A { -----};
class B : virtual public A { ---------- };
class C : virtual public A { ---------- };
class D : public B, public C { ------ };

- In virtual base class, only one copy of the class is inherited regardless of how many inheritance paths
exist
#include <iostream.h> class result: public test, public sports
#include conio.h> {
class student int total;
{ public:

88
protected: void display()
int rollno; {
public: total= sub1+sub2+score;
void getroll (int x) cout<<rollno:<<rollno;
{ cout<< total:<<Score:<<total;
rollno = x; }
} };
}; void main( )
class test: virtual public student { result s;
{ s.getroll(101);
protected: s.getmark(90,98);
int sub1, sub2; s.getscore(2000);
public: s. display( );
void getmark (int y, int z) }
{
sub1 = y; sub2 = z;
}
};
class sports : virtual public student
{ protected:

public:
int score;
Rollno: 101
void getscore (int a ) Total: 188
{
score=a;
} Score: 2000
};

POLYMORPHISM

Polymorphism is a powerful feature of the object oriented programming language C++.


The overloading member functions are selected for invoking by matching arguments, both type and number.
This information is known to the compiler at the compile time. This is called early binding or static binding or
compile time polymorphism.
Two types of Poymorphism:

89
VIRTUAL FUNCTIONS (RUNTIME POLYMORPHISM. )

When we use the same function name in base and derived classes, the function in the base classes is
declared as virtual using keyword virtual preceding its normal declaration.

The member function that can be changed at runtime is called virtual function.

Syntax for defining virtual function

class classname
{
public:
virtual returntype functionname (arguments)
{
.....
.....
}
};
The virtual function should be defined in the public section of a class. When one function is made virtual
and another one is normal, and compiler determines which function to create at runtime. In this we have to
create a basepointer.

If the base pointer points to a base class object means it will execute the base class function.

If the base pointer points to a derived class object means it will execute the derived class function.

EXAMPLE PROGRAM:

#include <iostream.h>
class A
{
public:
void displayA( )
{
cout<<Welcome;
}
virtual void show( )
{
cout<<Hello;
}
};
class B: public A
{
public:
void display( )
{
cout<<Good Morning;
}
void show( )
{
cout<<Hai;
}
};
void main( )
{
A S1;
B S2;
A *bptr;
90
bptr = &S1;
bptr->show( ); //Calls base class show
bptr=&S2;
bptr->show( ); //Calls derived class show
S2.displayA( ); //Calls base class display A
S2.display( ); //Calls derived class display
}

OUTPUT:
Hello
Hai
Welcome
Good Morning
Rules for virtual function:

Virtual function must be a members of some class.

They cannot be static members.

They are accessed by using base pointer.

A virtual function in a base class must be defined even though it may not be used.

A prototype (or declaration) of a base class virtual function and all the derived class version must be
identical.

We cannot use a pointer to a derived class to access an object of the base class.

PURE VIRTUAL FUNCTIONS

A virtual function, equated to zero is called a pure virtual function.

It is function declared in a base class that has no definition relative to the base class .

A class containing such pure function is called an abstract class.

Syntax,

virtual void display()=0;

ERROR (Exception) HANDLING

The exception refers to unexpected condition in a program.


The unexpected conditions could be faults, causing an error which in turn causes the program to fail.
The error handling mechanism of C++ is generally referred to as exception handling.

Types of Exceptions

Synchronous Exception
Asynchronous Exception

Synchronous Exception
91
The exception which occurs during the program execution, due to some fault in the input data or
technique that is not suitable to handle the current class of data, with in the program are known as
synchronous exception.
Example: out of range, divide by zero, overflow, underflow
Asynchronous Exception

The errors that are caused by events beyond the control of the program are called asynchronous
exceptions.
Example: disk failure
Exception handling Mechanism:

The purpose of the exception handling mechanism is to provide means to detect and report an
exceptional circumstance so that appropriate action can be taken.
The exception handling mechanism consists of the following task or operations:
Find the problem ( hit the exception)
Inform that an error has occurred (throw the exception)
Receive the error information ( catch the exceptions)
Take corrective actions( handle the exceptions)
Error handling basically consists of two segments;
One to detect and to throw exceptions
Other to catch the exceptions and to take appropriate actions.
Exception Handling Model:
The exception handling mechanism uses three blocks try, throw, catch. The relationship of those
three exception handling model shown below
Diagram:

The keyword try is used to preface a block of statements (surrounded by braces) which may generate
exceptions. These blocks of statements known as try bock.
When an exception is detected, it is thrown using a throw statement in the try block.
A catch block defined by the keyword catch catches the exception thrown by the throw statement in the try
block, and handle it appropriately.
General format:

try

. // block of statements which detects and

throw exception // throws an exception

catch ( type arg)

// block of statements that handles the


exception

92
}

..

When the try block throws an exception, the program control leaves the try block and enters the catch
statement of the catch block.
Exceptions are objects or variables used to transmit information about a problem.
If the type of object thrown matches the arg type in the catch statement, then catch block is executed for
handling the exception.
If they do not match, the program is aborted with the help of the abort() function which is invoked
automatically.
The catch block may have more than one catch statements, each corresponding to a particular type of
exception.
For example if the throw block is likely to throw two exception, the catch block will have two catch
statements one for each type of exception. Each catch statement is called is exception handler.
When no exception is detected and thrown, the control goes to the statement immediately after the catch
block. That is catch block is skipped.
Example:divide by zero

#include<iostream.h>

void main( )
RUN 1:
{
enter the values of x , y, z
int x, y, z;
50 30 20
cout<<enter the values of x, y, z; the result of z/ (x-y ) is: 1
cin>>x>>y>>z; RUN 2:
try Enter the values of x, y, z
{
30 30 20
exception caught x-y is : 0
if(x= =y)

throw y;

else

int d= z / ( x- y);

cout<<the result of z/ (x-y )is:<< d;

catch( int y)

cout<<exception caught x-y is << x-y ;

93
EX: 2

#include<iostream.h>

void divide ( int x, int y,int z) RUN:


{
cout<<we are inside the function; we are inside the try block
if(x= =y)
we are inside the function
throw (x-y);
else the result of z/ (x-y )is: -3
int d= z / ( x- y);
cout<<the result of z/ (x-y )is:<< d; we are inside the function
} exception caught x-y is: 0
void main( )
{
try
{
cout<< we are inside the try block;
divide( 10, 20, 30); // invoke divide ()
divide( 10, 10, 20); // invoke divide ()
}
catch( int i) // catches the exception
{
cout<<exception caught x-y is : <<i;
}
}

Multiple catches with object:

To throw an exception with an object it needs to define an abstract class.


Abstract class is nothing but a class with empty data members.
Class name is called as nameless object which is used to throw the exceptions

Example program for multiple catches:

#include<iostream.h>
void test(int a)
{
try
{
if(a==1) throw a; //int
else if(a==0) throw 'a'; //char
else if(a==-1) throw 1.0; //double
else
cout<<end of try block<<endl;
}
catch(char c)
94
{
cout<<caught a character<<endl;
}
catch(int m)
{
cout<<caught a int <<endl;
}

catch(double d)

{
cout<<caught a double<<endl;
}

void main()
{
cout<<testing multiple cathces;
cout<<a==1'<<endl;
test(1);
cout<<a==0'<<endl;
test(0);
cout<<a==-1'<<endl;
test(-1);
}

OUTPUT:

testing multiple cathces


a==1
caught a int
a==0
caught a character
a==-1
caught a double

Explanation:

The program when executed it invokes function test() with a=1, therefore it invokes

95
throw a an int exception. This matches the type of parameter m in catch2 and
catch2 handler is executed.

After the execution , immediately test() is again invoked with a=0, in this throw a an
character type exception is invoked and the first handler is executed.
For a==-1 , the double type exception is thrown.

Catch all exception

In some situations, we may not be able to realize all possible types of exceptions and therefore we may not
be able to design independent catch handlers to catch them.
In such situations ,we can force a catch statement to catch all exceptions instead of a certain type alone.
It should always be placed last in the list of handlers.
This type can be achieved by defining the catch statement using ellipses.

Catch()

statement for processing all exceptions

Catch() statement is used as a default statement along with other catch handlers. It can catch all exceptions which
are not handled explicitly.

Example program:

#include<iostream.h>

Void test(int x)

Try

if(x==0) throw x; //int

if(x==-1) throw x; //char

if(x==1) throw 1.0; //float

Catch() //catch all


96
{

cout<<caught an exception \n;

};

int main()

cout<<testing generic catch \n;

test(-1);

test(0);

test(1);

return 0;

OUTPUT:

Testing generic catch

Caught an exception

Caught an exeception

Caught an exeception

RETHROWING AN EXCEPTION:

A handler may decide to throw the exception caught without processing it. It invokes throw without any argument

EX: throw;
This implies that the current exception to be thrown to the next enclosing try/catch sequence and is caught
by a catch statement listed after that enclosing try block.

Example program:

#include<iostream.h>

Void divide(double x, double y)

{
97
cout<<insidde function \n;

try

if(y==0.0)

throw y; //throwing double

else

cout<<Division = <<x/y;

catch(double) //catch a double

cout<<caught double inside function \n;

throw; // rethrowing double

cout<<end of function \n ;

Int main()

cout<<Inside main;

try

divide(10.5,2.0);

divide(20.0,0.0);

catch(double)

cout<<caught double inside main \n;

cout<<end of main \n;

OUTPUT:

98
Inside main

Inside function

Division = 5.25

End of function

Inside function

Caught double inside function

Caught double inside main

End of main

Explanation:

When an exception is rethrown , it will not be caught by the same catch statement or any other catch in that group.

It will be caught by an appropriate catch in the outer try/catch sequence only.

EXCEPTION SPECIFICATIONS:

It is possible to restrict a function to throw only certain specified exceptions by adding a throw list clause to
the function definition

SYNTAX:

type function(arg-list) throw (type-list)

function body

Typelist:- specifies the type of exceptions that may be thrown.


Throwing any other type of exception will cause program termination.
If we want to prevent function from throwing any exception, we may do so by making the type list empty

Syntax: throw();

EXAMPLE:

99
#include<iostream.h>

Void test(int x) throw(int double)

Try

if(x==0) throw x; //char

else if(x==1) throw x; //int

else if(x==-1) throw 1.0; //double

cout<<end of function block;

};

void main()

cout<<testing throw restrictions \n;

cout<<x==-1 \n;

test(-1);

cout<<x==0 \n;

test(0);

cout<<x==1 \n;

test(1);

Catch(char c)

cout<<caught a character \n;

Catch(int m)

cout<<caught an integer \n;

Catch(double d)
100
{

cout<<caught an double \n;

Cout<<end of try catch system;

UNCAUGHT EXCEPTIONS:

If a propagating exception is not caught by any try-catch net , then it propagates all the way out of main().

In that case the program terminates usually with an uncaught exception error message.

UNIT IV

OVERVIEW OF JAVA
Data types, variables and arrays, operators, control statements, classes, objects, methods
Inheritance

INTRODUCTION TO JAVA

JAVA is a General purpose programming Language developed by Sun Microsystems of USA in


1991.Orginally called OAK by James Gosling, one of the inventor of Java Language.

101
simpler to use than C++ in many ways
gives up Cs low-level capabilities
currently approximately tied with C++ as the most widely used programming language
Used in many web-based applications
Widespread use in embedded systems (software that runs on computers included in
appliances, cars, etc)
Widely used for programming devices like video game consoles, BluRay players, smart
phones, etc.
Designed to allow identical code to produce the same results on many different platforms

Since Java is an object oriented programming language it has following features:

Reusability of Code
Emphasis on data rather than procedure
Data is hidden and cannot be accessed by external functions
Objects can communicate with each other through functions
New data and functions can be easily added

JAVA FEATURES:

1. Compiled and Interpreted

Usually a computer Language is either compiled or interpreted. Java combines both these approaches thus
making java a two stage systems. First , java compiler translates source code into what is known as byte code
instructions. Second java interpreter generates machine code that can be directly executed by the machine
that is running the java program.
2. Portable (Platform Independent)

Java programs can be easily moved from one system to another ,anywhere and anytime. changes and
upgrades in operating systems, processors and system resources will not force any changes in java programs.
3. Object Oriented

Java is a true object oriented language. Almost everything in java is an object. All program code and data
reside within objects and classes.
4. Robust and Secure

Java is a robust Language. It provides many safeguards to ensure reliable code. It has strict compile time and
run time checking for data types.java also incorporates the concepts of exception handling, which captures
serious errors and eliminates any risk of crashing the system.
Java was designed to allow secure execution of code across network. To make Java secure many of the
features of C and C++ were eliminated. The Absence of Pointers In Java ensures that programs cannot gain
access to memory locations without proper authorization.

5. Distributed

Java enables multiple programmers at multiple remote location to collaborate and work together on a single
project. With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and
access the objects across net via URLs.
6. Familiar, simple and small

Java does not use pointers, preprocessors header files, goto statements and many others. It also eliminates
operator overloading and multiple inheritance.
Java code looks like C++ code; In fact, java is a simplified version of C++.
102
7. Multithreaded and interactive

Multithreading means handling multiple tasks simultaneously. Java supports multithreaded programs. One
of the powerful aspects of the Java language is that it allows multiple threads of execution to run
concurrently within the same program A single Java program can have many different threads executing
independently and continuously. Multiple Java applets can run on the browser at the same time sharing the
CPU time.
8. High performance

Java performance is impressive for an interpreted language, mainly due to the use of intermediate bytecode.
9. Dynamic and Extensible

Java is a Dynamic Language. Java is capable of dynamically linking in new class libraries, methods and
objects. Java program support functions written in other languages such as C and C++ .

OOPS CONCEPTS
Four principles of Object Oriented Programming are
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

Abstraction

Abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of
objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.

Encapsulation

Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its
structure and behaviour. Encapsulation serves to separate the contractual interface of an abstraction and its
implementation.

* Hides the implementation details of a class.


* Forces the user to use an interface to access data
* Makes the code more maintainable.

Inheritance

Inheritance is the process by which one object acquires the properties of another object.

Polymorphism

Polymorphism is the existence of the classes or methods in different forms or single name denoting different
implementations.

GARBAGE COLLECTION

Automatic garbage collection is another great feature of Java with which it prevents inadvertent corruption
of memory.
Similar to C++, Java has a new operator to allocate memory on the heap for a new object.
103
But it does not use delete operator to free the memory as it is done in C++ to free the memory if the object
is no longer needed. It is done automatically with garbage collector.

JAVA APPLICATIONS

Java has evolved from a simple language providing interactive dynamic content for web pages to a
predominant enterprise-enabled programming language suitable for developing significant and critical
applications. Today, it is used for many types of applications including Web based applications, financial
applications, Gaming applications, embedded systems, Distributed enterprise applications, mobile applications,
Image processors, desktop applications and many more.
COMPARISON BETWEEN JAVA AND C++

1. Java does not support operator overloading.


2. Java does not have template classes as in C++.
3. Java does not support multiple inheritance of classes. This is accomplished using a new feature
called interface.
4. Java does not use pointers.
5. Java has replaced the destructor function with a finalize ( ) function..
6. Java does not support Global variables. Every variable and method is declared within a class and
forms part of that class.

Variable
Variable is name of reserved area allocated in memory.

1. int data=50;//Here data is variable


Types of Variable
There are three types of variables in java
local variable
instance variable
static variable

104
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It is not declared as
static.
Static variable
A variable that is declared as static is called static variable. It cannot be local.

Example to understand the types of variables


1. class A{
2. int data=50;//instance variable
3. static int m=100;//static variable
4. void method(){
5. int n=90;//local variable
6. }
7. }//end of class

Data Types in Java


In java, there are two types of data types
primitive data types
non-primitive data types

Data Type Default Value Default size


boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Float 0.0f 4 byte
Double 0.0d 8 byte
Why char uses 2 byte in java and what is \u0000 ?
Because java uses unicode system rather than ASCII code system. \u0000 is the lowest range of unicode system.

105
Operators

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

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

The Arithmetic Operators:

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The
following table lists the arithmetic operators:

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

SR.NO Operator and Example

+ Addition

1 Adds values on either side of the operator

Example: A + B will give 30


2 - Subtraction

Subtracts right hand operand from left hand operand

Example: A - B will give -10


3 * Multiplication

Multiplies values on either side of the operator

Example: A * B will give 200


4 / Division

Divides left hand operand by right hand operand

Example: B / A will give 2


5 % Modulus

Divides left hand operand by right hand operand and returns remainder

Example: B % A will give 0


6 ++ Increment

Increases the value of operand by 1

Example: B++ gives 21

106
7 -- Decrement

Decreases the value of operand by 1

Example: B-- gives 19

The Relational Operators:

There are following relational operators supported by Java language

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

SR.NO Operator and Description

== equalto

1 Checks if the values of two operands are equal or not, if yes then condition becomes true.

Example: A==BA==B is not true.

2 != notequalto

Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.

Example: A!=BA!=B is true.


3 > greaterthan

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes
true.

Example: A>BA>B is not true.

4 < lessthan

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes
true.

Example: A<BA<B is true.

5 >= greaterthanorequalto

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then
condition becomes true.

Example A>=BA>=B is not true.

6 <= lessthanorequalto

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition
becomes true.

exampleA<=BA<=B is true.

107
The Bitwise Operators:

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

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

a = 0011 1100

b = 0000 1101

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

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators:

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

SR.NO Operator and Description

& bitwiseand

1
Binary AND Operator copies a bit to the result if it exists in both operands.

Example: A & B A & B will give 12 which is 0000 1100

2 | bitwiseor

Binary OR Operator copies a bit if it exists in either operand.

Example: A|BA|B will give 61 which is 0011 1101

3 ^ bitwiseXOR

Binary XOR Operator copies the bit if it is set in one operand but not both.

Example: ABAB will give 49 which is 0011 0001

4 ~ bitwisecompliment

Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.

Example: A A will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.

5 << leftshift

108
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the
right operand

Example: A << 2 will give 240 which is 1111 0000

6 >> rightshift

Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by
the right operand.

Example: A >> 2 will give 15 which is 1111

7 >>> zerofillrightshift

Shift right zero fill operator. The left operands value is moved right by the number of bits specified by
the right operand and shifted values are filled up with zeros.

Example: A >>>2 will give 15 which is 0000 1111

The Logical Operators:

The following table lists the logical operators:

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

Operator Description

&& logicaland

1 Called Logical AND operator. If both the operands are non-zero, then the condition becomes
true.

Example A && B A && B is false.

2 || logicalor

Called Logical OR Operator. If any of the two operands are non-zero, then the condition
becomes true.

Example A||BA||B is true.

3 ! logicalnot

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is
true then Logical NOT operator will make false.

Example ! A && B A && B is true.

The Assignment Operators:

There are following assignment operators supported by Java language:


109
SR.NO Operator and Description

1 =

Simple assignment operator, Assigns values from right side operands to left side operand.

Example: C = A + B will assign value of A + B into C

2 +=

Add AND assignment operator, It adds right operand to the left operand and assign the result to left
operand.

Example: C += A is equivalent to C = C + A

3 -=

Subtract AND assignment operator, It subtracts right operand from the left operand and assign the
result to left operand.

Example:C -= A is equivalent to C = C - A

4 *=

Multiply AND assignment operator, It multiplies right operand with the left operand and assign the
result to left operand.

Example: C *= A is equivalent to C = C * A

5 /=

Divide AND assignment operator, It divides left operand with the right operand and assign the result to
left operand

ExampleC /= A is equivalent to C = C / A

6 %=

Modulus AND assignment operator, It takes modulus using two operands and assign the result to left
operand.

Example: C %= A is equivalent to C = C % A

7 <<=

Left shift AND assignment operator.

ExampleC <<= 2 is same as C = C << 2

8 >>=

110
Right shift AND assignment operator

Example C >>= 2 is same as C = C >> 2

9 &=

Bitwise AND assignment operator.

Example: C &= 2 is same as C = C & 2

10 ^=

bitwise exclusive OR and assignment operator.

Example: C ^= 2 is same as C = C ^ 2

11 |=

bitwise inclusive OR and assignment operator.

Example: C |= 2 is same as C = C | 2

Miscellaneous Operators

There are few other operators supported by Java Language.

Conditional Operator ?:?:

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

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

Following is the example:

public class Test {

public static void main(String args[]){


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

111
This would produce the following result

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

Instance of Operator:

This operator is used only for object reference variables. The operator checks whether the object is of a particular
type classtypeorinterfacetypeclasstypeorinterfacetype. instanceof operator is written as:

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

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

public class Test {


public static void main(String args[]){
String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
System.out.println( result );
}
}

This would produce the following result:

true

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

class Vehicle {}
public class Car extends Vehicle {

public static void main(String args[]){

Vehicle a = new Car();


boolean result = a instanceof Car;
System.out.println( result );
}
}

This would produce the following result:

true

Precedence of Java Operators:


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

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

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

Category Operator Associativity

Postfix [] . dotoperator Left toright

Unary ++ - - ! ~ Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift >> >>> << Left to right

Relational > >= < <= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Control Statements In Java


There may be a situation when you need to execute a block of code several number of times. In general,
statements are executed sequentially: The first statement in a function is executed first, followed by the second,
and so on.
Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and following is the
general form of a loop statement in most of the programming languages:

113
Java programming language provides the following types of loop to handle looping requirements.

Loop Type Description

while loop Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.

for loop Execute a sequence of statements multiple times and abbreviates the code
that manages the loop variable.

do...while loop Like a while statement, except that it tests the condition at the end of the
loop body

Loop Control Statements:


Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic
objects that were created in that scope are destroyed.
Java supports the following control statements.

Control Statement Description

break statement Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.

continue statement Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.

Enhanced for loop in Java:

As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including
arrays.

Syntax:

The syntax of enhanced for loop is:

for(declaration : expression)
{
//Statements

114
}

Declaration: The newly declared block variable, which is of a type compatible with the elements of the array
you are accessing. The variable will be available within the for block and its value would be the same as the
current array element.

Expression: This evaluates to the array you need to loop through. The expression can be an array variable or
method call that returns an array.

Example:

public class Test {


public static void main(String args[]){
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}}

This would produce the following result:

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

Decision making structures have one or more conditions to be evaluated or tested by the program, along with a
statement or statements that are to be executed if the condition is determined to be true, and optionally, other
statements to be executed if the condition is determined to be false.

Following is the general form of a typical decision making structure found in most of the programming languages:

115
Java programming language provides following types of decision making statements.

Statement Description

if statement An if statement consists of a boolean expression followed by one or more


statements.

if...else statement An if statement can be followed by an optional else statement, which executes
when the boolean expression is false.

nested if statements You can use one if or else if statement inside another if or else if statement(s).

switch statement A switch statement allows a variable to be tested for equality against a list of
values.

The ? : Operator:

We have covered conditional operator ? : in previous chapter which can be used to replace if...else statements. It
has the following general form:

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

To determine the value of whole expression, initially exp1 is evaluated

If the value of exp1 is true, then the value of Exp2 will be the value of the whole expression.
If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of the entire expression.

BYTECODE

To run a Java program on the Java processor, the souce program (the text file) must be translated into
bytecodes.
A Java bytecode is a machine instruction for a Java processor.
The architecture of this processor has been very carefully described by the designers of Java and is available
to anyone.

116
Here is a picture of the sample Java program Hello.java being translated into bytecodes.
The file of bytecodes (machine language for the Java processor) is calledHello.class.

In this picture, the source program Hello.java is examined by a program called javac running on your
computer.
The javac program is a compiler (a translator) that translates the source program into a bytecode file
called Hello.class.

Important Idea: The bytecode file will contain exactly the same bytecodes no matter what computer system
is used.
The Java compiler on a Macintosh will produce the exact same bytecodes as the Java compiler on an Intel
system.

JAVA VIRTUAL MACHINE:

Java compiler produces an intermediate code known as byte code for a machine that does not exist.
This machine is called the java virtual machine and its exists only inside the computer memory.

117
An implementation of the Java Virtual Machine Specification, interprets compiled Java binary code
(called bytecode) for a computer's processor (or "hardware platform") so that it can perform a Java
program's instructions.

Java was designed to allow application programs to be built that could be run on
any platform without having to be rewritten or recompiled by the programmer for each separate
platform.

A Java virtual machine makes this possible because it is aware of the specific instruction lengths and
other particularities of the platform.

The Java Virtual Machine Specification defines an abstract -- rather than a real -- machine or
processor.

The Specification specifies an instruction set, a set of registers, a stack, a "garbage heap," and
a method area.

Once a Java virtual machine has been implemented for a given platform, any Java program (which,
after compilation, is called bytecode) can run on that platform.

A Java virtual machine can either interpret the bytecode one instruction at a time (mapping it to a
real processor instruction) or the bytecode can be compiled further for the real processor using what
is called a just-in-time compiler.

JAVA PROGRAM STRUCTURE:

A java program may contain many classes of which only one class defines a main method. Classes
contain data members that operate on the data members of the class. Methods may contain data type
declarations and executable statements.

118
1. Documentation section:

The documentation section comprises a set of comments lines giving the name of the program, the
author and other details. Comments must explain why and what of classes and how of algorithms. Java also
uses a third style of comment/*.*/ known as documentation comment.

2. Package Statement:

The first statement allowed in a java is a package statement. This statement declares a package name
and informs the compiler that the classes defined here belong to this package

Example: package student;

The package statement is optional.

3. Import Statement:

The next thing after a package statement may be a number of import statements.This is similar to the
#include statement in c.

Example: import student.test;

This statement instructs the interpreter to load the test class contained in the package student.

4. Interface Statements:

An interface is like a class but includes a group of method declarations. This is also optional section
and is used only when we wish to implement the multiple inheritance feature in the program.

5. Class Definitions.

A java program may contain multiple class definitions. Classes are the primary and essential
elements of a java program. These classes are used to map the objects of real world problems. The number
of classes used depends on the complexity of the problem.

119
6. Main method class:

The main method is the essential part of the java program. The main method creates objects of
various classes and establishes communications between them. On reaching end of main ,the program
terminates and the control passes back to the operating system.

SIMPLE JAVA PROGRAM:

class sample
{
Public static void main(String args[])
{
Sytem.out.println(Java is better than C++);
}
}
OUTPUT:

To Compile the program: javac sample.java

To run the program : java sample

Java is better than C++

EXPALNATION OF THE PROGRAM:

CLASS DECLARATION:

The first line class sample declares a class and everything must be placed inside a class. Class is a
keyword and sample is a java identifier that specifies the name of the class to be defined.

OPENING BRACE:

Every class definition in java begins with an opening brace { and ends with a matching closing
braces}.

THE MAIN LINE:

The third line Public static void main(String args[]) defines a method named main. This is the
starting point for the interpreter to begin the execution of the program. A java application can have any
number of classes but only one of them must include the main method to initiate the execution.

Public: The keyword public is an access specifier that declares the main method as unprotected and
therefore making it accessible to all other classes.

Static: Declares the method as one that belongs to the entire class and not a part of any objects of the
class. The main must always be declared as static since the interpreter uses this method before any
objects are created.

Void: States that the main method does not return any value.

String args[]: declares a parameter named args,which contains an array of objects of the class type
String.

120
OBJECTS

The smallest logical unit of Java is the object

Objects are identified by its unique name.

An object is a instance of a class.

Objects are the basic runtime entities in an object oriented system.

Real-world objects share two characteristics: They all have state and behavior.

Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail).

Software objects also have a state and behaviour.

A software object's state is stored in fields and behaviour is shown via methods.

CREATING OBJECTS:

Creating an object is also referred to as instantiating an object. An object in java is essentially a


block of memory that contains space to store all the instance variables. Objects in java are created using the
new operator. The new operator creates an object of the specified class and return a reference to that object.

(eg)

Rectangle rect; //declaration

Rect=new Rectangle(); //instantiation

(Or )Rectangel rect= new Rectangle()

The first statement declares a variable to hold the object reference and the second one actually
assigns the object reference to the variable.

Bundling code into individual software objects provides a number of benefits


Modularity
Information-hiding
Code re-use
Plug ability and debugging ease

CLASSES

A class is the blueprint from which individual objects are created.

Classes are made up of objects

121
In the real world, you'll often find many individual objects all of the same kind. There may be
thousands of other bicycles in existence, all of the same make and model. Each bicycle was built
from the same set of blueprints and therefore contains the same components. In object-oriented
terms, we say that your bicycle is an instance of the class of objects known as bicycles.

A class must have a valid identifier name; it can begin with an alphabetic character, the underscore,
or the dollar sign.

Syntax for declaring a class:

The class body is declared within curly braces.


class MyClass {
member variables;

member functions () ;

} // end class MyClass
class room class RoomA

{ {

float length,breadth; public static void main(String args[])

void getdata(float a, float b) {

{ float area;

length=a; room x=new room();

breadth=b; x.getdata(14,10);

} area=x.length*x.breadth;

} System.out.println(area= + area);

OUTPUT:

Area= 140

EXAMPLE:2

Class Rect rect r1 = new Rect();

{ Rect r2 = new Rect();

int l,w; r1.l=15;

void getData(int x,int y) r1.w=10;

{ a1=r1.l*r1.w;

l=x; r2.getData(20,12);

w=y; a2=r2.rectArea();

122
} System.out.println(Area1=+a1);

int rectArea() System.out.println(Area2=+a2);

{ }

int area = l*w; }

return(area);

} OUTPUT:

Class RectArea Area1= 150

{ Area2= 240

Public static void main(String args[])

int a1,a2;

ARRAYS

An array is a group of contiguous or related data items that share a common name. An array has a fixed:

Name
Type
Length

Array types

One dimensional array.


Two dimensional array.

One dimensional array(or)single subscripted variable

A list of items can be given one variable name using only one subscript and such a variable is
called a single subscripted variable or a one dimensional array.

Creating an array:

An array is created by allocating memory space to the arrays (i.e. new operator is used).

Creation of arrays involve three steps:

1. Declare the array int num[];


2. Create memory locations num = new int[];
3. Put values into the memory locations num[1] = 35;

Int a[] = {35,56,76,45,34};

123
Declaring an array:

An array variable is declared by specifying the array data type, followed by[] and the array variable
name.

SYNTAX:

Data_type arrayname[]; Or

Data_type[] arrayname;

E.g.:int a[]; int [] a;

Creating of arrays

After declaring , we need to create it in the memory

Array_name=new data_type[size];

a=new int[10];

Array declaration and creation can be combined as one statement as follows:

int a[]=new int[10];

INTIALIZATION:

Final step is to put values into the array created.

Arrayname[subscript]=value

or

Type arrayname[]={list of values};

Accessing the elements of an array:

Each item in an array is called an element.


Each element is accessed by numerical index within[].
All array index starts with zero and ends with (array.lenth-1).
Array_name[<index>]

ARRAY INITIALIZERS:

Array elements are initialized explicitly using loop.


It can also be initialized while array creation.

General form

<data_type> arrayname[]={<values list>}

E.g

int a[]={1,2,3,4,5}

Or
124
for(int i=1;i<=5;i++)

{ a[i]=i;

ARRAY SIZE:

The number of elements in an array can be found using array name.length

(e.g) a.length=4

ONE DIMENSIONAL ARRAY class sample1

class sample {

{ public static void main(String args[])

int num[]; {

sample() sample s=new sample();

{ s.print();

num=new int[10]; }

for(int i=0;i<num.length;i++) }

num[i]=i+1; output:

} 1

void print() 2

{ 3

System.out.println("numbers are"); 4

for(int i=0;i<num.length;i++) 5

System.out.println(num[i]); 7

} 8

} 9

10

ANONYMOUS ARRAYS

Allocates a new array and fills it with values inside the braces.
General form
New <data_type>[]{<list of values>};

125
(E.g ) a=new int[]{1,2,3,4,5};

COPYING ARRAYS:

One array variable can be copied into another variable.

Example program:

Class array1

Public static void main(String args[])

int a[]={1,2,3,4,5};

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

b=a;

for(int i=0;i<b.length;i++)

System.out.println(i+:+b[i]);

OUTPUT:

USING ARRAYCOPY() METHOD:

126
The system class has an arraycopy() method which can be used to copy data's from one array to
another array.

SYNTAX:Arraycopy(object from, int from index, object to, int to index, int count)

EXAMPLE PROGRAM:

import java.util.*;

import java.io.*;

class array1

public static void main(String args[])

int a[]={1,2,3,4,5,6};

int b[]={10,20,30,40,50,60,70,80,90};

System.arraycopy(a,2,b,3,4);

for(int i=0;i<b.length;i++)

System.out.println(""+b[i]);

}}}

SORTING AN ARRAY:

The array class has the sort array method that can be used to sort the array of numbers.
Various methods of java.util.array class
Static void sort(a[])
Static int search(a[],key)
Static boolean equals(int a[],int b[])
Static void fill(a[],val)

127
EXAMPLE PROGRAM:

import java.util.*;

import java.io.*;

class array1

public static void main(String args[])

int a[]={5,6,1,8,2};

System.out.println("The unsorted array");

for(int i=0;i<a.length;i++)

System.out.println(a[i]);

Arrays.sort(a);

System.out.println("The sorted array");

for(int i=0;i<a.length;i++)

System.out.println(a[i]);

MULTIDIMENSIONAL ARRAY:

Is an array which has more than one index to access the elements.
Syntax

Declaration:
128
<data_type> array_name[][][];

E.g: int a[][][];

Creation:

array_name=new <data_type>[size1][size2];

E.g: a=new int[3][3][3];

int a[][][]=new int[3][3][3];

EXAMPLE PROGRAM:

TWO DIMENSIONAL ARRAY void print()

import java.io.*; {

class sample2 System.out.println("numbers are");

{ for(int i=0;i<3;i++)

int num[][]; {

sample2() for(int j=0;j<3;j++)

{ System.out.println(""+num[i][j]+"");

num=new int[3][3]; }}

for(int i=0;i<3;i++) Class array1

{ {

for(int j=0;j<3;j++) public static void main(String args[]) throws IOException

num[i][j]=(i+1)*(j+1); {

} sample2 s=new sample2();

} s.print();

}}

OUTPUT:

123

246

369

RAGGED ARRAYS

129
Ragged arrays have rows of unequal length. Each row has a different number of columns, or entries.
Ragged arrays are allowed in Java

Example: create a 2-D int array named b with 5 elements in the first row, 7 in the second row, and 4 in
the third row:

int[][] b = new int[3][];

b[0] = new int[5];

b[1] = new int[7];

b[2] = new int[4];

EXAMPLE PROGRAM:

import java.util.*; for(int i=0;i<a.length;i++)

import java.io.*; {

class array1 for(int j=0;j<a[i].length;j++)

{ {

public static void main(String a[i][j]=i;


args[])
System.out.print(""+a[i][j]);
{
}
int a[][]=new int[3][5];
System.out.println("");

}}}

OUTPUT:

00000

11111

22222

COMMAND LINE PARAMETERS:

Every java program has a main method with a string args[] parameter.
This parameter indicates that the main method receives an array of strings, namely, the
arguments specified on the command line.
While running the program any things written after the name of the class are the command line
arguments.

EXAMPLE PROGRAM:

130
import java.util.*;

import java.io.*;

class array1

public static void main(String args[])

if(args[0].equals("h"))

System.out.println("hello");

else if(args[0].equals("g"))

System.out.println("hello world");

for(int i=0;i<args.length;i++)

System.out.println(args[i]);

}}

INHERITANCE IN JAVA

The mechanism of deriving a new class from an old class is called inheritance. (i.e)One class can
inherit properties of another class. class that is inherited is called superclass. Hence, subclass is specialized
version of super class. We use the keyword extends for inheriting a class from other in java.

Advantages of inheritance:

Reusability of code.
Effort and time saving.
Increased reliability.

Implementation of inheritance:

1. Inheriting classes (Extending classes).


131
Creates a new class as an extension of another class.
A class cannot be inherited from more than one class.
A derived class can only access the non private members of the base class.

2. Inheriting interfaces(Implementing interface)

The implements keyword is used to inherit an interface in java.


Java allows a class to be inherited from more than one interface.

General form:

Class <class_name> implements <interfce1>,<interfce2>..

Class <class_name>extends old class_name

Types of inheritance

1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

Single inheritance:

The process of creating only one sub class from only one super class is single inheritance

Multiple inheritance:

The process of creating only one sub class from more than one super class is known as
multiple inheritance.
Java does not support multiple inheritance.
This is implemented with the help of interfaces in java.

132
Multilevel inheritance:

The process of creating a new sub class from an already existing sub class is known as
multilevel inheritance.

Hierarchical inheritance:

The process of creating more than one sub class from an super class is known as Hierarchical
inheritance.

133
Hybrid inheritance:

The process of combining more than one inheritance in classes is known as hybrid inheritance.

134
UNIT V
EXCEPTION HANDLING
Packages and Interfaces, Exception handling, Multithreaded programming, Strings, Input/Output

PACKAGES

Package is defined as a way to group a related class and interface into one unit. Packages are essentially a
means of organizing classes together as groups. Packages act as containers for classes.

BENEFITS OF PACKAGES:

1. The classes contained in the packages of other programs can be easily reused.
2. Packages provide a way to hide classes thus preventing other programs or packages from accessing
classes that are meant for internal use only.
3. Packages also provide a way for separating design from coding.

CREATING PACKAGES:

First declare the name of the package using the package keyword followed by a package name.
This must be the first statement in a java source file.

Syntax

package packagename; //package declaration

public class firstclass //class definition

//body of class
}

While creating a package, care should be taken that the statement for creating a package must be written
before any other import statements

LEGAL ILLEGAL

package mypackage ; import java.io;


import java.io; package mypackage ;

Creating our own package involves the following steps:

1. Declare the package at the beginning of a file using: package package name;
2. Define the class then is to be put in the package and declare it public.
3. create a subdirectory under the directory where the main source files are stored.
4. store the file as the class name.java file in the subdirectory created.
5. compile the file. This creates .class file in the subdirectory.

Importing Packages:

Two ways to import a package

1. Importing a specific Package Member

import mypackage.Calculator;
135
2. Importing an Entire Package

import mypackage.*;

SYNTAX:

In Java, the Packages can be imported into a program in the following manner :

import <package_name>.<class_name>;

Suppose we wish to use a class say MyClass whose location is as follows :


import mypackage.mysubpackage.MyClass;

Standard java packages

Java.lang Language support classes include primitive types, strings, math functions threads
and exceptions.
Java.util Language utility classes such as vectors, hash tables random numbers, date etc..
Java.net Classes for networking.
Java.awt classes for implementing GUI.
Java.applet classes for creating and implementing applets.

EXAMPLE PROGRAM 1:

Package package1;

Public class classA

Public void displayA()

System.out.println(classA);

}}

The source file should be named as class A.java and store in the subdirectory package1.

Main program:

Import package1.classA;

Class packageTest1

Public static void main (string args[])


136
{

ClassA objA=new classA();

objA.dispalyA();

Store the file in the bin directory as packageTest1.java and compile it.

OUTPUT:

ClassA

EXAMPLE PROGRAM 2:

package addition; Main program:

public class add import addition.add;

{ import subtraction.sub;

int a=5,b=10,c; class sample

public void print1() {

{ public static void main (String args[])

c=a+b; {

System.out.println("sum="+c); add x=new add();

}} sub y=new sub();

package subtraction; x.print1();

public class sub y.print1();

{ } }

int a=15,b=10,c; Output:

public void print1() C:\Program Files\Java\jdk1.6.0_19\bin>javac


sample.java
{
C:\Program Files\Java\jdk1.6.0_19\bin>java
c=a-b; sample
System.out.println("sub="+c); sum=15

}} sub=5

Advantages of packages:

Classes can be easily reused.


Two classes in different package can have the same name.
137
Packages provide a way to hide classes.

INTERFACES
An interface is basically a kind of class. Like classes interface contain methods (without
implementations) and variables but with a major difference. The difference is that interface defines only
abstract methods and final fields. This means that interfaces do not specify any code to implement these
method and data fields contain only constant values.
A class can implement more than one interface. All methods declared in an interface are automatically
considered as public. Therefore it is the responsibility of the class that implements an interface to define the
code for implementation of these methods.

SYNTAX:

interface interfacename
{
variable declaration;
Methods declaration;
}
Here interface is the keyword and interface name is any valid names.

Variables are declared as follows: All the variables are declared as constants.

Static final type variable name=value;

Method Declaration:

Method declaration will contain only a list of methods without any body statements.

return-type method-name(parameter-list);

EXAMPLE:
interface item
{
static final int code=1000;
static final string name=JAVA
void display()
}

Rules for interface constants.


They must always be
public
static
final

Once the value has been assigned, the value can never be modified. The assignment happens in the interface
itself (where the constant is declared), so the implementing class can access it and use it, but as a read-only
value.

IMPLEMENTING INTERFACE:

Interfaces are used as superclasses whose properties are inherited by classes.


To make a class implement an interface, have to carry out two steps:
138
Declare that your class intends to implement the given interface.
Supply definitions for all methods in the interface.

To declare that a class implements an interface, use the implements keyword:

SYNTAX:

class classname implements interfacename


{
//definitions for all methods in the interface
}

Implementation classes must adhere to the same rules for method implementation as a class extending an
abstract class.
In order to be a legal implementation class, a nonabstract implementation class must do the following:
When you implement an interface method, method must be declared as public. (The access level can be
more accessible than that of the overridden method.)
Type signature of the implementing method must match exactly the type signature specified in the interface
definition. (The argument list and return type must exactly match that of the overridden method.)
A class can implement one or more interfaces.
Partial Implementations: If a class includes an interface but does not fully implement the methods defined
by that interface, then that class must be declared as abstract.

Properties of interface:
Interfaces are not classes (i.e.)one cannot instantiate an interface.
Interface variables can be declared.
o E.g.: <interface name><variable name>;
An interface variable can refer to an object of a class which implements the interface.
Fields in interface are public static final.
Classes can implement multiple interfaces.
Static methods cannot be placed in interfaces.
One interface can extend the other interface.

E.g.: interface <interface2> extends <interface1>

139
Example:2
import java .io.*; class InterfaceTest

interface Area {

{ public static void main(String args[])

final static float pi=3.14F; {

float compute(float x,float y); Rectangle rect=new Rectangle();

} Circle cir=new Circle();

class Rectangle implements Area Area ar;

{ ar=rect;

public float compute(float x,float y) System.out.println("Area of


Rectangle="+ar.compute(10,20));
{
ar=cir;
return(x*y);
System.out.println("Area of
} } Circle="+ar.compute(10,0));
class Circle implements Area } }
{

public float compute(float x, float y) OUTPUT:


{ COMPILATION AND EXECUTION:
return(pi*x*x); C:\Program Files\Java\jdk1.6.0_19\bin> javac
} InterfaceTest.java

} C:\Program Files\Java\jdk1.6.0_19\bin> java


InterfaceTest

OUTPUT:

Area of Rectangle=200.0

Area of Circle=314.0

EXCEPTIONS
Exception is a condition that is caused by a run time error in the program. Exceptions may occur in
any programming language. When the Java interpreter encounters an error such as dividing an integer by
zero, it creates an exception object and throws it(inform us that an error has occurred).
If the exception object is not caught and handled properly, the interpreter will display an error
message and will terminate the program. If we want to continue with the execution of the remaining code,

140
then we should try to catch the exception object thrown by the error condition and then display an
appropriate message for taking corrective actions. This task is known as exception handling.

The purpose of exception handling mechanism is to provide a means to detect and report an perform
the following task.

1. Find the problem(Hit the exception)


2. Inform that an error has occurred(Throw the exception)
3. Receive the error information(catch the exception)
4. Take corrective action(Handle the exception)

COMMON JAVA EXCEPTION :


No Exception type cause of Exception
1 ArithmeticException Caused by math errors such as division by zero
2 ArrayIndexOutOfBoundsException Caused by bad array indexes
3 ArrayStoreException Caused when a program tries to store the wrong type of data in
an array
4 FileNotFoundException Caused by an attempt to access a non existent files
5 IOException Caused by general I/O failures such as inability to read from a
file.
6 OutOfMemoryException Caused when theres not enough memory to allocate a new
object.
7 StackOverflowException Caused when the system runs out of stack space.

Java Exception handling is managed by the following five keywords:


1. Try
2. Throw: to throw an exception explicitly using he throw statement.
3. Catch
4. Throws:- A throws clause lists the type of exceptions that a method might throw.
5. Finally

SYNTAX OF EXCEPTION HANDLING CODE:

The basic concepts of exception handling are throwing an exception and catching it. This is shown in
fig.

141
Java uses a keyword try to preface a block code that is likely to cause an error condition and throw an
exception. A catch block defined by the keyword catch catches the exception thrown by the try block
and handles it appropriately. The catch block is added immediately after the try block. The following
example shows the use of simple try and catch statements:

.
.
try
{
// block of code to monitor for errors
}
Catch(ExceptionType obj)
{
//statement //processes the exception
}

Example Program:

class error3
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println(Division by zero);
}
y=a/(b+c);
System.out.println(y=+y);
}
}

OUTPUT:
Division by zero
y=1

CATCHING INVALID COMMAND LINE ARGUMENTS:

class clineinput
{
public static void main (String args[])
{
int invalid=0;
int number,count=0;
for(int i=0;i<args.length;i++)
{
try
{
number=Integer.parseInt(args[i]);

142
}
catch(NumberFormatException e)
{
invalid=invalid+1; //caught an invalid number
System.out.println("invalid number:"+args[i]);
continue; //skip the remaining part of the loop
}
count=count+1;
}

System.out.println("valid numbers="+count);
System.out.println("Invalid numbers="+invalid);
}
}
OUTPUT:

C:\Program Files\Java\jdk1.6.0_19\bin>java clineinput 56 java 100 10.6 program


invalid number:java
invalid number:10.6
invalid number:program
valid numbers=2
Invalid numbers=3

MULTIPLE CATCH STATEMENTS:

It is possible to have more than one catch statement in the catch block.

Syntax:

try
{
Statement
}

Catch(Exception-type1 e)
{
Statement
}

Catch(Exception-type2 e)
{
Statement
}
Catch(Exception-type3 e)
{
Statement
}
.
.

When an exception in a try block is generated, the java treats the multiple catch statements like cases
in a switch statement. The first statement whose parameter matches with the exception object will be
executed and the remaining statements will skipped.

EXAMPLE PROGRAM:
143
class error
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index error");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}
int y=a[1]/a[0];
System.out.println("y="+y);
}
}

OUTPUT:
Array index error
y=2

Explanation:

Since the array element a[2] does not exist because array a is defined to have only two elements a[0] and
a1]. Therefore the index 2 is outside the array boundary thus causing the block

Catch(ArrayIndexOutOfException e)

To catch and handle the error. Remaining catch blocks are skipped.

USING FINALLY STATEMENT:


Java supports another statement known as finally statement that can be used to handle an exception
that is not caught by any of the previous catch statements. "finally block can be used to handle any
exception generated within a try block. finally creates a block of code that will be executed after try/catch
block has completed and before the code following the try/catch block.finally clause will execute whether or
not an exception is thrown.

SYNTAX:

try
{
..
}

144
finally
{

EXAMPLE PROGRAM:
class error
{
public static void main(String args[])
{
int a[]={5,10};
int b=5;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index error");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}
finally
{
int y=a[1]/a[0];
System.out.println("y="+y);
}
}
}

OUTPUT:
C:\Program Files\Java\jdk1.6.0_19\bin>javac error.java

C:\Program Files\Java\jdk1.6.0_19\bin>java error


Array index error
y=2

THROWING OUR OWN EXCEPTIONS:

It is possible for your program to throw an exception explicitly.


throw TrrowableInstance
Here, TrrowableInstance must be an object of type Throwable or a subclass Throwable
There are two ways to obtain a Throwable objects:
Using a parameter into a catch clause
Creating one with the new operator

We can throw our own exceptions by using the keyword throw as follows:

145
throw new Throwable_subclass;

EXAMPLE PROGRAM:

class ThrowDemo
{
static void demo()
{
try
{
throw new NullPointerException("Demo");
}
catch(NullPointerException e)
{
System.out.println("caught inside demo");
throw e; //re-throw the exception
}
}

public static void main(String args[])


{
try
{
demo();
}
catch(NullPointerException e)
{
System.out.println("Recaught:"+e);
}
}
}

OUTPUT:
C:\Program Files\Java\jdk1.6.0_19\bin>java ThrowDemo
caught inside demo
Recaught:java.lang.NullPointerException: Demo

THROWS

If a method is capable of causing an exception that it does not handle, it must specify this behavior so
that callers of the method can guard themselves against that exception
type method-name parameter-list) throws exception-list
{
// body of method
}

It is not applicable for Error or RuntimeException, or any of their subclasses

EXAMPLE PROGRAM:

class sample
{
static void throwone()throws IllegalAccessException
{

System.out.println(" inside throwone");

146
throw new IllegalAccessException("demo");
}

public static void main(String args[])


{
try
{
throwone();
}
catch(IllegalAccessException e)
{
System.out.println("caught:"+e);
}
}
}

OUTPUT:

C:\Program Files\Java\jdk1.6.0_19\bin>java sample


inside throwone
caught:java.lang.IllegalAccessException: demo

THREADS
What are Threads?
A piece of code that run in concurrent with other threads.
Each thread is a statically ordered sequence of instructions.
Threads are being extensively used express concurrency on both single and multiprocessors
machines.
Programming a task having multiple threads of control Multithreading or Multithreaded
Programming.

MULTI-THREADED PROGRAMMING:

Multithreading is a conceptual programming paradigm where a program (process) is divided


into two or more subprograms which can be implemented at the same time in parallel.
A thread is similar to a program that has a single flow of control. It has a beginning , a body,
and an end ,and executes commands sequentially.
A unique property of java is ,its supports multithreading. Java enables us to use multiple
flows of control in developing programs.
Each flow of control may be thought as a tiny program known as thread that runs in parallel
to others.
A program that contains multiple flows of control is known as multithreaded program.

147
The main thread is actually the main method module, which is designed to create and start the other
three threads namely A,B,C.
A,B, C run concurrently and share the resources jointly.
The ability of a language to support multithreads is referred to as concurrency.

LIGHTWEIGHT THREADS:

The threads in java are subprograms of a main application program and share the same memory
space . hence it is known an light weight threads or light weight process.

LIFE CYCLE OF A THREAD: THREAD STATES


Threads can be in one of the six states: A thread is always in one of these five states.
Newborn state
Runnable state
Running state
Blocked state
Dead state

1. NewBorn state:
148
A new thread begins its life cycle in the new state.
When we create a thread object the thread is born and is said to be in newborn state.
At this state it can perform 1) Schedule it for running using start method. 2) kill it using
stop method.
If scheculed , it moves to the runnable state.If we attempt to use any other method at this stage ,
an exception will be thrown.

2. Runnable:
The thread is ready for execution and is waiting for the availability of the processor. (i.e) the
thread has joined the queue of threads that are waiting for execution. If all the threads have equal
priority then they are given time slots for execution in round-robin fashion(first come first serve
method). The process of assigning time to threads is known as time slicicng.
If we want a thread to relinquish control to another thread of equal priority before it turn
comes it can do so by using yield() method.

3. Running state:
Running means that the processor has given its time to the thread for its execution.
A running thread may relinquishes its control in one of the following situations as
SUSPEND(), RESUME() , SLEEP(), WAIT(), NOTIFY().
Suspend(): - It has been suspended using this method. A suspended method can be revived
by using the resume() method.
Sleep():- We can put a thread to sleep for a specified time period using the method
sleep(time), where time is in milliseconds. The thread re-enters the runnable state as soon as
this time period is elapsed.
Wait():- It has been told to wait until some event occurs. This is done using the wait()
method. The thread can be scheduled to run again using the notify() method.

4. Blocked state:
A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state.
A block thread is considered not runnable but not dead na therefore fully qualified to run
again.
5. DeadState:
Every thread has a life cycle. A running thread ends its life when it has completed executing
its run() method. It is a natural death.

STOPPING AND BLOCKING A THREAD

Stopping a thread:- to stop a thread it call stop() method.


(ie) athread.stop();
Stop statement causes the thread to move to the dead state.
Blocking a thread: -A thread can also be temporarily suspended or blocked from entering into the
runnable and subsequently running state by using the following methods:
Sleep() //blocked for a specified time.
Suspend() // blocked until further orders.
Wait() // blocked until certain condition occurs.

Creating Thread:
Threads are implemented in the form of objects that contain a method called run() which is the heart
and soul of any thread.
It makes up the entire body of a thread and is the only method in which the threads behavior can be
implemented.
run() would appear as follows:
public void run ()
{
---
149
---stm for implementing thread
}

The run() method should be invoked by an object of the concerned thread. This can be achieved by
creating the thread and initiating it with the help of another thread method called start().
A new thread can be created in two ways:
1. By creating a thread class:
2. By converting a class to a thread:

1st method: Extending Thread class

Create a class by extending Thread class and override run() method:


class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
Create a thread:
MyThread thr1 = new MyThread();
Start Execution of threads:

thr1.start();

ANOTHER METHOD: Create and Execute:

new MyThread().start();

Example:1

class MyThread extends Thread


{
public void run()
{
System.out.println(" This thread is running ... ");
}}
class ThreadEx1
{
public static void main(String [] args )
{
MyThread t = new MyThread();
t.start();
}
}

OUTPUT:

This thread is running

EXAMPLE:2

class A extends Thread


{ OUTPUT:
public void run()
{ C:\Program Files\Java\jdk1.6.0_19\bin>java
150
for(int i=1;i<=10;i++) ThreadTest
{ From ThreadA: i= 1
System.out.println("\t From ThreadA: i= From ThreadA: i= 2
"+i); From ThreadA: i= 3
} From ThreadA: i= 4
System.out.println("Exit from A"); From ThreadA: i= 5
} } From ThreadA: i= 6
class B extends Thread From ThreadA: i= 7
{ From ThreadA: i= 8
public void run() From ThreadB: j= 1
{ From ThreadB: j= 2
for(int j=1;j<=10;j++) From ThreadB: j= 3
{ From ThreadB: j= 4
System.out.println("\t From ThreadB: j= From ThreadB: j= 5
"+j); From ThreadB: j= 6
} From ThreadB: j= 7
System.out.println("Exit from B"); From ThreadB: j= 8
} } From ThreadC: k= 1
From ThreadA: i= 9
class C extends Thread From ThreadA: i= 10
{ Exit from A
public void run() From ThreadC: k= 2
{ From ThreadC: k= 3
for(int k=1;k<=10;k++) From ThreadC: k= 4
{ From ThreadC: k= 5
System.out.println("\t From ThreadC: k= From ThreadC: k= 6
"+k); From ThreadC: k= 7
} From ThreadC: k= 8
System.out.println("Exit from C"); From ThreadC: k= 9
} From ThreadC: k= 10
} Exit from C
class ThreadTest From ThreadB: j= 9
{ From ThreadB: j= 10
public static void main(String args[]) Exit from B
{
new A().start();
new B().start();
new C().start();
} }

EXAMPLE :3

//Program using yield function: public class addsub


{
class add extends Thread public static void main(String args[])throws
{ Exception
public void run() {
{ add s;
int a=5,b=10,c; sub c;
c=a+b; s = new add();
yield(); c = new sub();
System.out.println("\nadd="+c); s.sleep(1000);
}} s.start();
class sub extends Thread c.start();
{ }
151
public void run() }
{ OUTPUT:
int a=15,b=10,c; Sub=5
c=a-b; Add= 15
System.out.println("\nsub="+c);
}}

2nd method: Threads by implementing Runnable interface


Create a class that implements the interface Runnable and override run() method:
class MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
Creating Object:

MyThread myObject = new MyThread();

Creating Thread Object:

Thread thr1 = new Thread( myObject );

Start Execution:

thr1.start();

EXAMPLE PROGRAM:1

class MyThread implements Runnable


{
public void run()
{
System.out.println(" this thread is running ... ");
}
}
class ThreadEx2
{
public static void main(String [] args )
{
MyThread thr=new MyThread() ;
Thread t = new Thread(thr);
t.start();
}
}

OUTPUT:

C:\Program Files\Java\jdk1.6.0_19\bin>java ThreadEx2


this thread is running ...

152
EXAMPLE :2
class add implements Runnable public class addsub
{ {
public void run() public static void main(String args[])throws
{ Exception
int a=5,b=10,c; {
c=a+b;
add s = new add();
System.out.println("\nadd="+c); sub c = new sub();
}} Thread obj1=new Thread(s);
Thread obj2=new Thread(c);
class sub implements Runnable
{ obj1.start();
public void run() obj2.start();
{ }
int a=15,b=10,c; }
c=a-b;
System.out.println("\nsub="+c); OUTPUT:
C:\Program Files\Java\jdk1.6.0_19\bin>java addsub
} add=15
} sub=5

THREAD PRIORITY

In java each thread is assigned a priority which affects the order in which it is scheduled for running.
The threads so far had same default priority (NORM_PRIORITY) and they are served using FCFS
policy.
Java permits us to set the priority of a thread using setpriority() method as follows.

Threadname.setpriority(int number);

The intNumber is an integer value to which the Threads Priority is set. The Thread class defines several
Priotiy constants:

MIN_PRIORITY=1
NORM_PRIORITY=5
MAX_PRIORITY=10

Most user level processes should use NORM_PRIORITY,plus or minus one.

The thread class defines several priority constants


MIN_ PRIORITY=1
NORM_PRIORITY=5
MAX_PRIORITY=10

EXAMPLE PROGRAM:

class add extends Thread public class addsub


{ {
public void run() public static void main(String args[])throws
{ Exception
int a=5,b=10,c; {
153
c=a+b;
add s = new add();
System.out.println("\nadd="+c); sub c = new sub();
}} c.setPriority(Thread.MAX_PRIORITY); //(or)
c.setPriority(5);
class sub extends Thread s.setPriority(Thread.MIN_PRIORITY);
{ //(or) c.setPriority(1);
public void run()
{ s.start();
int a=15,b=10,c; c.start();
c=a-b; }
System.out.println("\nsub="+c); }

} OUTPUT:
}
C:\Program Files\Java\jdk1.6.0_19\bin>java addsub

sub=5

add=15

STREAMS AND I/O


Java uses the concept of streams to represent the ordered sequence of data. Stream presents a
uniform, easy-to-use, object-oriented interface between the program and the input/output devices. It is a path
along which data flows. It has a source and a destination.
Java streams are classified into two basic types, namely, input stream and output stream.
Input stream extracts data from the source and sends it to the program
Output stream takes data from the program and sends it to the destination.

Stream classes

A stream is an abstraction that either produces or consumes information. The java.io package
contains a large number of stream classes that provides capabilities for processing all types of data. These
classes may be categories into two groups based on the data type on which they operate.
Byte Stream Class that provide support for handling I/O operations on bytes.
Input Stream Classes
Output Stream Classes
Character Stream Class can be used to read and write 16-bit Unicode characters.
Reader Stream Classes
Writer Stream Classes

154
Byte Streams:

It provides a convenient means for handling input and output of bytes. Byte streams are used
for reading and writing binary data. Byte stream are defined by two class hierarchies:

1. Input stream classes


2. Output stream classes

INPUT STREAM CLASSES:

Input Stream classes that are used to read 8-bit bytes include a super class known as InputStream and
a number of subclasses for supporting various input related functions .

These classes has several subclasses that handles the differences between various devices such as file ,
network connections and even memory buffers.

The byte stream classes are as follows:

These streams are typically used to read and write binary data such as images and sounds. Two
of the byte stream classes, ObjectInputStream and ObjectOutputStream, are used for object
serialization. These classes are covered in Object Serialization.
As with Reader and Writer, subclasses of InputStream and OutputStream provide specialized
I/O that falls into two categories, as shown in the following class hierarchy figure: data sink
streams (shaded) and processing streams (unshaded).

155
The super class Input stream is an abstract class and therefore we cannot create instances of this class.
We must use the subclasses that inherit from this class. The input stream class defines methods for
performing input functions such as

Reading bytes

Closing streams

Marking position in streams

Skipping ahead in a stream

Finding the number of bytes in a stream.

OUTPUT STREAM CLASSES:

Like Input stream , the Output stream is an abstract class and therefore we cannot instantiate it. The
several subclasses of the Output stream can be used for performing the output operations.

156
The output stream includes methods that are designed to perform the following task.
Writing bytes
Closing streams
Flushing streams.

CHARACTER STREAMS CLASSES:

It provides a convenient means for handling input and output of characters, used to read and write
16 bit Unicode characters. There are two kinds of character stream classes namely

Reader stream classes


Writer stream classes

READER STREAM CLASSES:

Reader stream classes are designed to read character from the files. Reader class is the base class for
all other classes in this group. The Reader class contains methods that are identical to those available in the
Input stream class, except Reader is designed to handle characters.

WRITER STREAM CLASSES

The writer stream classes are designed to perform all output operations on files. Only difference is
that while output stream classes are designed to write bytes, the writer stream classes are designed to write
characters.

Subclasses of Reader and Writer implement specialized streams and are divided into two
categories: those that read from or write to data sinks (shown in gray in the following figures) and
those that perform some sort of processing (shown in white). The following figure shows the class
hierarchies for the Reader and Writer classes.

157
CharArrayReader:
CharArrayReader is an implementation that uses a character array as the source. This class has two
constructors. CharArrayReader(char array[])
ChararrayReader(char array[], int start, int numclass)
Buffered Reader:
Buffered Reader improves performance by buffereing input. It hac two constructors.
BufferedReder(reader inputstream)
BufferedReader(Reader inputstream, int bufSize)
BufferedWriter
A bufferedWriter is a writer that adds a fluch() method that can be used to ensure that data buffers
are physically written to the actual output stream.
PushbaskReader:
This class allows one or more characters to be returned to the input stream.
PrintWriter: It provides the formatted output methods print() and println().

STRINGS

Strings represent a sequence of characters. The easiest way to represent a sequence of characters in
java is by using a character array. Java doesnt support the string data type.The java library provides the
String class to create and manipulate strings.

Char chararrayy[] = new char[4];

In java strings are class objects and implemented using twoclasses namely string and string buffer.A
java string is an instantiated object of the string class.Strings may be declared and created as follows:

String stringname;

Stringname= new string(string);

VARIOUS CONSTRUCTOR SUPPORTED BY STRING CLASS:

String S=new String();


String S=new String(hello);
String S=new String(char a[]); {char a[]={h,i}}
String S=new String(char a[],1,1); {char a[]={h,i}}

STRING METHODS:

The string class defines a number of methods that allow us to accomplish a variety of string manipulation
tasks.

VARIOUS METHODS SUPPORTED BY STRING CLASS:

158
1. S1.charAt(int index)- Gives nth character of S1.
2. S2=S1.toLowercase()- converts the string S1 to all lowercase.
3. S2=S1.toUppercase() - converts the string S1 to all uppercase.
4. S1.length() Gives the length of S1.
5. S2=S1.trim() Remove white space s at the beginning and end of the string S1.
6. S1.substring(n) - Gives substring starting from nth character.
7. S1.substring(n,m) - Gives substring starting from nth character upto mth(not
imcluding mth).
8. S1.concat(S2) concatenates S1 and S2.
9. S2=S1.replace(char oldchar,char newchar)- Replace all appearance of old with new.
10. S1.equals(S2) Returns true if S1 is equal to S2.
11. S1.equalsIgnoreCase(S2) Returns true if S1=S2 .ignoring the case of characters.

EXAMPLE PROGRAM 1:

import java.io.*;

public class string1

public static void main(String args[])

char a[]={'b','i','r','t','h','d','a','y'};

String s=new String("hello");

String s1=new String();

String s2=new String(s);

String s3=new String(a);

String s4=new String(a,5,3);

System.out.printf("s1=%s\ns2=%s\ns3=%s\ns4=%s",s1,s2,s3,s4);

OUTPUT:

S1=

S2=hello

S3=birthday

S4=day

E.G :2 PROGRAM FOR VARIOUS STRING OPERATIONS USING EQUALSIGNORECASE:

import java.io.*;
159
class strequals

public static void main(String args[])

String S1="malayalam";

String S2="MALAYALAM";

if (S1.equalsIgnoreCase(S2) )

System.out.println("Both are same");

else

System.out.println("Both are not same");

}}

OUTPUT:

C:\Program Files\Java\jdk1.7.0_25\bin>javac strequals.java

C:\Program Files\Java\jdk1.7.0_25\bin>java strequals

Both are same

EXAMPLE:3

import java.io.*;

public class string1

public static void main(String args[])

String s=" java program ";

String s1="ing";

System.out.println("length="+s.length());

160
System.out.println("without whitespace="+s.trim());

System.out.println("character at="+s.charAt(7));

System.out.println("uppercase string="+s.toUpperCase());

System.out.println("lowercase string="+s.toLowerCase());

System.out.println("concat="+s.concat(s1));

System.out.println("substring from index value 3="+s.substring(3));

System.out.println("substring of 3 to 7="+s.substring(3,7));

System.out.println("String after replacement ==> "+ s.replace('a', 'Y'));

System.out.println("String after replacement ==> "+ s.replace("java", "loan"));

}}

OUTPUT:

C:\Program Files\Java\jdk1.7.0_25\bin>javac string1.java

C:\Program Files\Java\jdk1.7.0_25\bin>java string1

length=17

without whitespace=java program

character at=p

uppercase string= JAVA PROGRAM

lowercase string= java program

concat= java program ing

substring from index value 3=ava program

substring of 3 to 7=ava

String after replacement ==> jYvY progrYm

String after replacement ==> loan program

STRING CONCATENATION:

Means adding two or more strings.Java uses + symbol.

EXAMPLE PROGRAM::

import java.io.*;

161
public class string1

public static void main(String args[])

String s="java program";

String s1="ing";

String s3=s+s1;

System.out.println("after concatenation="+s3);

}}

OUTPUT:

After concatenation=java programing

EXAMPLE PROGRAM :4 A string can be concatenated with a value also in the similar way.

import java.io.*;

public class string1

public static void main(String args[])

String s="java program";

int s1=1;

String s3=s+s1;

System.out.println("after concatenation="+s3);

}}

OUTPUT:

After concatenation=java program1

UNIVERSITY QUESTIONS:

1. Write a java class called student with name, Marks of 3 subjects and total Marks. Write another class
named calculate that gets the Marks of the student and calculates the total Marks and displays the
result(pass or fail)?. (NOV/DEC 2010)
2. Explain the following with examples from Java. (2 8 =16)(NOV/DEC 2010)(NOV/DEC 2012)
(i) Streams and IO
(ii) Java threads.
3. Explain with example program, exception handling in java(APR/MAY2011),2012

162
4. Explain in detail about the inheritance mechanism in Java with example programs.(APR/MAY2011))(NOV/DEC
2011))(NOV/DEC 2011)
5. Describe the structure of a typical java program and give the steps to execute it, and explain the
importance of JVM in JRE.(NOV/DEC 2011)
6. Create a complex number class in java. The class should have a constructor and methods to add,
subtract and multiply two complex numbers and to return the real and imaginary parts.(NOV/DEC 2011)
7. What are packages? How we they created and used?
8. What is multithreading? Explain with an example?(NOV/DEC 2012)
9. write a java program to add 2 integers and raise exception when any other character exception when
any except number(0-9) is given as input.(NOV/DEC 2012)

163

Вам также может понравиться