Академический Документы
Профессиональный Документы
Культура Документы
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.
V. It should be reusable.
Correctness
Maintainability
Reusability
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.
Features:
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.
I. Monitor
II. Keyboard
III. CPU
2
Features of Object oriented programming:
1. Objects
2. Class
3. Data Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message passing
1. Objects:
3
They may represent a person, a place, a bank account that the program has to handle.
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 data inside the objects are called attributes and related functions are called operations.
Ex: computer
Reusability - New software components can be written or developed from existing ones
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:
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.
class MyClass {
member variables;
member functions () ;
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.
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.
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
8. Message passing:
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.
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.
int test() { }
int test(int a){ }
int test(double a){ }
int test(int a, double b){ }
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.
#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;
}
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;
}
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++
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;
Program elements
1. Comments
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
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.
#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:
5. Constants:
14
Using const keyword.
#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
#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
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;
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.
16
Unary + - ! ~ ++ - - (type)* &sizeof Right to left
Traditional conversions
Int< unsigned < long < unsigned long < float < double < long double
It will be done by the compiler, by following the rule of lower type converted to higher type.
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);
Input Stream
Syntax:
cin >> var1 >> var2 >>;
cin Keyword, it is an object, predefined in C++ to correspond to the standard input stream.
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
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".
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.
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:
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;
return0;
}
When the above code is compiled and executed, it produces the following result:
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;
return0;
}
When the above code is compiled and executed, it produces the following result:
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
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;
}
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:
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;
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 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:
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.
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.
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 :
Syntax:
return-type function_name ( parameter1, parameter2, ...)
Statements
Syntax
-------
Statements
int main ()
return 0;
27
}
The function definition contains the code for the function. The general syntax of a function definition in C++ is shown
below:
Function declaration:
Function definition:
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 r;
r=c+d;
return (r);
int main()
int z;
z = addition (5,3);
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
Function Prototypes:
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);
cin>>x;
cin>>y;
change(x,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:
CALL BY ADDRESS:
#include <iostream.h>
void main()
intx,y,change(int*,int*);
cin>>x;
cin>>y;
cout<<"\nbeforeswapping : "<<x<<"\t"<<y;
change(&x,&y);
getch();
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
CALL BY REFERENCE:
#include <iostream.h>
change(int& x, int& y) ;
void main()
intx,y;
cin>>x;
cin>>y;
cout<<"\nbeforeswapping : "<<x<<"\t"<<y;
change(x,y);
getch();
int change(int&a,int&b)
int c;
c=a;
a=b;
b=c;
OUTPUT:
before swapping :5 6
after swapping: 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.
4. used to eliminate the different function names with the same operation(ie)reusability of the code.
Function components:
Function call
Function definition
SYNTAX:
----
Void func (int a,int b)--------------------function definition &a,b are formal parameters
---
void main()
---
32
---
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;
return(s+s);
return(r+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>
void main()
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:
Jumps to function
Saving in registers
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.
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).
Syntax:
Function body
Example:
#include<iostream.h>
#include<conio.h>
return(a*a*a);
int main()
int a;
clrscr();
cin>>a;
cout<<cube is:<<cube(a);
getch();
return 0;
OUTPUT:
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 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.
// Function declaration
voidfunc(void);
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:
The extern modifier is most commonly used when there are two or more files sharing the same global variables or
functions as explained below.
#include<iostream>
int count ;
externvoidwrite_extern();
main()
{
count=5;
write_extern();
}
#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>
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>
namespace first
int x = 5;
int y = 10;
39
}
namespace second
double x = 3.1416;
double y = 2.7183;
int main ()
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.
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:
This is done by placing the index of the element within square brackets after the name of the array. For example:
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
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 */
};
int a[3][4]={0,1,2,3,4,5,6,7,8,9,10,11};
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;
return0;
}
When the above code is compiled and executed, it produces the following result:
doublegetAverage(intarr[],int size)
{
int i, sum =0;
doubleavg;
avg=double(sum)/ size;
returnavg;
}
#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;
return0;
}
Result:
POINTER:
Syntax:
type *var-name;
(c) finally access the value at the address available in the pointer variable.
#include <iostream>
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable
45
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
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>
int main ()
{
int var[MAX] = {10, 100, 200};
int *ptr;
Result:
46
Address of var[2] = 0xbfa088b8
Value of var[2] = 200
#include <iostream>
#include <ctime>
int main ()
{
unsigned long sec;
getSeconds( &sec );
return 0;
}
When the above code is compiled and executed, it produces the following result:
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;
47
return 0;
}
return avg;
}
When the above code is compiled together and executed, it produces the following result:
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:
We can free up the memory that it occupies in the free store with the delete operator as follows:
48
Program:
#include <iostream>
using namespace std;
int main ()
{
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
return 0;
}
Result:
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.
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:
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;
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;
return 0;
}
When the above code is compiled and executed, it produces the following result:
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 );
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:
Pointers to Structures:
We can define pointers to structures in very similar way as you define pointer to any other variable as follows:
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>
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;
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:
Complex numbers:
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;
1 mytypes.c
2 mytypes.i
3 mytypes.f
Example:
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:
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
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:
Both of the objects Box1 and Box2 will have their own copy of 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:
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();
}
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();
}
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:
protected:
private:
};
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);
};
voidLine::setLength(doublelen)
{
length=len;
}
59
// Main function for the program
int main()
{
Lineline;
When the above code is compiled and executed, it produces the following result:
Length of line : 6
Length of line : 10
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;
};
voidBox::setWidth(doublewid)
{
width=wid;
}
return0;
}
Result:
Length of box : 10
Width of box : 10
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;
};
voidSmallBox::setSmallWidth(doublewid)
{
width=wid;
}
return0;
}
Result:
Width of box : 5
Class Scope:
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.
Outside the class we have to give the definition for static data members
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
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
64
t1.setcode();
test::showcount();
t2.setcode();
test::showcount();
t2.showcode();
return 0;
}
OUTPUT:
count:2
count:3
count:4
object number:4
#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
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.
They do not have return value specification, not even void is allowed.
Types of constructors
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;
};
voidLine::setLength(doublelen)
{
length=len;
}
doubleLine::getLength(void)
{
return length;
}
// Main function for the program
int main()
{
Lineline;
return0;
}
When the above code is compiled and executed, it produces the following result:
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;
};
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);
return0;
}
When the above code is compiled and executed, it produces the following result:
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:
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.
~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:
};
The destructor name is same as the class name but prefixed by a tilde(~).
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;
};
voidLine::setLength(doublelen)
{
length=len;
}
71
doubleLine::getLength(void)
{
return length;
}
// Main function for the program
int main()
{
Lineline;
return0;
}
When the above code is compiled and executed, it produces the following result:
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.
Syntax:
#include<iostream>
usingnamespacestd;
classBox
{
double width;
public:
friendvoidprintWidth(Boxbox);
voidsetWidth(doublewid);
};
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:
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:
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 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
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.
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:
Components of STL
Containers
Algorithms
Iterators
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.
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.
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.
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:
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.
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*/
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
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*/
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:
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
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
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
};
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
/* 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.
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
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.
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:
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.
It is function declared in a base class that has no definition relative to the base class .
Syntax,
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
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);
catch( int y)
93
EX: 2
#include<iostream.h>
#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:
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.
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()
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
};
int main()
test(-1);
test(0);
test(1);
return 0;
OUTPUT:
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>
{
97
cout<<insidde function \n;
try
if(y==0.0)
else
cout<<Division = <<x/y;
cout<<end of function \n ;
Int main()
cout<<Inside main;
try
divide(10.5,2.0);
divide(20.0,0.0);
catch(double)
OUTPUT:
98
Inside main
Inside function
Division = 5.25
End of function
Inside function
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.
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:
function body
Syntax: throw();
EXAMPLE:
99
#include<iostream.h>
Try
};
void main()
cout<<x==-1 \n;
test(-1);
cout<<x==0 \n;
test(0);
cout<<x==1 \n;
test(1);
Catch(char c)
Catch(int m)
Catch(double d)
100
{
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
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
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:
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.
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++
Variable
Variable is name of reserved area allocated in memory.
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.
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
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The
following table lists the arithmetic operators:
+ Addition
Divides left hand operand by right hand operand and returns remainder
106
7 -- Decrement
== equalto
1 Checks if the values of two operands are equal or not, if yes then condition becomes true.
2 != notequalto
Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes
true.
4 < lessthan
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes
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.
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 = 1100 0011
& bitwiseand
1
Binary AND Operator copies a bit to the result if it exists in both operands.
2 | bitwiseor
3 ^ bitwiseXOR
Binary XOR Operator copies the bit if it is set in one operand but not both.
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
6 >> rightshift
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by
the right operand.
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.
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.
2 || logicalor
Called Logical OR Operator. If any of the two operands are non-zero, then the condition
becomes 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.
1 =
Simple assignment operator, Assigns values from right side operands to left side operand.
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 <<=
8 >>=
110
Right shift AND assignment operator
9 &=
10 ^=
Example: C ^= 2 is same as C = C ^ 2
11 |=
Example: C |= 2 is same as C = C | 2
Miscellaneous Operators
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:
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:
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:
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 {
true
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.
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.
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
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.
As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including
arrays.
Syntax:
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:
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...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:
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
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 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.
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
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.
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.
class sample
{
Public static void main(String args[])
{
Sytem.out.println(Java is better than C++);
}
}
OUTPUT:
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 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
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).
A software object's state is stored in fields and behaviour is shown via methods.
CREATING OBJECTS:
(eg)
The first statement declares a variable to hold the object reference and the second one actually
assigns the object reference to the variable.
CLASSES
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.
{ {
{ float area;
breadth=b; x.getdata(14,10);
} area=x.length*x.breadth;
} System.out.println(area= + area);
OUTPUT:
Area= 140
EXAMPLE:2
{ a1=r1.l*r1.w;
l=x; r2.getData(20,12);
w=y; a2=r2.rectArea();
122
} System.out.println(Area1=+a1);
{ }
return(area);
} OUTPUT:
{ Area2= 240
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
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).
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;
Creating of arrays
Array_name=new data_type[size];
a=new int[10];
INTIALIZATION:
Arrayname[subscript]=value
or
ARRAY INITIALIZERS:
General form
E.g
int a[]={1,2,3,4,5}
Or
124
for(int i=1;i<=5;i++)
{ a[i]=i;
ARRAY SIZE:
(e.g) a.length=4
class sample {
int num[]; {
{ 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:
Example program:
Class array1
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:
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
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
int a[]={5,6,1,8,2};
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
Arrays.sort(a);
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[][][];
Creation:
array_name=new <data_type>[size1][size2];
EXAMPLE PROGRAM:
import java.io.*; {
{ for(int i=0;i<3;i++)
int num[][]; {
{ System.out.println(""+num[i][j]+"");
num=new int[3][3]; }}
{ {
num[i][j]=(i+1)*(j+1); {
} 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:
EXAMPLE PROGRAM:
import java.io.*; {
{ {
}}}
OUTPUT:
00000
11111
22222
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
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:
General form:
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
//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
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:
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>;
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;
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
objA.dispalyA();
Store the file in the bin directory as packageTest1.java and compile it.
OUTPUT:
ClassA
EXAMPLE PROGRAM 2:
{ import subtraction.sub;
c=a+b; {
{ } }
}} sub=5
Advantages of packages:
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.
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()
}
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:
SYNTAX:
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.
139
Example:2
import java .io.*; class InterfaceTest
interface Area {
{ ar=rect;
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.
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
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:
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.
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
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
}
}
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
}
EXAMPLE PROGRAM:
class sample
{
static void throwone()throws IllegalAccessException
{
146
throw new IllegalAccessException("demo");
}
OUTPUT:
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:
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.
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.
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:
thr1.start();
new MyThread().start();
Example:1
OUTPUT:
EXAMPLE:2
EXAMPLE :3
Start Execution:
thr1.start();
EXAMPLE PROGRAM:1
OUTPUT:
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
EXAMPLE PROGRAM:
} OUTPUT:
}
C:\Program Files\Java\jdk1.6.0_19\bin>java addsub
sub=5
add=15
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:
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.
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
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.
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 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.
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.
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;
STRING METHODS:
The string class defines a number of methods that allow us to accomplish a variety of string manipulation
tasks.
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.*;
char a[]={'b','i','r','t','h','d','a','y'};
System.out.printf("s1=%s\ns2=%s\ns3=%s\ns4=%s",s1,s2,s3,s4);
OUTPUT:
S1=
S2=hello
S3=birthday
S4=day
import java.io.*;
159
class strequals
String S1="malayalam";
String S2="MALAYALAM";
if (S1.equalsIgnoreCase(S2) )
else
}}
OUTPUT:
EXAMPLE:3
import java.io.*;
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 of 3 to 7="+s.substring(3,7));
}}
OUTPUT:
length=17
character at=p
substring of 3 to 7=ava
STRING CONCATENATION:
EXAMPLE PROGRAM::
import java.io.*;
161
public class string1
String s1="ing";
String s3=s+s1;
System.out.println("after concatenation="+s3);
}}
OUTPUT:
EXAMPLE PROGRAM :4 A string can be concatenated with a value also in the similar way.
import java.io.*;
int s1=1;
String s3=s+s1;
System.out.println("after concatenation="+s3);
}}
OUTPUT:
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