Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 147

Object oriented Programming

Unit – I

Basic concepts of object oriented programming:

 Objects
 Classes
 Data Abstraction
 Data Encapsulation
 Inheritance
 Polymorphism
 Dynamic binding
 Message Passing

Objects:

 Object is an instance of a class.


 Objects are basic run-time entities in object oriented programming.
 A variable of a class is an object. Using objects we can access the member variable and member
function of a class.
 Object represent a person, place or any item that the program has to handle.
 A single class can have any number of objects.

Class
 It is a collection of objects. Each object has attributes and operations. The entire set of data and
code of an object can be made a user – defined data type with the help of a class.
 Classes are user-defined data types and behave like built-in types of programming language
and they are known as Abstract Data Types (ADT), since it uses the concept of data abstraction.

1
 Class is a user defined data type, which holds its own data members and member functions,
which can be accessed and used by creating instance of that class.
 The variables inside class definition are called as data members and the functions are called
member functions.
 Class name must start with an uppercase letter. If class name is made of more than one word,
then first letter of each word must be in uppercase. Example,
class Study, class StudyTonight etc
 Classes contain, data members and member functions, and the access of these data members
and variable depends on the access specifiers.
 Class's member functions can be defined inside the class definition or outside the class
definition. Class in C++ are similar to structures in C, the only difference being, class defaults to
private access control, where as structure defaults to public.

Data Abstraction
The insulation of data from direct access by the program is called as data hiding or information
binding. The data is not accessible to the outside world and only those functions, which are wrapped in
the class, can access it.

Data Encapsulation
 Encapsulation means binding of data and functions together in a single entity called class.
 Data abstraction and encapsulation provide two important advantages:
o Hiding the data item.
o The data is not accessible to the outside functions and only those functions which are
wrapped in the class can access it.
Data Hiding
 It is the process of hiding the members from outside the class.
 It is implemented by the concept of “private” access specifiers.
 It can be accessed only by the member functions of that class where it is defined. This is also
called as information hiding.

Inheritance
 Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
 It means the new classes can be developed using some of the properties of old classes.

2
 The newly derived class is called as a derived class or sub class or child class. The existing class
is called as a base class or parent class or super class.
 Inheritance supports the concept of hierarchical classification.
 In OOP, the concept of inheritance provides the idea of reusability.

Polymorphism
Polymorphism means the ability to take more than one form. For example, an operation may exhibit
different behavior in different instances. The behavior depends upon the types of data used in the
operation.

Dynamic Binding
 Binding refers to the linking of a procedure call to the code to be executed in response to the
call.
 In Static binding which function is to be called for a particular object is determined at the
compile time.
 Dynamic binding is the runtime determination of which function to call for a particular object of
the class based on the type of argument. In dynamic binding the code associated with a given
procedure call is not known until the time of the call at runtime.
Message Passing

3
 An object - oriented program consists of a set of objects that communicate with each other. The
process of programming in an object – oriented language, therefore, involves the following
basic steps:
 Creating classes that define objects and their behavior
 Creating objects from class definitions.
 Establishing communication among objects.

Inline functions

 C++ inline function is powerful concept that is commonly used with classes. If a function is
inline, the compiler places a copy of the code of that function at each point where the function is
called at compile time.
 To inline a function, place the keyword inline before the function name and define the function
before any calls are made to the function.
 The compiler can ignore the inline qualifier in case defined function is more than a line.
 A function definition in a class definition is an inline function definition, even without the use of
the inline specifier.

Program
#include <iostream.h>
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
int main( )
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}

Output:
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010

Constructors

Constructors
• A constructor is a kind of member function that initializes an instance of its class.
• A constructor has the same name as the class and no return value.
• A constructor can have any number of parameters and a class may have any number of
overloaded constructors.

Example
4
class Line
{
private:
int length;
public:
Line(); // This is the constructor
void input();
void display();
};

Types of Constructor
• Default Constructor
• Parameterized Constructor
• Copy Constructor

(i) Default Constructor


Default constructor is the constructor which doesn't take any argument. It has no parameter.

Syntax :
class_name ()
{
Constructor Definition
}

Program
#include <iostream.h>
class myclass
{
private:
int a,b;
public:
myclass()
{
a = 30;
b = 20;
}
void show()
{
cout << "Sum is " << a+b << endl;
}
};
int main()
{
myclass ob1;
ob1.show();
return 0;
}
Output
5
Sum is 50

(ii) Parameterized Constructor


These are the constructors with parameter. Using this Constructor you can provide different values to
data members of different objects, by passing the appropriate values as argument.

Syntax :
class_name (list of parameter)
{
Constructor Definition
}

Program
#include <iostream.h>
class myclass
{
private:
int a,b;
public:
myclass(int x, int y)
{
a = x;
b = y;
}
void show()
{
cout << "Sum is " << a+b << endl;
}
};
int main()
{
myclass ob1(20,30);
ob1.show();
return 0;
}
Output
Sum is 50
(iii) Copy Constructor
These are special type of Constructors which takes an object as argument, and is used to copy values of
data members of one object into other object.

Syntax
ClassName (const ClassName &old_obj);

Program
include<iostream.h>
class Point
{
6
private:
int x, y;
public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}
Point(const Point &p2) // Copy constructor
{
x = p2.x;
y = p2.y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
Point p1(10, 15);
Point p2 = p1;
cout <<p1.getX() << p1.getY();
cout <<p2.getX() << p2.getY();
return 0;
}
Output:
10 15
10 15

Destructor
Destructor is a special class function which destroys the object as soon as the scope of object ends. The
destructor is called automatically by the compiler when the object goes out of scope. Destructors will
never have any arguments.
Syntax
class A
{
public:
~A();
};

Constructor Overloading

7
 Constructors can also be overloaded since the constructor in a class have the same name as that
of the class their signatures are differentiate as their parameter list. Overloading of constructor
allows appropriate initialization of objects on creation, depending upon the constructors allow
specifying or initializing the data members dynamically.
 Constructors Overloading are used to increase the flexibility of a class by having more number
of constructor for a single class. By have more than one way of initializing objects can be done
using overloading constructors.

Program
#include <iostream.h>
class myclass
{
private:
int a,b;
public:
myclass();
myclass(int,int);
~myclass();
void show();
};
myclass::myclass()
{
a = 30;
b = 20;
}
myclass::myclass(int x,int y)
{
a = x;
b = y;
}
myclass::~myclass()
{
cout << "Destructing...\n";
}
void myclass::show()
{
cout << "Sum is " << a+b << endl;
}
int main()
{
myclass ob1;
ob1.show();
myclass ob2(100,200);
ob2.show();
return 0;
}
Output:
Sum is 50
8
Destructing…
Sum is 300
Destructing…

Static data member and member Function

Static Data Member


• A static member is shared by all objects of the class. All static data is initialized to zero when the
first object is created, if no other initialization is present.
• Example
static int Count;

Static Member Function


• A static member function can only access static data member, other static member functions
and any other functions from outside the class.
• Static member functions have a class scope and they do not have access to the this pointer of
the class.
• Example
static int getCount()
{
return objectCount;
}

Example Program
#include<iostream.h>
#include<conio.h>
class test
{
int code;
static int count;
public :
void setcode()
{
code= ++count;
}
void showcode()
{
cout<<"object number"<<code;
}
static void showcount()
{
cout<<"count"<<count<<endl;
}
};
int test::count;
void main()
{
clrscr();
9
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
getch();
}
Output
Count 2
Count 3
Object number 1
Object number 2
Object number 3

Default arguments

Default arguments assign a default value to the parameter, which does not have matching argument in
the function call. Default values are specified when the function is declared.
Eg : float amount(float principle,int period,float rate=0.15)
Function call is
value=amount(5000,7);
Here it takes principle=5000 & period=7
And default value for rate=0.15
Value=amount(5000,7,0.34)
Passes an explicit value 0f 0.34 to rate
We must add default value from right to left

Program
#include <iostream.h>
#include <conio.h>
void display(char = '*', int = 1);
void main()
{
clrscr();
cout<<"No argument passed:\n";
display();
cout<<"\n\nFirst argument passed:\n";
display('#');
cout<<"\n\nBoth argument passed:\n";
display('$', 5);
}
void display(char c, int n)
{
10
for(int i = 1; i <=n; ++i)
{
cout<<c;
}
}
Output
No argument passed:
*
First argument passed:
#
Both argument passed:
$$$$$

University Questions

Write a C++ program to define overloaded constructor to perform string initialization, string
copy and string destruction.
#include<iostream.h>
#include<string.h>
class String
{
char *name;
int length;
public:
String()
{
length = 0;
name = new char[length + 1];
}
String(char *s)
{
length = strlen(s);
name = new char[length + 1];
strcpy(name,s);
}
String(String &s)
{
length = s.length;
name = new char[length + 1];
strcpy(name,s.name);
}
void display()
{
cout<<”\nName : “ << name;
11
}
void join(String &s1, String &s2)
{
length = s1.length + s2.length;
name = new char[length + 1];
strcpy(name,s1.name);
strcat(name,s2.name);
}
~String()
{
delete name;
}
};
void main()
{
String str1(“Chettinad”);
String str2(str1);
String str3;
str3.join(str1,str2);
str1.display();
str2.display();
str3.display();
}
Output
Name: Chettinad
Name: Chettinad
Name: ChettinadChettinad

Friend Function

 A function that has access to the private member of the class but is not itself a member of the
class is called friend functions. The general form is
friend data_type function_name(classname);
 Friend function is preceded by the keyword “friend‟.

Properties
Friend function is not in the scope of the class to which it has been declared as friend. Hence it
cannot be called using the object of that class.
Usually it has object as arguments.
It can be declared either in the public or private part of a class.
It cannot access member names directly. It has to use an object name and dot membership
operator with each member name. eg: ( A . x )

Program
12
#include <iostream.h>
class Distance
{
int meter;
public:
Distance()
{
meter=0;
}
friend int func(Distance); //friend function
};
int func(Distance d)
{
d.meter=5;
return d.meter;
}
void main()
{
Distance D;
cout<<"Distace: "<<func(D);
}
Output
Distance: 5

Unit – II

Polymorphism

Polymorphism is the ability to take more than one form. An operation may exhibit different behaviors
in different. The behavior depends upon the type of data used. Polymorphism is of two types.

Types of Polymorphism:
C++ provides two different types of polymorphism.
 Run-time polymorphism
 Compile-time Polymorphism

(i) Run-time polymorphism:


The appropriate member function could be selected while the programming is running. This is known
as run-time polymorphism. The run-time polymorphism is implemented with inheritance and virtual
functions.
Example: Virtual functions

Virtual functions
A function qualified by the virtual keyword. When a virtual function is called via a pointer, the class of
the object pointed to determines which function definition will be used. Virtual functions implement
polymorphism, whereby objects belonging to different classes can respond to the same message in
different ways.

13
(ii) Compile-time Polymorphism:
The compiler is able to select the appropriate function for a particular call at compile-time itself. This
is known as compile-time polymorphism. The compile-time polymorphism is implemented with
templates. They are:
Ø Function overloading
Ø Operator overloading

Function overloading

Function overloading is a feature of C++ that allows us to create multiple functions with the same
name, so long as they have different parameters. Function overloading is usually used to enhance the
readability of the program. If you have to perform one single operation but with different number or
types of arguments, then you can simply overload the function.

Ways to overload a function


1. By changing number of Arguments.
2. By having different types of argument.

Program to find the maximum of 2 numbers using Function Overloading


#include<iostream.h>
#include<conio.h>
class Maximum
{
public:
int max(int a, int b)
{
If( a > b)
return a;
else
return b;
}
float max(float a, float b)
{
If( a > b)
return a;
else
return b;
}
};
void main()
{
int n1,n2;
float x,y,z;
Maximum obj;

14
clrscr();
cout<<“\nEnter two integer number: “;
cin>>n1>>n2;
int t=obj.max(n1,n2);
cout<<“Maximum number is: “<<t;
cout<<“\nEnter two float number: “;
cin>>x>>y;
float temp=obj.max(x,y);
cout<<“Maximum number is: “<<temp;
getch();
}

Operator Overloading

C++ has the ability to provide the operators with a special meaning for a data type. This mechanism of
giving such special meanings to an operator is known as Operator overloading. It provides a flexible
option for the creation of new definitions for C++ operators.
Syntax
Returntype classname:: operator operatorsymbol(argument list)
{
\\Function body
}

Operators that cannot be overloaded.


In C++, following operators cannot be overloaded:
 . (Member Access or Dot operator)
 ?: (Ternary or Conditional Operator )
 :: (Scope Resolution Operator)
 .* (Pointer-to-member Operator )
 sizeof (Object size Operator)
Rules to overload an operator
1. Only the existing operators can be overloaded.
2. The overload operator must have at least one operand that is of user defined data type.
3. We cannot change the basic meaning of an operator. That is to say, we cannot redefine the plus
(+) operator to subtract one value from the other.
4. Overloaded operators must follow the syntax rules of the original operators.
5. Some of the operators cannot be simply overloaded.
6. We cannot use friend function to overload certain operators. However, member functions can
be used to overload them.
7. Unary operators, overloaded by means of a member function, take no explicit arguments and
return no explicit values, but, those overloaded by means of a friend function, take one
reference argument.
8. Binary operators overloaded through a member function take one explicit argument and those
which are overloaded through a friend function take two explicit arguments.
9. When using binary operators overloaded through a member function, the left hand operand
must be an object of the relevant class.

15
10. Binary arithmetic operators such as +, -, * and / must explicitly return a value. They must not
attempt to change their own arguments.

Implementing Operator Overloading


Operator overloading can be done by implementing a function which can be :
– Member Function
– Friend Function

(i) Unary Operator Overloading


The unary operators operate on a single operand and following are the examples of Unary operators:
 The increment (++) and decrement (--) operators.
 The unary minus (-) operator.
 The logical not (!) operator.

Whenever an unary operator is used, it works with one operand, therefore with the user defined data
types, the operand becomes the caller and hence no arguments are required.

//Program for Unary Operator Overloading using member Function


#inlcude<iostream.h>
class space
{
int x, y, z;
public:
void getdata(int ,int,int);
void display();
void operator-();
};
void space :: getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void space :: display()
{
cout<<x<<" \t"<<y<<"\t"<<z<<"\n";
}
void space::operator-()
{
x=-x;
y=-y;
z=-z;
}
int main()
{
space s;
s.getdata(10,-20,30);
cout<<"S : ";
16
s.display();
-s;
cout<<"S :";
s.display();
return 0;
}
Output
S : 10 -20 30
S :-10 20 -30

//Program for Unary Operator Overloading using Friend Function


#inlcude<iostream.h>
class space
{
int x;
int y;
int z;
public:
void getdata(int a,int b.int c);
void display();
friend void operator-(space &s);
};
void space :: getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void space :: display()
{
cout<<x<<" \t"<<y<<"\t"<<z<<"\n";
}
void operator-( space &s)
{
s.x=-s.x;
s.y=-s.y;
s.z=-s.z;
}
int main()
{
space s;
s.getdata(10,-20,30);
cout<<"S : ";
s.display();
-s;
cout<<"S :";
s.display();

17
return 0;
}
Output
S : 10 -20 30
S :-10 20 -30

(ii) Binary Operator Overloading


The binary operators take two arguments and following are the examples of Binary operators.
 addition (+) operator,
 subtraction (-) operator
 multiplication (*) operator and
 division (/) operator.

//Program for Binary Operator Overloading using Member Function


#include <iostream.h>
class Complex
{
private:
float real;
float imag;
public:
void input();
Complex operator+(Complex);
void output();
};
void Complex::input()
{
cin>>real>>imag;
}
Complex Complex:: operator + (Complex c2) /* Operator Function */
{
Complex temp;
temp.real=real+c2.real;
temp.imag=imag+c2.imag;
return temp;
}
void Complex::output()
{
cout<<"Result is : "<<real<<"+"<<imag<<"i";
}
int main()
{
Complex c1, c2, result;
cout<<"Enter first complex number:\n";
c1.input();
cout<<"Enter second complex number:\n";
c2.input();
18
result=c1+c2;
result.output();
return 0;
}

Output
Enter first complex number:
4
5
Enter second complex number:
9
1
Result is : 13 + 6 i

//Program for Binary Operator Overloading using Friend Function


#include <iostream.h>
class Complex
{
private:
float real;
float imag;
public:
void input();
friend Complex operator+(Complex,Complex);
void output();
};
void Complex::input()
{
cin>>real>>imag;
}
Complex operator + (Complex c1,Complex c2) /* Operator Function */
{
Complex temp;
temp.real=c1.real+c2.real;
temp.imag=c1.imag+c2.imag;
return temp;
}
void Complex::output()
{
cout<<"Result is : "<<real<<"+"<<imag<<"i";
}
int main()
{
Complex c1, c2, result;
cout<<"Enter first complex number:\n";
c1.input();
cout<<"Enter second complex number:\n";
19
c2.input();
result=c1+c2;
result.output();
return 0;
}

Output
Enter first complex number:
4
5
Enter second complex number:
9
1
Result is : 13 + 6 i

(iii) Input and Output (Stream)Operator or Insertion (>>)and Extraction


Operator (<<)Overloading

 C++ is able to input and output the built-in data types using the stream extraction operator >>
and the stream insertion operator <<. The stream insertion and stream extraction operators
also can be overloaded to perform input and output for user-defined types like an object.
 Here, it is important to make operator overloading function a friend of the class because it
would be called without creating an object.
 Following example explains how extraction operator >> and insertion operator <<.

//Program for
#include <iostream.h>
class Distance
{
private:
int feet;
int inches;
public:
Distance()
{
feet = 0;
inches = 0;
}
Distance(int f, int i)
{
feet = f;
inches = i;
}
friend ostream &operator<<( ostream &output, const Distance &D )
{
output << "F : " << D.feet << " I : " << D.inches;
return output;
}
20
friend istream &operator>>( istream &input, Distance &D )
{
input >> D.feet >> D.inches;
return input;
}
};
int main()
{
Distance D1(11, 10), D2(5, 11), D3;
cout << "Enter the value of object : " << endl;
cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;
return 0;
}

Output
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10

C++ Type Conversions or Type Casting

• A cast is a special operator that forces one data type to be converted into another. As an
operator, a cast is unary and has the same precedence as any other unary operator.
• The most general cast supported by most of the C++ compilers is as follows:
(type) expression

Example
#include <iostream.h>
void main()
{
int a;
float b=7.33;
a=b;
cout<<a;
}

Types of Conversion
• Basic to Class Type Conversion
• Class to Basic Type Conversion
• Class to Class Type Conversion

21
1. Basic to Class Type Conversion
The conversion from basic to class type is easily carried out. It is automatically done by the compiler
with the help of in-built routines or by applying type casting.

Program
#include<iostream.h>
class sample
{
int hrs, minute;
public:
sample()
{
}
sample(int a)
{
hrs=a/60;
minute=a%60;
}
void display()
{
cout<<hrs<<"\t"<<minute;
}
};
void main()
{
sample obj;
int t=85;
obj=t;
obj.display();
}
Output
1 25

2. Class to Basic Type Conversion


In this type of conversion, the programmer needs to explicitly tell the compiler how to perform
conversion from class to basic type. These instructions are written in a member function. The compiler
searches for the operator keyword followed by data type and if it is need defined, it applies the
conversion function.

Program
#include<iostream.h>
class sample
{
int x,y;
public:
sample(int a,int b)
{
x=a;
22
y=b;
}
operator int()
{
return x+y;
}
};
void main()
{
sample obj(10,20);
int t;
t=obj;
cout<<t;
}
Output
30

3. Class to Class Type Conversion


When an object of one class is assigned to object of another class, it is necessary to give clear-cut
instruction to the compiler about how to make conversion between these two user defined data types.

Program
# include <iostream.h>
class in1
{
int code,items;
float price;
public:
in1(int a,int b,int c)
{
code=a;
items=b;
price=c;
}
void putdata()
{ cout<<code<<items<<price<<endl;
}
int getcode()
{
return code;
}
};
class in2
{
float value;
public:
void putdata()
{
23
cout<<value<<endl;
}
in2(in1 p)
{
value=p.getcode();
}
};
void main()
{
in1 s1(100,51,140.0);
in2 d1;
d1=in1(s1);
s1.putdata();
d1.putdata();
}
Output
100 51 140
100

University Questions

1. Write a C++ program to implement C = A + B , C = A − B and C = A * B where A , B and C are


objects containing a int value (vector).

#include<iostream.h>
class SAMPLE
{
float no;
public:
void getdata()
{
cout<<"\n ENTER AN FLOATING NUMBER :";
cin>>no;
}
void putdata()
{
cout<<"\n\nANSWER IS :"<<no;
}
SAMPLE operator+(SAMPLE)
{
SAMPLE temp;
temp.no=no+a.no;
return temp;
}
SAMPLE operator*(SAMPLE)
{
SAMPLE temp;
24
temp.no=no*b.no;
return temp;
}
SAMPLE operator-(SAMPLE)
{
SAMPLE temp;
temp.no=no-b.no;
return temp;
}
};
void main()
{
SAMPLE A,B,C;
A.getdata();
B.getdata();
C = A + B;
cout<<"\n\nAFTER ADDITION OF TWO OBJECTS";
C.putdata();
cout<<"\n\nAFTER MULTIPLICATION OF TWO OBJECTS";
C = A * B;
C.putdata();
cout<<"\n\nAFTER SUBSTRACTION OF TWO OBJECTS";
C = A - B;
C.putdata();
}

2. Write a C++ program to create a class called String and implement the following
operations. Display the result after every operation by overloading the operator <<.
(i) String s1 = “Anna”
(ii) String s2 = “University”
(iii) String s3 = s1 + s2 (Use copy constructor)

#include<iostream.h>
#include<conio.h>
#include<string.h>
class String
{
char *name;
int length;
public:
String()
{
length = 0;
name = new char[length + 1];
}
String(char *s)
{
length = strlen(s);
25
name = new char[length + 1];
strcpy(name,s);
}
String(String s)
{
length = s.length;
name = new char[length + 1];
strcpy(name,s,name);
}
ostream& operator <<(ostream &out)
{
out<<"Name : " << name;
return out;
}
void join(String &s1, String &s2)
{
length = s1.length + s2.length;
name = new char[length + 1];
strcpy(name,s1.name);
strcat(name,s2.name);
}
~String()
{
delete name;
}
};
void main()
{
String str1("Anna");
String str2(“University”);
String str3=str1;
String str4;
clrscr();
str4.join(str3,str2);
cout<<str4;
getch();
}

3. Write a Program to concatenate two strings using + operator overloading

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
class string
{
char str[100];
public:
26
void input();
void output();
string operator+(string s);
};
void string::input()
{
cout<<"enter the string\n";
gets(str);
}
string string::operator+(string s)
{
string temp;
strcpy(temp.str,str);
strcat(temp.str,s.str);
return(temp);
}
void string::output()
{
cout<<"the string is\n";
cout<<str;
}
void main()
{
string s1,s2,s3;
clrscr();
s1.input();
s2.input();
s3=s1+s2;
s3.output();
getch();
}

OUTPUT:
enter the string
farook
enter the string
college
the string is
farookcollege

4. Write a C++ program as follows to perform arithmetic operations on Rational numbers of


type a/b, where a and b are integers.
(i) Define a class by ‘Rational Number’. (4)
(ii) Use operator overloaded methods for addition and subtraction. (6)
(iii) Write a main program to demonstrate the use of this class and its methods. (4)
(iv) Give a sample output. (2)

#include <iostream.h>
27
class Rationalnumber
{
private:
float a,b;
public:
void input();
Rationalnumber operator+(Complex);
Rationalnumber operator- (Complex);
void output();
};
void Complex::input()
{
cin>>a>>b;
}
Rationalnumber Rationalnumber:: operator + (Complex c2) /* Operator Function */
{
Rationalnumber temp;
temp.a=a+c2.a;
temp.b=b+c2.b;
return temp;
}
Rationalnumber Rationalnumber:: operator - (Complex c2) /* Operator Function */
{
Rationalnumber temp;
temp.a=a - c2.a;
temp.b=b - c2.b;
return temp;
}
void Rationalnumber::output()
{
cout<<"Result is : "<<a<<"\t"<<b;
}
int main()
{
Rationalnumber c1, c2, result;
cout<<"Enter first complex number:\n";
c1.input();
cout<<"Enter second complex number:\n";
c2.input();
result=c1+c2;
result.output();
result=c1-c2;
result.output();
return 0;
}

Output
Enter first complex number:
28
6
5
Enter second complex number:
3
1
Result is : 9 6
Result is : 3 4

5. Write a C++ program to perform 2D matrix operations as follows:


(i) Define class MATRIX, use appropriate constructor(s).
(ii)Define methods for the following 2 matrix operations: determinant and transpose.
(iii)Write a main prog. to demonstrate the use of the MATRIX class and its methods.

#include <iostream.h>
class Matrix
{
int a[2][2];
public:
void getMatrix()
{
cout<<"Enter the Matrix value one by one";
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
cin>>a[i][j];
}
void transpose()
{
int t[2][2],i,j;
cout<<endl<<"transpose..."<<endl;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
t[i][j]=a[j][i];
for(i=0;i<2;i++)
for(j=0;j<2;j++)
cout<<" "<<t[i][j];
}
void determinent()
{
int z = (a[0][0] * a[1][1]) - (a[0][1]*a[1][0]);
cout<<endl<<"determinant = "<<z;
}
};
int main()
{
Matrix m;
m.getMatrix();
m.transpose();
29
m.determinent();
return 0;
}
Output:
Enter the Matrix value one by one
3
1
4
2
transpose...
3412
determinant = 2

6. Define a class String that could work as a user defined string type. Include constructor
that will enable us to initialize an object with string constant at the time of creation like
String s1(“Chettinad Tech”); And include another constructor that will initialize an
object with another object like String S2(S1); Include a function that adds two strings to
make a third string. Write a complete program to test your class.

#include<iostream.h>
#include<conio.h>
#include<string.h>
class String
{
char *name;
int length;
public:
String()
{
length = 0;
name = new char[length + 1];
}
String(char *s)
{
length = strlen(s);
name = new char[length + 1];

strcpy(name,s);
}
String(String s)
{
length = s.length;
name = new char[length + 1];

strcpy(name,s,name);
}
void display()
{
30
cout<<”Name : “ << name;
}
void join(String &s1, String &s2)
{
length = s1.length + s2.length;
name = new char[length + 1];

strcpy(name,s1.name);
strcat(name,s2.name);
}
};
void main()
{
String str1(“Chettinad”);
String str(str1);
String str3;
clrscr();
str3.join(str1,str2);
str3.display();
getch();
}
Output:
ChettinadChettinad

I/O Manipulators

C++ Manipulators are special stream functions, they are basically used to change the characteristics of
the input/output. As the name suggests these manipulate functions are used to change format flags
and different values of the stream.
The output values can be changed with the help of these c++ manipulators and take place of inputted
format values. All the c++ manipulators are include in the <iomanip.h> header file.
Some c++ manipulators which are commonly used are as follows :

(i) endl :
This manipulator is used to move the cursor to the next line in c++ program. Basically, this
manipulator is used in the output statements such as cout.

Example
cout<<"line number 1"<<endl;
cout<<"line number 2"<<endl;

The above two statements will give the output :


line number 1
line number 2

(ii) setw() or width(n):


This operator stands for set width. This is also an output manipulator. This manipulator is used when
you have to display the value at some width to the value.
31
Example
int a=56;
cout<<setw(10)<<a;

This will set the width of 10 spaces for a.

(iii) setbase() :
This is one of the powerful C++ manipulators. This manipulator is used to change the base of one
numeric value to the another base value. The syntax is:
setbase (base value);
Example
void main()
{
int i;
cout<<"enter any numeric value";
cin>>i;
cout<<"decimal value of"<<i<<"is"<<setbase(10);
cout<<"octal value of "<<i<<"is"<<setbase(8);
getch();
}

(iv) setfill() :
It works with setw() which fill tell the compiler to set the width for the characters to be displayed.
here setw(3); and setfill(“*”); will fill the blank space with ***. setfill(); will fill the unused blank
spaces created by setw();
setfill(char);

Example
void main()
{
int i=12345;
cout<<setfill('*')<<setw(9)<<a;
getch();
}

Output
****12345

(v) setprecision :
Sets the number of digits printed to the right of the decimal point. This applies to all subsequent
floating point numbers written to that output stream. However, this won't make floating-point
"integers" print with a decimal point. It's necessary to use fixed for that effect. The syntax is:
setprecision(p);
where p represents the precision value up to which you want to display the floating point value.
Example
void main()
32
{
float i,j,k;
i=8;
j=3;
k= i/j;
cout<<setprecision(3)<<i;
cout<<setprecision(4)<<i;
getch();
}

Output
2.666
2.6666

(vi) fixed
Used fixed point notation for floating-point numbers. Opposite of scientific. If no precision has already
been specified, it will set the precision to 6.

Example
float tenth = 0.1, one = 1.0, big = 1234567890.0;
cout << fixed << setprecision(3) << tenth << ", " << one << ", " << big << endl;

Output
0.100, 1.000, 1234567936.000

(vii) scientific
Formats floating-point numbers in scientific notation. Opposite of fixed.

Example
float tenth = 0.1, one = 1.0, big = 1234567890.0;
cout << "C. " << scientific << tenth << ", " << one << ", " << big << endl;

Output
1.000000e-001, 1.000000e+000, 1.234568e+009

(viii) left
Left justifies output in field width. Only useful after setw(n).

(ix) right
Right justifies output in field width. Since this is the default, it is only used to override the effects of
left. Only useful after setw(n).

Unit - III

Streams and various formatted I/O in C++

 C++ uses a convenient abstraction called streams to perform input and output operations in
sequential media such as the screen, the keyboard or a file.
33
 A stream is just a sequence of characters that can be accessed sequentially. Over time, a stream
may produce or consume potentially unlimited amounts of data. There is no need to know
details about the media associated to the stream or any of its internal specifications. All it needs
to know is that streams are a source/destination of characters, and that these characters are
provided/accepted sequentially (i.e., one after another).

Types of streams
 Input Streams
 Output Streams

Input streams are used to hold input from a data producer, such as a keyboard, a file, or a network.
For example, the user may press a key on the keyboard while the program is currently not expecting
any input.

Conversely, output streams are used to hold output for a particular data consumer, such as a monitor,
a file, or a printer. When writing data to an output device, the device may not be ready to accept that
data yet.

C++ provides the following classes to perform output and input of characters to/from files:

Header File Function and Description


This file defines the cin, cout, cerr and clog objects, which correspond to the
<iostream> standard input stream, the standard output stream, the un-buffered standard
error stream and the buffered standard error stream, respectively.
This file declares services useful for performing formatted I/O with so-called
<iomanip>
parameterized stream manipulators, such as setw and setprecision.

34
<fstream> This file declares services for user-controlled file processing.

These classes are derived directly or indirectly from the classes istream and ostream. cin is an object
of class istream and cout is an object of class ostream. C++ comes with the following four predefined
standard stream objects.

stream description
cin standard input stream
cout standard output stream
cerr standard error (output) stream
clog standard logging (output) stream

The standard output stream (cout):


The predefined object cout is an instance of ostream class. The cout object is said to be "connected to"
the standard output device, which usually is the display screen. The cout is used in conjunction with
the stream insertion operator, which is written as << which are two less than signs.

The standard input stream (cin):


The predefined object cin is an instance of istream class. The cin object is said to be attached to the
standard input device, which usually is the keyboard. The cin is used in conjunction with the stream
extraction operator, which is written as >> which are two greater than signs as shown in the following
example.

Program
#include <iostream.h>
int main( )
{
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
}

Output
Please enter your name: cplusplus
Your name is: cplusplus

The standard error stream (cerr):


The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to the
standard error device, which is also a display screen but the object cerr is un-buffered and each
stream insertion to cerr causes its output to appear immediately.

The standard log stream (clog):


The predefined object clog is an instance of ostream class. The clog object is said to be attached to the
standard error device, which is also a display screen but the object clog is buffered. This means that
each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the
buffer is flushed.
35
Inheritance

Inheritance is one of the key feature of object-oriented programming including C++ which allows user
to create a new class (derived class) from a existing class(base class). The derived class inherits all
feature from a base class and it can have additional features of its own.

Access Control and Inheritance


A derived class can access all the non-private members of its base class. Thus base-class members that
should not be accessible to the member functions of derived classes should be declared private in the
base class. We can summarize the different access types according to who can access them in the
following way:

Access public protected private


Same class yes yes yes
Derived classes yes yes no
Outside classes yes no no

A derived class inherits all base class methods with the following exceptions:
 Constructors, destructors and copy constructors of the base class.
 Overloaded operators of the base class.
 The friend functions of the base class.

Types of Inheritance
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)

1. Single Inheritance
It is the inheritance hierarchy wherein one derived class inherits from one base class.

36
Program
#include<iostream.h>
class Shape
{
protected:
float width, height;
public:
void set_data (float a, float b)
{
width = a;
height = b;
}
};
class Rectangle: public Shape
{
public:
float area ()
{
return (width * height);
}
};
int main ()
{
Rectangle rect;
rect.set_data (5,3);
cout<<rect.area() << endl;
return 0;
}
Output
15

2. Multiple Inheritance
It is the inheritance hierarchy wherein one derived class inherits from multiple base classes.

37
Program
#include<iostream.h>
#include<conio.h>
class student
{
protected:
int rno,m1,m2;
public:
void get()
{
cout<<"Enter the Roll no :";
cin>>rno;
cout<<"Enter the two marks :";
cin>>m1>>m2;
}
};
class sports
{
protected:
int sm; // sm = Sports mark
public:
void getsm()
{
cout<<"\nEnter the sports mark :";
cin>>sm;
}
};
class statement : public student , public sports
{
int tot,avg;
public:
void display()
{
tot=(m1+m2+sm);
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal : "<<tot;
cout<<"\n\tAverage : "<<avg;
}
};
void main()
{

38
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();
}
Output:
Enter the Roll no: 100
Enter two marks
90
80
Enter the Sports Mark: 90
Roll No: 100
Total : 260
Average: 86.66

3. Hierarchical Inheritance
It is the inheritance hierarchy wherein multiple subclasses inherit from one base class.

Program
#include<iostream.h>
class Shape
{
protected:
float width, height;
public:
void set_data (float a, float b)
{
width = a;
height = b;
}
};
class Rectangle: public Shape
{
public:
float area ()
{
return (width * height);
}
};
class Triangle: public Shape

39
{
public:
float area ()
{
return (width * height / 2);
}
};
int main ()
{
Rectangle rect;
Triangle tri;
rect.set_data (5,3);
tri.set_data (2,5);
cout<<rect.area() << endl;
cout<<tri.area() << endl;
return 0;
}
Output
15
5

4. Multilevel Inheritance
It is the inheritance hierarchy wherein subclass acts as a base class for other classes.

Program
#include<iostream.h>
#include<conio.h>
class top
{
public :
int a;
void getdata()
{
cout<<"\n\nEnter first Number :::\t";
cin>>a;
}
void putdata()

40
{
cout<<"\nFirst Number Is :::\t"<<a;
}
};
//First level inheritance
class middle :public top
{
public:
int b;
void square()
{
getdata();
b=a*a;
cout<<"\n\nSquare Is :::"<<b;
}
};
//Second level inheritance
class bottom :public middle
{
public:
int c;
void cube()
{
square();
c=b*a;
cout<<"\n\nCube :::\t"<<c;
}
};
int main()
{
clrscr();
bottom b1;
b1.cube();
getch();
}

Output
Enter first number::: 4
Square is :::16
Cube ::: 64

5. Hybrid (Virtual) Inheritance


The inheritance hierarchy that reflects any legal combination of other four types of inheritance is
called Hybrid Inheritance.

41
Program
#include<iostream.h>
#include<conio.h>
class A
{
public:
int l;
void len()
{
cout<<"\n\nLenght :::\t";
cin>>l;
}
};
class B :public A
{
public:
int b,c;
void l_into_b()
{
len();
cout<<"\n\nBreadth :::\t";
cin>>b;
c=b*l;
}
};
class C
{
public:
int h;
void height()
{
cout<<"\n\nHeight :::\t";
cin>>h;
}
};
class D:public B,public C
{
public:
42
int res;
void result()
{
l_into_b();
height();
res=h*c;
cout<<"\n\nResult (l*b*h) :::\t"<<res;
}
};
int main()
{
clrscr();
D d1;
d1.result();
getch();
}

Output
Length ::: 20
Breadth ::: 30
Height :::40
Result (l*b*h) ::: 24000

Runtime Polymorphism - Virtual Function

A virtual function in C++ is :


- A simple member function of a class which is declared with “virtual” keyword
- It usually performs different functionality in its derived classes.
- The resolving of the function call is done at run-time.
Syntax
virtual void display()
{
……………..
}

Program
#include<iostream.h>
#include<conio.h>
class Base
{
public:
virtual void show()
{
cout << "Base class";
}
};
class Derived : public Base
{
43
public:
void show()
{
cout << "Derived Class";
}
}
int main()
{
Base* b;
Derived d;
b = &d;
b->show();
}
Output
Derived class

Pure Virtual Functions


Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and
ends with = 0.
Syntax
virtual void show() = 0;

Abstract Classes
• Any class that has at least one pure virtual function is called an abstract class.
• Example
// An abstract class
class Test
{
public:
virtual void show() = 0;
};

Program
//Program for Pure Virtual Functions and Abstract Classes
#include <iostream.h>
class Shape
{
protected:
float rad;
public:
void get_data()
{
cin>>rad;
}
virtual float area() = 0;
};
class Square : public Shape
44
{
public:
float area()
{
return rad*rad;
}
};
class Circle : public Shape
{
public:
float area()
{
return 3.14*rad*rad;
}
};

void main()
{
Square s;
Circle c;
cout<<"Enter length: ";
s.get_data();
cout<<"Area of square: "<<s.area();
cout<<"\nEnter radius:";
c.get_data();
cout<<"Area of circle: "<<c.area();
}
Output
Enter length to calculate area of a square: 5
Area of square: 25
Enter radius to calculate area of a circle: 2
Area of circle: 12.56

Templates

• Templates are a feature of the C++ programming language that allows functions and classes to
operate with generic types. This allows a function or class to work on many different data types
without being rewritten for each one.
• Types
– Function Template
– Class template

(i) Function Template


• A function template behaves like a function except that the template can have arguments of
many different types. In other words, a function template represents a family of functions.
• Syntax
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
45
Example
#include<iostream.h>
#include<conio.h>
template<class t>
void swap(t &x,t &y)
{
t temp;
temp=x;
x=y;
y=temp;
cout<<x<<"\t"<<y;
}
void main()
{
int a=5,b=2;
float c=7.23,d=1.67;
clrscr();
cout<<"Integer swapping";
swap(a,b);
cout<<"Floatig point swapping";
swap(c,d);
getch();
}
Output:
Integer swapping
2 5
Floating point swapping
1.67 7.23

(ii) Class template


A class template defines a family of classes. The syntax is
template < parameter-list > class-declaration

//Program for Class Template


#include <iostream.h>
template <class T>
class Stack
{
private:
T a,b;
public:
Stack(T x,T y)
{
a=x;
b=y;
}
void display()
{
46
cout<<a<<"\t"<<b;
}
};
int main ()
{
Stack<int> i(10,20);
Stack<char> c('P','Q');
i.display();
c.display();
return 0;
}

File Handling in C++

File Handling concept in C++ language is used for store a data permanently in computer. Using file
handling we can store our data in Secondary memory (Hard disk).

Advantages
 For permanent storage.
 The transfer of input - data or output - data from one computer to another can be easily done by
using files.

For read and write from a file you need another standard C++ library called fstream, which defines
three new data types:

Datatype Description
ofstream This is used to create a file and write data on files
ifstream This is used to read data from files
This is used to both read and write data from/to
fstream
files

47
Steps to be performed in File Handling
 Naming a file
 Opening a file
 Reading data from file
 Writing data into file
 Closing a file

Functions use in File Handling

Function Operation
open() To create a file
close() To close an existing file
get() Read a single character from a file
put() write a single character in file.
read() Read data from file
write() Write data into file.

Defining and Opening a File


The function open() can be used to open multiple files that use the same stream object.
Syntax
file-stream-class stream-object;
stream-object.open("filename");
Example
ofstream outfile; // create stream
outfile . open ("data1"); // connect stream to data1

Closing a File
A file must be close after completion of all operation related to file. For closing file we need close()
function.
Syntax
outfile.close();

File Opening mode

File mode parameter Meaning


ios::app Append to end of file

48
ios::ate go to end of file on opening
ios::binary file open in binary mode
ios::in open file for reading only
ios::out open file for writing only
ios::nocreate open fails if the file does not exist
ios::noreplace open fails if the file already exist
ios::trunc delete the contents of the file if it exist

Both ios :: app and ios :: ate take us to the end of the file when it is opened. The difference between the
two parameters is that the ios :: app allows us to add data to the end of file only, while ios :: ate mode
permits us to add data or to modify the existing data any where in the file. The mode can combine two
or more parameters using the bitwise OR operator (symbol |)

Example
fstream file;
file.Open("data . txt", ios :: out | ios :: in);

File pointer
Each file have two associated pointers known as the file pointers. One of them is called the input
pointer (or get pointer) and the other is called the output pointer (or put pointer). The input pointer is
used for reading the contents of a given file location and the output pointer is used for writing to a
given file location.

Types of File Access


 Sequential Access
 Random Access

1. Sequential Access
Sequential Access files access the contents of a file in sequence - hence the name. A files access pointer
will start at the first character in the file and proceed until the last eof(). The advantage of this method
of file access is that it is relatively simple. It is convenient for storing logs, trace files, and ASCII

49
data. The disadvantage is that, if you want to store data that is more complex than ASCII text, you are
limited. For many purposes, sequential access files are fine.

Functions used in Sequential File Access


(i) getline
getline reads characters from an input stream and places them into a string.

Example
#include<iostream.h>
#include<fstream.h>
void main()
{
char str[50];
ifstream in;
in.open(“input.txt”,ios::in);
while(in)
{
getline(in,str,10);
cout<<str;
}
}
input.txt
hello welcome
Output
Hello welcome

(ii) put() and get() function


The function put() write a single character to the associated stream. Similarly, the function get() reads
a single character from the associated stream.

Example
#include<iostream.h>
#include<fstream.h>
void main()
{
char s;
ifstream in;
in.open(“input.txt”,ios::in);
while(in)
{
get(in,s);
put(s);
}
}

(iii) read() and write() function

50
These function take two arguments. The first is the address of the variable V , and the second is the
length of that variable in bytes. The address of variable must be cast to type char * (i.e pointer to
character type).

Syntax
file . read ((char *)&V , sizeof (V));
file . Write ((char *)&V , sizeof (V));

2. Random Access
Each file stream class contains a file pointer that is used to keep track of the current read/write
position within the file. When something is read from or written to a file, the reading/writing happens
at the file pointer’s current location. By default, when opening a file for reading or writing, the file
pointer is set to the beginning of the file. However, if a file is opened in append mode, the file pointer is
moved to the end of the file, so that writing does not overwrite any of the current contents of the file.

Functions
seekg() moves get pointer (input) to a specified location.
seekp() moves put pointer (output) to a specified location.
tellg() gives the current position of the get pointer.
tellp() gives the current position of the put pointer.

The other prototype for these functions is:


seekg(offset, refposition );
seekp(offset, refposition );

The parameter offset represents the number of bytes the file pointer is to be moved from the location
specified by the parameter refposition. The refposition takes one of the following three constants
defined in the ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file
Example

fout . seekg(0, ios :: beg) go to start


fout . seekg(0, ios :: cur) stay at current position
fout . seekg(0, ios :: end) go to the end of file
fout . seekg(m, ios :: beg) move to m+1 byte in the file
fout . seekg(m, ios :: cur) go forward by m bytes from the current position
fout . seekg(-m, ios :: cur) go backward by m bytes from the current position
fout . seekg(-m, ios :: end) go backward by m bytes from the end

Program for Random Access


#include<iostream.h>
#include<fstream.h>
int main()
{
fstream fp;
char buf[100];
51
int pos;
fp.open("random.txt", ios :: out | ios :: ate);
cout << "\nWriting to a file ... " << endl;
fp << "This is a line" << endl;
fp << "This is a another line" << endl;
pos = fp.tellp();
cout << "Current position of put pointer : " << pos << endl;
fp.seekp(-10, ios :: cur);
fp << endl << "Writing at a random location ";
fp.seekp(7, ios :: beg);
fp << " Hello World ";
fp.close();
cout << "Writing Complete ... " << endl;
fp.open("random.txt", ios :: in | ios :: ate);
cout << "\nReading from the file ... " << endl;
fp.seekg(0);
while (!fp.eof())
{
fp.getline(buf, 100);
cout << buf << endl;
}
pos = fp.tellg();
cout << "\nCurrent Position of get pointer : " << pos << endl;
return 0;
}

University Questions - File I/O

1. Program to copy contents of file to another file.


#include<iostream.h>
#include<fstream.h>
int main()
{
ifstream fin;
fin.open("input.txt",ios::in);
ofstream fout;
fout.open("sample.txt",ios::out);
char ch;
while(!fin.eof())
{
fin.get(ch);
fout << ch;
}
fin.close();
fout.close();
return 0;
}
Input
52
Input.txt
Hello
Welcome

Output
sample.txt
Hello
Welcome

2. Write a C++ program to create a file with odd numbers and create another file with set of
even numbers and merge these two files and store it another file.
#include<iostream.h>
#include<fstream.h>
int main()
{
ifstream fin1,fin2;
fin1.open("odd.txt");
fin2.open("even.txt");
ofstream fout;
fout.open("sample.txt");
char ch[10];
while(fin1.eof()!=0 && fin2.eof()!=0)
{
fin1.getline(ch,10);
fout << ch;
fin2.getline(ch,10);
fout << ch;
}
fin1.close();
fin2.close();
fout.close();
return 0;
}

Input
odd.txt
1
3
5
7
9

even.txt
2
4
6
8
10
53
Output
Sample.txt
1
2
3
4
5
6
7
8
9
10

3. Write a C++ program that merges lines alternately from two files and writes the results to
new file. If one file has less number of lines than the other, the remaining lines from the larger
file should be simply copied into the target file.
#include<iostream.h>
#include<fstream.h>
int main()
{
ifstream fin1,fin2;
fin1.open("input1.txt");
fin2.open("input2.txt");
ofstream fout;
fout.open("sample.txt");
char ch[10];
while(fin1.eof()!=0 && fin2.eof()!=0)
{
fin1.getline(ch,10);
fout << ch;
fin2.getline(ch,10);
fout << ch;
}
while(fin1.eof()!=0)
{
fin1.getline(ch,10);
fout << ch;
}
while(fin2.eof()!=0)
{
fin2.getline(ch,10);
fout << ch;
}
fin1.close();
fin2.close();
fout.close();
return 0;
54
}

Input
Input1.txt
Hello
Welcome

Input2.txt
Chettinad
College
Of
Engineering

Output
Sample.txt
Hello
Chettinad
Welcome
College
Of
Engineering

4. Write a C++ program to demonstrate file handling as follows: get strings as input from the
user, store them in a file, retrieve them and display them.
#include<iostream.h>
#include<fstream.h>
int main()
{
ofstream fout;
char str[20],str1[20];
cout<<”\n Enter the string:”;
cin>>str1;
fout.open("out.txt",ios::out);
fout << str1;
fout.close();
ifstream fin;
fin.open("out.txt",ios::in);
fin.getline(str2,20);
cout<<”String is “<<str2;
return 0;
}
Input
Enter the string:
Hello

Output
out.txt
Hello
55
String is Hello

Exception Handling

Exception
An exception is a problem that arises during the execution of a program. A C++ exception is a response
to an exceptional circumstance that arises while a program is running, such as an attempt to divide by
zero. Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
 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.
 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.
 throw: A program throws an exception when a problem shows up. This is done using a throw
keyword.

Exception Handling
To implement exception handling in C++, you use try, throw, and catch expressions.

Identify the exception


A try/catch block is placed around the code that might generate an exception. Code within a try/catch
block is referred to as protected code, and the syntax for using try/catch looks like the following:

Throwing Exceptions:
Exceptions can be thrown anywhere within a code block using throw statements. The operand of the
throw statements determines a type for the exception and can be any expression and the type of the
result of the expression determines the type of exception thrown.

Catching Exceptions:
56
The catch block following the try block catches any exception. You can specify what type of exception
you want to catch and this is determined by the exception declaration that appears in parentheses
following the keyword catch.
Example

Example Program
#include <iostream.h>
int main()
{
int x = -1;
try
{
if (x < 0)
{
throw x;
}
}
catch (int x )
{
cout << "Exception Caught \n";
}
return 0;
}

Output:
Exception Caught

Advantages
1) Separation of Error Handling code from Normal Code:
2) Functions/Methods can handle any exceptions they choose
3) Grouping of Error Types

Multiple catch statements


It is possible that a program segment has more than one condition to throw an exception. The general
syntax is
57
try
{
//try block
}
catch(type1 arg)
{
//catch block1
}
catch(type2 arg)
{
//catch block2
}
………
………
catch(typeN arg)
{
//catch blockN
}

When an exception is thrown, the exception handlers are searched in order for an appropriate match.
The first handler that yields a match is executed. After executing the handler, the control goes to the
first statement after the last catch block for that try. When no match is found, the program is
terminated. It is possible that arguments of several catch statements match the type of an exception. In
such cases, the first handler that matches the exception type is executed.

Program
#include<iostream.h>
#include<conio.h>
void test(int x)
{
try
{
if(x>0)
throw x;
else
throw 'x';
}
catch(int x)
{
cout<<"Catch a integer and that integer is:"<<x;
}
catch(char x)
{
cout<<"Catch a character and that character is:"<<x;
}
}
void main()
58
{
clrscr();
cout<<"Testing multiple catches\n:";
test(10);
test(0);
getch();
}
Output:
Testing multiple catches
Catch a integer and that integer is: 10
Catch a character and that character is: x

Handling multiple exception in single catch block


It is also possible to define a single or default catch block from one or more exceptions of different
types. In such situations, a single catch block is used to catch the exceptions thrown by the multiple
throw statements.

Program
#include<iostream.h>
#include<conio.h>
void test(int x)
{
try
{
if(x>0)
throw x;
else
throw 'x';
}
catch(…)
{
cout<<"Caught an exception”<<x;
}
}
void main()
{
clrscr();
cout<<"Testing multiple catches\n:";
test(10);
test(0);
getch();
}
Output:
Testing multiple catches
Caught an exception
Caught an exception

Rethrowing an exception
59
Rethrowing an expression from within an exception handler can be done by calling throw, by itself,
with no exception. This causes current exception to be passed on to an outer try/catch sequence. An
exception can only be rethrown from within a catch block. When an exception is rethrown, it is
propagated outward to the next catch block.

Program
#include <iostream.h>
void MyHandler()
{
try
{
throw 5;
}
catch (int a)
{
cout <<”Caught exception inside MyHandler\n”;
throw; //rethrow an exception
}
}
int main()
{
try
{
MyHandler();
}
catch(int b)
{
cout <<”Caught exception inside Main\n”;
}
return 0;
}
Output :
Caught exception inside MyHandler
Caught exception inside Main

Standard Template Library (STL)

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 algorithms and data
structures like vectors, lists, queues, and stacks.

Components of STL

60
Relationship between the components of STL

1. Containers
 A container is a holder object that stores a collection of other objects (its elements). They are
implemented as class templates, which allows a great flexibility in the types supported as
elements.
 The container manages the storage space for its elements and provides member functions to
access them, either directly or through iterators (reference objects with similar properties to
pointers).
 Many containers have several member functions in common, and share functionalities. The
decision of which type of container to use for a specific need does not generally depend only on
the functionality offered by the container, but also on the efficiency of some of its members
(complexity).

Types of Containers
 Sequence containers
 Associative containers
 Derived Containers or container adapters

(i) Sequence containers


Sequence containers maintain the ordering of inserted elements that you specify.
 A vector container behaves like an array, but can automatically grow as required. It is random
access and contiguously stored, and length is highly flexible. For these reasons and more,
vector is the preferred sequence container for most applications.
 An array container has some of the strengths of vector, but the length is not as flexible.
61
 A deque (double-ended queue) container allows for fast insertions and deletions at the
beginning and end of the container. It shares the random-access and flexible-length advantages
of vector, but is not contiguous.
 A list container is a doubly linked list that enables bidirectional access, fast insertions, and fast
deletions anywhere in the container, but you cannot randomly access an element in the
container.

(ii) Associative Containers


Associative containers are containers that automatically sort their inputs when those inputs are
inserted into the container. By default, associative containers compare elements using operator<.
 A set is a container that stores unique elements, with duplicate elements disallowed. The
elements are sorted according to their values.
 A multiset is a set where duplicate elements are allowed.
 A map (also called an associative array) is a set where each element is a pair, called a key/value
pair. The key is used for sorting and indexing the data, and must be unique. The value is the
actual data.
 A multimap (also called a dictionary) is a map that allows duplicate keys. Real-life dictionaries
are multimaps: the key is the word, and the value is the meaning of the word. All the keys are
sorted in ascending order, and you can look up the value by key. Some words can have multiple
meanings, which is why the dictionary is a multimap rather than a map.

(iii) Container Adapters


Container adapters are special predefined containers that are adapted to specific uses. The interesting
part about container adapters is that you can choose which sequence container you want them to use.
 A stack is a container where elements operate in a LIFO (Last In, First Out) context, where
elements are inserted (pushed) and removed (popped) from the end of the container. Stacks
default to using deque as their default sequence container (which seems odd, since vector
seems like a more natural fit), but can use vector or list as well.
 A queue is a container where elements operate in a FIFO (First In, First Out) context, where
elements are inserted (pushed) to the back of the container and removed (popped) from the
front. Queues default to using deque, but can also use list.
 A priority queue is a type of queue where the elements are kept sorted (via operator<). When
elements are pushed, the element is sorted in the queue. Removing an element from the front
returns the highest priority item in the priority queue.

2. Algorithms
Algorithms are a fundamental part of the Standard Template Library. Algorithms do not work with
containers themselves but rather with iterators. Therefore, the same algorithm can be used by most if
not all of the STL containers.

3. Iterators
An iterator is an object that can iterate over elements in an STL container and provide access to
individual elements. The STL containers all provide iterators so that algorithms can access their
elements in a standard way without having to be concerned with the type of container the elements
are stored in.
There are five categories of iterators. In order of increasing power, the categories are:
 Output.
 Input.
62
 Forward.
 Bidirectional.
 Random access.

Program
// C++ Program to Implement Vector in STL
#include <iostream.h>
#include <vector.h>
int main()
{
vector<int> ss;
int choice, item;
while (1)
{
cout<<"1.Insert the Vector"<<endl;
cout<<"2.Delete Last Element of the Vector"<<endl;
cout<<"3.Size of the Vector"<<endl;
cout<<"4.Display by Index"<<endl;
cout<<"5.Clear the Vector"<<endl;
cout<<"6.Exit"<<endl;
cout<<"Enter your Choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter value to be inserted: ";
cin>>item;
ss.push_back(item);
break;
case 2:
cout<<"Delete Last Element Inserted:"<<endl;
ss.pop_back();
break;
case 3:
cout<<"Size of Vector: ";
cout<<ss.size()<<endl;
break;
case 4:
cout<<"Displaying Vector by Index: ";
for (int i = 0; i < ss.size(); i++)
{
cout<<ss[i]<<" ";
}
cout<<endl;
break;
case 5:
ss.clear();
cout<<"Vector Cleared"<<endl;
63
break;
case 6:
exit(1);
break;
}
}
return 0;
}

Output
1.Insert Element into the Vector
2.Delete Last Element of the Vector
3.Size of the Vector
4.Display by Index
5.Clear the Vector
6.Exit
Enter your Choice: 1
Enter value to be inserted: 4

Enter your Choice: 1


Enter value to be inserted: 6

Enter your Choice: 1


Enter value to be inserted: 3

Enter your Choice: 1


Enter value to be inserted: 8

Enter your Choice: 1


Enter value to be inserted: 9

Enter your Choice: 1


Enter value to be inserted: 2

Enter your Choice: 3


Size of Vector: 6

Enter your Choice: 4


Displaying Vector by Index: 4 6 3 8 9 2

Enter your Choice: 2


Delete Last Element Inserted:

Enter your Choice: 3


Size of Vector: 5

Enter your Choice: 4


Displaying Vector by Index: 4 6 3 8 9
64
Enter your Choice: 6
Vector Cleared

Enter your Choice: 3


Size of Vector: 0

UNIT – IV

Java - Introduction
 Java was invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike
Sheridan.
 Java was designed by Sun Microsystems in the early 1990s.
 This language was initially called ―Oak but was renamed ―Javain 1995.
 Java has become the most important programming language because it is a language for
internet.
 The most exciting feature of Java is its platform independency.
 Any hardware or software environment in which a program runs, known as platform. Since
Java has its own Runtime Environment (JRE) and API, it is called platform.

Uses
 Desktop Applications
 Web Applications
 Enterprise Applications
 Mobile Applications
 Embedded System
 Games

Features of Java

 Simple
 Platform Independent and Portable
 Object-oriented
 Robust and Secure
 Multithreaded
 Architecture-neutral
 Interpreted
 High performance
 Distributed
 Dynamic

1. Simple
 Syntax is based on C++
 Removed many confusing features of C++, like operator overloading, multiple inheritance,
explicit pointers etc.

65
 Contains no goto statement, but break and continue
 Eliminates much redundancy (e.g. no structs, unions, or functions)
 No need to remove unreferenced objects because there is Automatic Garbage Collection in java.

2. Platform Independent and Portable


 A platform is the hardware or software environment in which a program runs.
 Java code can be run on multiple platforms. E.g Windows, Linux, Solaris, etc.
 Java code is compiled by the compiler and converted into bytecode. This bytecode is platform
independent because it can be run on multiple platforms.
 Write-Once Run-Anywhere
 In another words, java is portable because the same java program can be executed in multiple
platforms without making any changes in the source code.

3. Object-Oriented
 Java programming is object-oriented programming language, which means that you focus on
the data in your application and methods that manipulate that data, rather than in terms of
procedures.
 Like C++, java provides most of the object oriented features.
 In an object-oriented system, a class is a collection of data and methods that operate on that
data. Taken together, the data and methods describe the state and behavior of an object.
 Classes are arranged in a hierarchy, so that a subclass can inherit behavior from its superclass.
 Java is pure OOP Language. (while C++ is semi object oriented)

4. Robust and Secure


 Robust means strong.
 Designed with the intention of being secure.
 Java uses strong memory management.
 Java does automatic garbage collection, which prevents memory leaks.
 Exception handling and strict compile time and run time checking of data type.

5. Multithreaded
 Java supports multithreaded programming, which allows you to write programs that do many
things simultaneously.
 A thread is like a separate program, executing concurrently.
 Java programs deal with many tasks at once by defining multiple threads.
 The main advantage of multi-threading is that is shares the same memory.
 The java.lang package provides a Thread class that supports methods to start, run and stop a
thread and check on its status.

6. Architecture-Neutral
 Java is not tied to a specific machine or operating system architecture.
 Machine Independent i.e Java is independent of hardware.
 Easy to interpret on any machine.

7. Interpreted
 Java supports cross-platform code through the use of Java bytecode.
 Bytecode can be interpreted on any platform by Java Virtual Machine.
66
8. High Performance
 Bytecodes are highly optimized.
 JVM can executed them much faster .
 Interpretation of bytecodes slowed performance in early versions, but advanced virtual
machines with adaptive and just-in-time compilation and other techniques now typically
provide performance up to 50% to 100% the speed of C++ programs.
9. Distributed
 Java is designed for the distributed environment of the Internet, because it handles TCP/IP
protocols.
 In fact, accessing a resource using a URL is not much different from accessing a file.
 The original version of Java (Oak) included features for intraaddress- space messaging. This
allowed objects on two different computers to execute procedures remotely.
 Java revived these interfaces in a package called Remote Method Invocation (RMI).

10. Dynamic
 Java programs carry with them substantial amounts of run-time type information that is used
to verify and resolve accesses to objects at run time.
 The linking of data and methods to where they are located, is done at run-time.

Byte code & virtual machine

Java Compilation Process

JAVA VIRTUAL MACHINE (JVM)

67
 The Java Compiler converts the Source code into the Byte code.
 But java compiler is not executable code. Rather, it is byte code.
 This bytecode will be stored in class files.
 Bytecode is highly optimized set of instructions designed to be executed by the Java run – time
system, which is called the Java Virtual Machine (JVM).
 Java Virtual Machine (JVM) is unique for each platform. Though JVM is unique for each
platform, all interpret the same bytecode and convert it into machine code required for its own
platform and this machine code will be directly executed by the machine in which java program
runs.
 That is, in its standard form, the JVM is an interpreter for bytecode.

Components of JVM
JVM is divided into several components like the stack, the garbage-collected heap, the registers and the
method area.

Stack
 Storing the local variables of any method.
68
 Storing various arguments passed to the method.
 Keeps track of each and every method invocation. This is called Stack Frame.

Registers
 Stack performs manipulation of data with the help of three Registers namely vars, frame, optop.
This registers points to different parts of current Stack.
 The vars registers point to the local variable in the stack. These local variables are actually used
by the currently executing method.
 The stack operations are pointed by frame registers.
 The optop registers are used to point out the current byte code instruction.
Method Area
 This area stores the byte code of various methods.
 The program counter points to some byte in the method area.
 It always keep tracks of the current instruction which is being executed (interpreted). After
execution of an instruction, the JVM sets the PC to next instruction.
 Method area is shared among all the threads of a process.
 Hence if more then one threads are accessing any specific method or any instructions,
synchorization is needed.
 Synchronization in JVM is achieved through Monitors.

Garbage Collected Heap


 The Garbage-collected Heap is where the objects in Java programs are stored.
 Whenever we allocate an object using new operator, the heap comes into picture and memory
is allocated from there.
 Unlike C++, Java does not have free operator to free any previously allocated memory. Java does
this automatically using Garbage collection mechanism.
 Remember that the local object reference resides on Stack but the actual object resides in Heap
only.
 Also, arrays in Java are objects, hence they also resides in Garbage-collected Heap.

Java Runtime Environment (JRE) and Java Architecture

69
 Java Runtime Environment contains JVM, class libraries and other supporting components.
 Java source code is compiled into bytecode by Java compiler.
 This bytecode will be stored in class files.
 During runtime, this bytecode will be loaded, verified and JVM interprets the bytecode into
machine code which will be executed in the machine in which the Java program runs.
 The program that are running on JVM must be compiled into a binary format which is denoted
by .class files. Multiple class files are packaged into one .jar file.
 The JVM executes .class or .jar files, by either interpreting it or using a just-in-time
compiler(JIT).
 The JIT is used for compiling and not for interpreting the file. It is used to achieve greater speed.
A Java Runtime Environment performs the following main tasks respectively.
o Class loader - Loads the class
o Bytecode verifier - Verifies the bytecode.
o JVM - Interprets the bytecode

Java Structure

70
Example Program
//A Simple Java Program
class Sample
{
public static void main(String args[ ])
{
System.out.println(“Java is Better than C and C++”);
}
}

Java Command Line Arguments

The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an
input.

Example
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Z:\> javac CommandLineExample.java
Z:\> java CommandLineExample sonoo
Output
Your first argument is: sonoo
Java tokens

71
Smallest individual units in a program are known as tokens. The compiler recognizes them for building
up expressions and statements. A Java program is a collection of tokens, comments and white spaces.
Java language includes five types of tokens. They are:
1. Reserved Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators

1.Reserved Keywords
Keywords are an essential part of a language definition. They implement specific features of the
language. Java language has reserved 60 words as keywords. Java keywords, combined with operators
and separators according to a syntax, form definition of the Java language.

2. Identifiers
Identifiers are programmer – designed tokens. They are used for naming classes, methods, variables,
objects, labels, packages and interfaces in a program. Java identifiers follow the following rules:
1. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not begin with a digit.
3. Uppercase and Lowercase letters are distinct.
4. They can be of any length.

Names of all public methods and instance variables start with a leading lowercase letter. Example:
average
sum

When more than one word are used in a name, the second and subsequent words are marked with a
leading uppercase letters. Example:

72
dayTemperature
firstDayofMonth
totalMarks

All private and local variables use only lowercase letters combined with underscores. Example:
length
batch_strength

All classes and interfaces start with a leading uppercase letter(and each subsequent word with a
leading uppercase letter). Example:
Student
HelloJava

Variables that represent constant values use all uppercase letters and underscores between words.
Example:
TOTAL
PRINCIPAL_AMOUNT

3. Literals

Literals in java are a sequence of characters (digits, letters, and other characters) that represent
constant values to be stored in variables. Java language specifies five major types of literals. They are:
• Integer literals
• Floating_point literals
• Character literals
• String literals
• Boolean literals

Integer Literals
An Integer literal refers to a sequence of digits. There are two types of integers. namely,
(i) Decimal integer Literals
Ex: 123 -321 0 654321 - Valid
Ex: 15 750 20,000 $1000 - Invalid
(ii) Hexadecimal integer Literals
Ex: 0X2 0X9F 0Xbcd 0x
73
Real Literals
Integer literals are inadequate to represent quantities that vary continuously, such as distances, height
temperatures, prices and so on. These quantities are represented by numbers containing fractional
par, like 17.548. Such numbers are called real (or floating point) numbers.

Boolean Literals
There are two Boolean literal values: true or false

Single Character Literals


A single-character literal (or simply character constant) contains a single character enclosed within a
pair of single quote marks. Examples of character in the examples above constants are:
‘5’ ‘X’

String Literals
A string literal is a sequence of characters enclosed between double quotes. The characters may be
alphabets, digits, special characters and blank spaces.
Examples are: “2001” “WELL DONE”

Backslash character constants


Java supports some special backslash character constants that are used in output methods. For
example, ue the symbol '\n' stands for a new-line character.

4. Operators
An operator is a symbol that takes one or more arguments and operates on them to produce a result.
•Arithmetic operators
• Relational operators
• Logical operators
• Assignment operators
• Increment and Decrement operators
• Conditional operators
• Bitwise operators
• Special operators

5. Separators
Separators are symbols used to indicate where groups of code are divide and arranged. They basically
define the shape and function of our code.

74
Name What it is used for
paraentheses() Method definitions and invocation
braces { } Automatically initialized arrays
brackets [ ] declare array types
semicolon ; Used to separate statements
comma , Used to separate variable declaration
period . Used to separate package name

Java Data Types

Every variable in java has a data type. Data types specify the size and type of values that can be stored.
Java language is rich in its data types. The variety of data types available allows the programmer to
select the type appropriate to the needs of the applications.

There are two data types available in Java:


 Primitive Data Types
 Reference/Object Data Types

1. Primitive Data Types:

There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a keyword. Let us now look into detail about the eight primitive data types.

(i) byte:

 Byte data type is an 8-bit signed two's complement integer.


 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is
four times smaller than an int.
 Example: byte a = 100 , byte b = -50

(ii) short:

 Short data type is a 16-bit signed two's complement integer.


 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times smaller
than an int
 Default value is 0.
 Example: short s = 10000, short r = -20000

(iii) int:

 Int data type is a 32-bit signed two's complement integer.


 Minimum value is - 2,147,483,648.(-2^31)
 Maximum value is 2,147,483,647(inclusive).(2^31 -1)
75
 Int is generally used as the default data type for integral values unless there is a concern about
memory.
 The default value is 0.
 Example: int a = 100000, int b = -200000

(iv) long:

 Long data type is a 64-bit signed two's complement integer.


 Minimum value is -9,223,372,036,854,775,808.(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 This type is used when a wider range than int is needed.
 Default value is 0L.
 Example: long a = 100000L, long b = -200000L

(v) float:

 Float data type is a single-precision 32-bit IEEE 754 floating point.


 Float is mainly used to save memory in large arrays of floating point numbers.
 Default value is 0.0f.
 Float data type is never used for precise values such as currency.
 Example: float f1 = 234.5f

(vi) double:

 double data type is a double-precision 64-bit IEEE 754 floating point.


 This data type is generally used as the default data type for decimal values, generally the default
choice.
 Double data type should never be used for precise values such as currency.
 Default value is 0.0d.
 Example: double d1 = 123.4

(vii) boolean:

 boolean data type represents one bit of information.


 There are only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 Default value is false.
 Example: boolean one = true

(viii) char:

 char data type is a single 16-bit Unicode character.


 Minimum value is '\u0000' (or 0).
 Maximum value is '\uffff' (or 65,535 inclusive).
 Char data type is used to store any character.
 Example: char letterA ='A'

2. Reference Data Types:

76
 Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be changed. For
example, Employee, Puppy etc.
 Class objects, and various type of array variables come under reference data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any object of the declared type or any compatible
type.
 Example: Animal animal = new Animal("giraffe");

Binding

Connecting a method call to a method body is called binding.


Two types of binding are
 Static Binding - Compile time polymorphism
 Dynamic Binding – Runtime polymorphism

Static Binding
 When type of the object is determined at compile time(By the complier) .
 If there is any private, final or static method in a class, it is static binding.
 Static binding example would be overloading (Methods are invoked based on reference type of
a class)

Dynamic Binding
 When type of the object is determined at runtime.
 Dynamic binding example would be overriding (Methods are invoked based on object of a
class)

Java Packages

Packages are java‘s way of grouping a variety of classes and or interfaces together. The grouping is
usually done according to functionality. In fact, packages act as ―containers for classes.

Advantages of Packages
 The classes contained in the packages of other programs can be easily reused.
 Package provides access protection.
 Packages provide a way to ―hide classes thus preventing other programs or package from
accessing classes that are meant for internal use only.

77
Types of Packages
Java packages are therefore classified into two types.
1. Pre – defined packages (Java API Packages)
2. User – defined packages

1.Java API Packages

Package Name Contents


java.lang Language support classes. These are classes that java compiler itself uses
and therefore they are automatically imported. They include classes for
primitive types, strings, math functions, threads and exceptions
java.util Language utility classes such as vectors, hash tables, random numbers,
date, etc.
java.io Input / Output support classes. They provide facilities for the input and
output of data.
java.awt Set of classes for implementing graphical user interface. They include
classes for windows, buttons, lists, menus and so on.
java.net Classes for networking. They include classes for communicating with local
computers as well as with internet servers.
java.applet Classes for creating and implementing applets.

2. User defined packages


Creating our own package involves the following steps:
1. Declare the package at the beginning of a file using the form
package package_name;
2. Define the class that is to be put in the package and declare it public
3. Create a subdirectory under the directory where the main source files are
78
stored.
4. Store the listing as the classname.java file in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.
6. The subdirectory name must match the package name exactly.

Note:
Java also supports the concept of package hierarchy. This done by specifying multiple names in a
package statement, separated by dots.

Example:
package firstPackage.secondpackage;

Program
//Program for creating a package package1
package package1;
public class ClassA
{
public void displayA()
{
System.out.println("Class A");
}
}

//Program for import the package


import package1.ClassA;
class PackageTest1
{
public static void main(String args[])
{
ClassA objectA = new ClassA() objectA.displayA();
}
}

Output
Z:\javac -d . ClassA.java
Z:\javac PackageTest1.java
Z:\java PackageTest1
Class A

Object and Classes

Java is an object oriented language, complete java language is build on classes and object. Java is also
known as a strong Object oriented programming language(oops).OOPS is a programming approach
which provides solution to problems with the help of algorithms based on real world. It uses real
world approach to solve a problem. So object oriented technique offers better and easy way to write
program then procedural programming model such as C, ALGOL, PASCAL.

79
Class
In Java everything is encapsulated under classes. Class is the core of Java language. Class can be
defined as a template/ blueprint that describe the behaviors /states of a particular entity. A class
defines new data type. Once defined this new type can be used to create object of that type. Object is an
instance of class. You may also call it as physical existence of a logical template class.

A class is declared using class keyword. A class contain both data and code that operate on that data.
The data or variables defined within a class are called instance variables and the code that operates on
this data is known as methods.

Rules for Java Class


 A class can have only public or default(no modifier) access specifier.
 It can be either abstract, final or concrete (normal class).
 It must have the class keyword, and class must be followed by a legal identifier.
 It may optionally extend one parent class. By default, it will extend java.lang.Object.
 It may optionally implement any number of comma-separated interfaces.
 The class's variables and methods are declared within a set of curly braces {}.
 Each .java source file may contain only one public class. A source file may contain any number
of default visible classes.
 Finally, the source file name must match the public class name and it must have a .java suffix.

A simple class example


Suppose, Student is a class and student's name, roll number, age will be its property. Lets see this in
Java syntax.
class Student.
{
String name;
int rollno;
int age;
}

When a reference is made to a particular student with its property then it becomes an object, physical
existence of Student class.
Student std=new Student();
80
Program
import java.io.*;
class Rect
{
int height;
int width;
public void input()
{
height=10;
width=20;
}
public void area()
{
int result=height*width;
System.out.println("The area is: " +result);
}
}
class RectClass
{
public static void main(String args[])
{
Rect obj = new Rect(); //create an object
obj.input();
obj.area();
}
}

Output
Z:\javac RectClass.java
Z:\java RectClass
The area is 200

Constructor in Java

Constructor in java is a special type of method that is used to initialize the object. Java constructor is
invoked at the time of object creation. It constructs the values i.e. provides data for the object that is
why it is known as constructor.

Rules for creating java constructor


1. Constructor name must be same as its class name
2. Constructor must have no explicit return type

81
(i) Java Default Constructor
A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


<class_name>()
{
}
Example of default constructor
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}

Output:
Bike is created

(ii) Java parameterized constructor


 A constructor that have parameters is known as parameterized constructor.
 Parameterized constructor is used to provide different values to the distinct objects.

Example of parameterized constructor


class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
82
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}

Output
111 Karan
222 Aryan

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of constructors
that differ in parameter lists.The compiler differentiates these constructors by taking into account the
number of parameters in the list and their type.

Example of Constructor Overloading


class Student5
{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
83
}
}

Output
111 Karan 0
222 Aryan 25

Difference between constructor and method in java

Java Constructor Java Method


Constructor is used to initialize the state of an
Method is used to expose behaviour of an object.
object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default constructor if
Method is not provided by compiler in any case.
you don't have any constructor.
Method name may or may not be same as class
Constructor name must be same as the class name.
name.

Java - Arrays

Array is a collection of similar type of elements that have contiguous memory location.Java array is an
object the contains elements of similar data type. It is a data structure where we store similar
elements. We can store only fixed set of elements in a java array.Array in java is index based, first
element of the array is stored at 0 index.

Advantage of Java Array


 Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
 Random access: We can get any data located at any index position.

Disadvantage of Java Array


 Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in java.
Types of Array in java
 Single Dimensional Array
 Multidimensional Array

84
1. Single Dimensional Array
Syntax to Declare an Array in java
dataType[] arr; (or) dataType []arr; (or) dataType arr[];

Instantiation of an Array in java


arrayRefVar=new datatype[size];

Declaration, Instantiation and Initialization of Java Array

int a[]={33,3,4,5};//declaration, instantiation and initialization

Program
//Program for sorting set of numbers using one dimensional array
import java.util.Scanner;
class Sorting
{
public static void main(String [] args)
{
int i,j,n,swap;
Scanner in = new Scanner(System.in);
System.out.println("Input number of integers to sort");
n = in.nextInt();
int array[] = new int[n];
System.out.println("Enter " + n + " integers");
for(i=0;i<n;i++)
array[i] = in.nextInt();
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(array[i] > array[j])
{
swap=array[i];
array[i]=array[j];
array[j]=swap;
}
}
}
System.out.println("Sorted list of numbers");
for(i=0;i<n;i++)
System.out.println(array[i]);
}
}

Output
Z:\>javac Sorting.java
Z:\>java Sorting
85
Input number of integers to sort
5

Enter 5 integers
11
33
2
55
4

Sorted list of numbers


2
4
11
33
55

2. Multidimensional array
Syntax to Declare Multidimensional Array in java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java


int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in java


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Program
//Java program for Matrix addition using two dimensional array
class Testarray5
{
public static void main(String args[])
{
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
int c[][]=new int[2][3];
86
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println();
}

}
}

Output:
268
6 8 10

Strings

Strings, which are widely used in Java programming, are a sequence of characters. In the Java
programming language, strings are objects.The Java platform provides the String class to create and
manipulate strings. The java.lang.String class provides a lot of methods to work on string. By the help
of these methods, we can perform operations on string such as trimming, concatenating, converting,
comparing, replacing strings etc.

Creating a String

There are two ways to create a String in Java


1. String literal
2. Using new keyword

(i) String literal


In java, Strings can be created like this: Assigning a String literal to a String instance:
String str1 ="Welcome";
String str2 ="Welcome";

(ii) Using New Keyword


String str1 =newString("Welcome");
String str2 =newString("Welcome");
In this case compiler would create two different object in memory having the same text.

String Methods
87
1. toUpperCase() and toLowerCase()
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.

Example
String s="Sachin";
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s);

Output
SACHIN
sachin
Sachin

2. trim()
The string trim() method eliminates white spaces before and after string.

Example
String s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin

Output
Sachin
Sachin

3. startsWith() and endsWith()


startsWith( ) method determines whether a given String begins with a specified string. Conversely,
endsWith( ) determines whether the String in question ends with a specified string. They have the
following general forms:
boolean startsWith(String str)
boolean endsWith(String str)
Here, str is the String being tested. If the string matches, true is returned. Otherwise, false is returned.

Example
String s="Sachin";
System.out.println(s.startsWith("Sa"));
System.out.println(s.endsWith("n"));

Output
true
true

4. charAt()
The string charAt() method returns a character at specified index.

88
Example
String s="Sachin";
System.out.println(s.charAt(0));
System.out.println(s.charAt(3));

Output
S
h

5. length() method
The string length() method returns length of the string.

Example
String s="Sachin";
System.out.println(s.length());

Output
6

6. replace()
The string replace() method replaces all occurrence of first sequence of character with second
sequence of character.

Example
String str = "Change me";
System.out.println(str.replace('m','M'));

Output
Change Me

7. substring()
substring() method returns a part of the string. substring() method has two forms,
public String substring(int begin);
public String substring(int begin, int end);
The first argument represents the starting point of the subtring. If the substring() method is called
with only one argument, the subtring returned, will contain characters from specified starting point to
the end of original string.
But, if the call to substring() method has two arguments, the second argument specify the end point of
substring.

Example
String str = "0123456789";
System.out.println(str.substring(4));
Output : 456789
System.out.println(str.substring(4,7));
Output : 456

89
8. equals() and equalsIgnoreCase()
To compare two strings for equality, use equals()

Syntax:
boolean equals(String str)
Here, str is the String object being compared with the invoking String object. It returns true if the
strings contain the same characters in the same order, and false otherwise. The comparison is case -
sensitive.

Example
String first="HELLO",second="hello";
boolean check=first.equals(second);
if(!check)
System.out.println("Strings are not equal");
else
System.out.println("Strings are equal”);

Output
Strings are not equal

9. equalsIgnoreCase()
To perform a comparison that ignores case differences, call equalsIgnoreCase(). When it compares two
string, it considers A - Z to be the same as a - z.

Syntax:
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object. It, too, returns true if the
strings contain the same characters in the same order, and false otherwise.

Example
String first="HELLO",second="hello";
boolean check=first.equalsIgnoreCase(second);
if(!check)
System.out.println("Strings are not equal");
else
System.out.println("Strings are equal”);

Output
Strings are equal

10. Concatenation

This method concatenates the string str at the end of the current string. For e.g. s1.concat("Hello");
would concatenate the String “Hello” at the end of the String s1.

Example
String first="HELLO",second="WELCOME";
System.out.println(first.concat(second));

90
Output
HELLOWELCOME

University Questions
Write a java program to perform all string operations using the String class.
import java.util.*;
class Stringoperation
{
public static void main(String[] args)
{
String first="",second="";
Scanner sc=new Scanner(System.in);
System.out.println("String Operation");
System.out.println();
System.out.print("Enter the first Sting: ");
first=sc.nextLine();
System.out.print("Enter the second Sting: ");
second=sc.nextLine();
System.out.println("The strings are: "+first+" , "+second);
System.out.println("The length of the first string is :"+first.length());
System.out.println("The length of the second string is :"+second.length());
System.out.println("The concatenation of first & second is :"+first.concat(second));
System.out.println("The first character of " +first+" is: "+first.charAt(0));
System.out.println("The uppercase of " +first+" is: "+first.toUpperCase());
System.out.println("The lowercase of " +first+" is: "+first.toLowerCase());
StringBuffer str=new StringBuffer(first);
System.out.println("The reverse of " +first+" is: "+str.reverse());
boolean check=first.equals(second);
if(!check)
System.out.println(first + " and " + second + " are not same.");
else
System.out.println(first + " and " + second + " are same.");
}
}

Output
Z:\>javac Stringperation.java
Z:\>java Stringoperation

String Operation
Enter the first Sting: hello
Enter the second Sting: welcome
The strings are: hello , welcome
The length of the first string is :5
The length of the second string is :7
The concatenation of first & second is :hellowelcome
91
The first character of hello is: h
The uppercase of hello is: HELLO
The lowercase of hello is: hello
The reverse of hello is: olleh
hello and welcome are not same.

Unit 5

Inheritance

Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance the information is made manageable in a hierarchical
order.

The class which inherits the properties of other is known as subclass (derived class, child class) and
the class whose properties are inherited is known as superclass (base class, parent class).

Advantages of Inheritance
1. Reusability of the code.
2. To Increase the reliability of the code.
3. To add some enhancements to the base class.

extends Keyword
extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends
keyword.

Example
class Sample
{
.....
.....
}

class Sub extends Sample


{
.....
.....

92
}

I. Types of Inheritance
1. Single Inheritance (Only one Super Class and One Only Sub Class)
2. Multiple Inheritance (Many Super Class and Only one Sub Class)
3. Multilevel Inheritance (Derived from a Derived Class)
4. Hierarchical Inheritance (One Super Class, Many Subclasses)

1. Single Inheritance
Single inheritance is easy to understand. When a class extends another one class only then we call it
a single inheritance. The below flow diagram shows that class B extends only one class which is A.
Here A is a parent class of B and B would be a child class of A.

Program
import.java.io.*;
class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
}
class Single
{
public static void main(String args[])
{
B obj = new B();
obj.methodA();
obj.methodB();
}
}
Output
Z:\javac Single.java
Z:\java Single

93
Base class method
Child class method

2. Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base
class. The inheritance we learnt earlier had the concept of one base class or parent. The problem with
“multiple inheritance” is that the derived class will have to manage the dependency on two base
classes. It can be implemented with the help of Interfaces.

3. Multilevel Inheritance

Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived
class, thereby making this derived class the base class for the new class.
Program
import.java.io.*;
class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
class Z extends Y
{
public void methodZ()
{
94
System.out.println("class Z method");
}
}
class Multilevel
{
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}

Output
Z:\javac Multilevel.java
Z:\java Multilevel

Class X method
Class Y method
Class Z method

4. Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example class B,C and
D inherits the same class A. A is parent class (or base class) of B,C & D.

Program
import.java.io.*;
class A
{
protected int a;
A()
{
a = 10;
}
}
class B extends A

{
void area()

95
{
System.out.println("Area is:" + (a * a));
}
}
class C extends A
{
void volume()
{
System.out.println("Volume is:" + (a * a* a));
}
}
class Hierarchical
{
public static void main(String [] args)
{
B hr =new B();
C br = new C();
hr.Area();
br.Volume();
}
}
Output
Z:\>javac Hierarchical.java
Z:\>java Hierarchical

Area is: 100


Volume is: 1000

II. Inheritance with super keyword


In Java, super keyword is used to refer to immediate parent class of a class. In other words super
keyword is used by a subclass whenever it need to refer to its immediate super class.

The purpose of the ‘super’ keyword:


1. Using super to call Superclass Constructors
2. Using super to call Superclass Methods

1.Using super to Call Superclass Constructor


A Subclass can call a constructor method defined by its superclass by use of the following form of
super:
super (parameter – list) ;

Here, parameter – list specifies any parameter needed by the constructor in the superclass, super()
must always be the first statement executed inside a subclass constructor.

Restriction of the Subclass constructor


1. super may only be used within a subclass constructor method.
2. The call to superclass constructor must appear as the first statement within the subclass constructor

96
3. The parameters in the subclass must match the order and type of the instance variable declared in
the superclass.

1. Using super to call Superclass Constructors


Program
import.java.io.*;
class A
{
protected int a, b, c;
A(int x, int y)
{
this.a = x;
this.b = y;
}
void Area()
{
System.out.println("Area is:" + (a* b));
}
}
class B extends A
{
int c;
B(int a, int b, int c)
{
super(a,b);
this.c = c;
}
void Volume()
{
System.out.println("Volume is:" + (a * b * c));
}
}
class SuperClass
{
public static void main(String [] args)
{
B hr =new B(10,20,30);
hr.Area();
hr.Volume();
}
}

Output
Z:\javac SuperClass.java
Z:\java SuperClass

Area is:200
Volume is:6000
97
2. Using super to Call Superclass Method
Program
import.java.io.*;
class A
{
void FuncA()
{
System.out.println("A Class");
}
}
class B extends A
{
void FuncB()
{
System.out.println("B Class");
}
}
class C extends B
{
void FuncC()
{
super.FuncA();
super.FuncB();
System.out.println("Class C");
}
}
class Superb
{
public static void main(String [] args)
{
C br = new C();
br.Func();
}
}

Output
Z:\javac Superb.java
Z:\java Superb
Class A
Class B
Class C

III. Inheritance with Method Overriding


The benefit of overriding is: ability to define a behavior that's specific to the subclass type which
means a subclass can implement a parent class method based on its requirement. In object-oriented
terms, overriding means to override the functionality of an existing method.

98
Rules for method overriding:
 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
 The access level cannot be more restrictive than the overridden method's access level.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared public or
protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the overridden
method throws exceptions or not.
 Constructors cannot be overridden.

Program
import java.io.*;
class A
{
void funcA()
{
System.out.println("Base Class");
}
}
class B extends A
{
void funcA()
{
System.out.println("Derived Class");
}
}
class Sample
{
public static void main(String [] args)
{
B br = new B();
br.funcA();
}
}

Output
E:\>javac Sample.java
E:\>java Sample
Derived Class

99
Super Keyword in Method Overriding
When invoking a superclass version of an overridden method the super keyword is used.

Program
import java.io.*;
class A
{
void funcA()
{
System.out.println("Base Class");
}
}
class B extends A
{
void funcA()
{
System.out.println("Derived Class");
super.funcA();
}
}
class Sample
{
public static void main(String [] args)
{
B br = new B();
br.funcA();
}
}

Output
E:\>javac Sample.java
E:\>java Sample
Derived Class
Base Class

IV. Inheritance with Abstract Class


An abstract class is a class that is declared abstract—it may or may not include abstract methods.
Abstract classes cannot be instantiated, but they can be subclassed. An abstract method is a method
that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, then the class itself must be declared abstract, as in:
public abstract class GraphicObject
{
// declare fields
// declare nonabstract methods
abstract void draw();
100
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the
abstract methods in its parent class. However, if it does not, then the subclass must also be declared
abstract.

Program
abstract class A
{
abstract void callme( ); // Abstract Method
void callmetoo( ) // Concrete Method
{
System.out.println("This is a Concrete method");
}
}
class B extends A
{
void callme( ) //Redefined for the Abstract Method
{
System.out.println("B's Implementation of Callme");
}
}
class AbsMainRoom
{
public static void main(String [] args)
{
B b = new B( );
b.callme( );
b.callmetoo( );
}
}

Output
Z:\>javac AbsMainRoom.java
Z:\>java AbsMainRoom

B's Implementation of Callme


This is a Concrete method

V. Inheritance with final Keyword


The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only. We will have
detailed learning of these. Let's first learn the basics of final keyword.
101
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).

Program
class Bike9
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}
Output:
Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.

Program
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}

Output:
Compile Time Error

102
3) Java final class
If you make any class as final, you cannot extend it.

Program
final class Bike
{
}
class Honda1 extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda();
honda.run();
}
}

Output:
Compile Time Error

Java Interfaces

An interface in java is a blueprint of a class. It has static constants and abstract methods only. The
interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the
java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java.
It cannot be instantiated just like abstract class.

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


 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface matching
the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.

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


 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an interface must
be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

103
Properties
 An interface is implicitly abstract. You do not need to use the abstract keyword while declaring
an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
 Methods in an interface are implicitly public.

Understanding relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.

Program for Interfaces


interface Area
{
final static float pi = 3.14F;
float compute (float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return (x * y);
}
}
class Circle implements Area
{
public float compute(float x, float y)
{
return (pi * x * x);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle ();
Circle cir = new Circle();
Area area;
area = rect;
System.out.println("Area of Rectangle = " + area.compute(10,20));
area = cir;
System.out.println("Area of Circle = " + area.compute(10,0));
104
}
}
Output
Z:\>javac InterfaceTest.java
Z:\>java InterfaceTest
Area of Rectangle = 200.0
Area of Circle = 314.0

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.

Program
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A implements Printable, Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
}
class MultiInterface
{
public static void main(String args[])
{
A obj = new A();
obj.print();
obj.show();
105
}
}

Output
Z:\javac MultiInterface.java
Z:\java MultiInterface

Hello
Welcome
Interface inheritance
A class implements interface but one interface extends another interface .

Program
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class Testinterface2 implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
}
class InterfaceInherit
{
public static void main(String args[])
{
Testinterface2 obj = new Testinterface2();
obj.print();
obj.show();
}
}
Output
Z:\javac InterfaceInherit.java
Z:\java InterfaceInherit

Hello
Welcome

106
Types of Interfaces

Abstract Class Vs Interface

Abstract Classes Interfaces


abstract class can extend only one class or one interface can extend any number of interfaces at a
abstract class at a time time
abstract class can extend from a class or from an
interface can extend only from an interface
abstract class
abstract class can have both abstract and
interface can have only abstract methods
concrete methods
A class can extend only one abstract class A class can implement any number of interfaces
In abstract class keyword ‘abstract’ is mandatory In an interface keyword ‘abstract’ is optional to
to declare a method as an abstract declare a method as an abstract
abstract class can have protected , public and Interface can have only public abstract methods
107
public abstract methods i.e. by default
abstract class can have static, final or static interface can have only static final (constant)
final variable with any access specifier variable i.e. by default

Exception handling

An exception (or exceptional event) is a problem that arises during the execution of a program. When
an Exception occurs the normal flow of the program is disrupted and the program/Application
terminates abnormally, which is not recommended, therefore these exceptions are to be handled. An
exception can occur for many different reasons, below given are some scenarios where exception
occurs.
 A user has entered invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run out of
memory.

Types of Exception
1) Checked Exception
The classes that extend Throwable class except Runtime Exception and Error are known as checked
exceptions.

Example
Exception Description
ClassNotFoundException Class not found.
Attempt to clone an object that does not implement the
CloneNotSupportedException
Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.

2) Unchecked Exception
The classes that extend Runtime Exception are known as unchecked exceptions.

Example
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
Illegal monitor operation, such as waiting on an
IllegalMonitorStateException
unlocked thread.
108
IllegalStateException Environment or application is in incorrect state.
Requested operation not compatible with current thread
IllegalThreadStateException
state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.

Exception Handling Keywords


There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw
5. throws

1. Try block
The try block contains a block of program statements within which an exception might occur. A try
block is always followed by a catch block, which handles the exception that occurs in associated try
block. A try block must followed by a Catch block or Finally block or both.

Syntax of try block


try
{
//statements that may cause an exception
}

2. Catch block
A catch block must be associated with a try block. The corresponding catch block executes if an
exception of a particular type occurs within the try block. For example if an arithmetic exception
occurs in try block then the statements enclosed in catch block for arithmetic exception executes.
Syntax of catch in java
catch (exception-type object)
{
//error handling code
}

3. Finally block
 A finally statement must be associated with a try statement. It identifies a block of
statements that needs to be executed regardless of whether or not an exception
occurs within the try block.
 After all other try-catch processing is complete, the code inside the finally block
executes. It is not mandatory to include a finally block at all, but if you do, it will run
109
regardless of whether an exception was thrown and handled by the try and catch parts
of the block.
 In normal execution the finally block is executed after try block. When any exception
occurs first the catch block is executed and then finally block is executed.
 An exception in the finally block, exactly behaves like any other exception.
 The code present in the finally block executes even if the try or catch block contains
control transfer statements like return, break or continue.

Syntax of Finally block


finally
{
//statements to be executed
}

4. throw keyword
The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to
throw custom exception.

Syntax of throw
throw exception;

5. Throws clause
 The throws keyword is used in method declaration, in order to explicitly specify the exceptions
that a particular method might throw. When a method declaration has one or more exceptions
defined using throws clause then the method-call must handle all the defined exceptions.
 When defining a method you must include a throws clause to declare those exceptions that
might be thrown but doesn’t get caught in the method.
 If a method is using throws clause along with few exceptions then this implicitly tells other
methods.

Syntax of Throws in java:


void MethodName() throws ExceptionName
{
Statement1
...
...
}

Throw vs Throws in java

Throw Throws
throw keyword is used to throw an Throws clause in used to declare an
exception explicitly exception
throw is followed by an instance variable throws is followed by exception class names
The keyword throw is used inside method throws clause is used in method
body to invoke an exception declaration (signature)

Hierarchy of Java Exception classes


110
Types of Exception handling
o Pre-Defined Exception
o User Defined Exception

1. Pre-Defined Exception
Program
class Exceptionhandle
{
public static void main(String args[])
{
int i,j,k;
i = 10;
j = 0;
try
{
k = i / j;
System.out.println("The Division of the K Value is: " + k);
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero");
111
}
}
}
Output:
Divided by zero

2. User defined exceptions


User defined exceptions in java are also known as Custom exceptions. Most of the times when we
are developing an application in java, we often feel a need to create and throw our own exceptions.
These exceptions are known as User defined or Custom exceptions.

Program
import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class Exce
{
public static void main(String args[])
{
int x = 5, y = 1000;
try
{
float z = (float) x / (float) y;
if (z < 0.01)
{
throw new MyException("Number is too small");
}
}
catch(MyException e)
{
System.out.println("Caught my exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I am always here");
}
}
}
Output
Z:\>javac Exce.java
Z:\>java Exce
Caught my exception
112
Number is too small
I am always here

Multiple catch blocks in Java


1. A try block can have any number of catch blocks.
2. A catch block that is written for catching the class Exception can catch all other exceptions
Syntax:
catch(Exception e)
{
//This catch block catches all the exceptions
}
3. If multiple catch blocks are present in a program then the above mentioned catch block
should be placed at the last as per the exception handling best practices.
4. If the try block is not throwing any exception, the catch block will be completely ignored and
the program continues.
5. If the try block throws an exception, the appropriate catch block (if one exists) will catch it
–catch(ArithmeticException e) is a catch block that can catch ArithmeticException
–catch(NullPointerException e) is a catch block that can catch NullPointerException
6. All the statements in the catch block will be executed and then the program continues.

Program
class Example
{
public static void main(String args[])
{
try
{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e)
{
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e)
{
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}

Output
113
Z:\javac Example.java
Z:\java Example
Warning: ArithmeticException
Out of try-catch block...

Java Threads

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It
shares a common memory area. in a single thread.

1. Life cycle of a Thread


The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
 New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
 Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
 Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task. A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
 Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
 Terminated ( Dead ): A runnable thread enters the terminated state when it completes its task
or otherwise terminates.

Thread Methods
 getName(): It is used for Obtaining a thread’s name
 getPriority(): Obtain a thread’s priority
 isAlive(): Determine if a thread is still running
 join(): Wait for a thread to terminate
 run(): Entry point for the thread
 sleep(): suspend a thread for a period of time
 start(): start a thread by calling its run() method

2. Thread creation in Java


Thread implementation in java can be achieved in two ways:
1. Extending the java.lang.Thread class
114
2. Implementing the java.lang.Runnable Interface
Note: The Thread and Runnable are available in the java.lang.* package

1) By extending thread class


 The class should extend Java Thread class.
 The class should override the run() method.
 The functionality that is expected by the Thread to be executed is written in the run() method.

void start():
Creates a new thread and makes it runnable.
void run():
The new thread begins its life inside this method.

Program
class MyThread extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
}
public class MThread
{
public static void main(String[] args)
{
MyThread obj = new MyThread();
obj.start();
}
}

Output
Z:\>javac MThread.java
Z:\>java MThread

thread is running...

2) By Implementing Runnable interface


 The class should implement the Runnable interface
 The class should implement the run() method in the Runnable interface
 The functionality that is expected by the Thread to be executed is put in the run() method

Program
class MyThread implements Runnable
{
public void run()
{
System.out.println("thread is running..");
}
115
}
public class MThread
{
public static void main(String[] args)
{
Thread t = new Thread(new MyThread());
t.start();
}
}

Output
Z:\>javac MThread.java
Z:\>java MThread

thread is running...

3. Multithreading
Multithreading in java is a process of executing multiple threads simultaneously. Thread is
basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading,
both are used to achieve multitasking.

Advantage of Java Multithreading


1. It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
2. You can perform many operations together so it saves time.
3. Threads are independent so it doesn't affect other threads if exception occur

(i) Multithreading by extending Thread Class


class MultiThread extends Thread
{
String msg;
MultiThread(String str)
{
msg = str;
start();
}
public void run()
{
for(int i=1;i<=4;i++)
{
System.out.println(msg);
}
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
116
System.out.println("Exception in Thread");
}
}
}
public class MThread
{
public static void main(String arg[])
{
MultiThread t1 = new MultiThread("First");
MultiThread t2 = new MultiThread("Second");
MultiThread t3 = new MultiThread("Third");
}
}

Output
Z:\>javac MThread.java

Z:\>java MThread
First
First
First
First
Second
Second
Second
Second
Third
Third
Third
Third

(ii) Multithreading by implementing Runnable Interface


class MultiThread implements Runnable
{
String str,msg;
Thread t;
MultiThread(String str)
{
msg = str;
t=new Thread(this,str);
t.start();
}
public void run()
{
for(int i=1;i<=4;i++)
{
System.out.println(msg);
}
117
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Exception in Thread");
}
}
}
public class MThread
{
public static void main(String arg[])
{
MultiThread t1 = new MultiThread("First");
MultiThread t2 = new MultiThread("Second");
MultiThread t3 = new MultiThread("Third");
}
}

Output
Z:\>javac MThread.java

Z:\>java MThread
First
First
First
First
Third
Third
Third
Third
Second
Second
Second
Second

Java I/O Streams

The stream in the java.io package supports many data such as primitives, Object, localized characters,
etc. All these streams represent an input source and an output destination. An I/O Stream represents
an input source or an output destination. A stream can represent many different kinds of sources and
destinations, including disk files, devices, other programs, and memory arrays.

Stream
Streams support many different kinds of data, including simple bytes, primitive data types, localized
characters, and objects. Some streams simply pass on data; others manipulate and transform the data
in useful ways. No matter how they work internally, all streams present the same simple model to
118
programs that use them: A stream is a sequence of data. A program uses an input stream to read data
from a source, one item at a time:

There are two kinds of Streams


 InPutStream: The InputStream is used to read data from a source.
 OutPutStream: the OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers
very basic functionality related to streams and I/O.

1. Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes
related to byte streams but the most frequently used classes are FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an input file
into an output file:

Program
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}

119
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}

input.txt
This is test for copy file.

$javac CopyFile.java
$java CopyFile

Output
As a next step, compile above program and execute it, which will result in creating output.txt file with
the same content as we have in input.txt.

2. Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character
streams are used to perform input and output for 16-bit unicode. Though there are many classes
related to character streams but the most frequently used classes are FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here
major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.

Program
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try
{
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
120
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
input.txt
This is test for copy file.
Output
$javac CopyFile.java
$java CopyFile

As a next step, compile above program and execute it, which will result in creating output.txt file with
the same content as we have in input.txt.

3. Standard Streams
All the programming languages provide support for standard I/O where user's program can take input
from a keyboard and then produce output on the computer screen. Java provides following three
standard streams
 Standard Input: This is used to feed the data to user's program and usually a keyboard is used
as standard input stream and represented as System.in.
 Standard Output: This is used to output the data produced by the user's program and usually a
computer screen is used to standard output stream and represented as System.out.
 Standard Error: This is used to output the error data produced by the user's program and
usually a computer screen is used to standard error stream and represented as System.err.

Program
import java.io.*;
public class ReadConsole
{
public static void main(String args[]) throws IOException
{
InputStreamReader cin = null;
try
{
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do
{
121
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}
finally
{
if (cin != null)
{
cin.close();
}
}
}
}
Output
$javac ReadConsole.java
$java ReadConsole

Enter characters, 'q' to quit.


1
1
e
e
q
q

4. Reading and Writing Files:


As described earlier, A stream can be defined as a sequence of data. The InputStream is used to read
data from a source and the OutputStream is used for writing data to a destination. Here is a hierarchy
of classes to deal with Input and Output streams.

(i) FileInputStream:
122
This stream is used for reading data from the files. Objects can be created using the keyword
new and there are several types of constructors available. Following constructor takes a file name as a
string to create an input stream object to read the file.:
InputStream f = new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows:
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);

Methods with Description


1. public void close() throws IOException{} - This method closes the file output stream.
Releases any system resources associated with the file. Throws an IOException.
2. protected void finalize()throws IOException {} - This method cleans up the connection to
the file. Ensures that the close method of this file output stream is called when there are no
more references to this stream. Throws an IOException.
3. public int read(int r)throws IOException{} - This method reads the specified byte of data
from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if
it's end of file.
4. public int read(byte[] r) throws IOException{} - This method reads r.length bytes from the
input stream into an array. Returns the total number of bytes read. If end of file -1 will be
returned.
5. public int available() throws IOException{} - Gives the number of bytes that can be read
from this file input stream. Returns an int.

(ii) FileOutputStream:
FileOutputStream is used to create a file and write data into it. The stream would create a file, if it
doesn't already exist, before opening it for output. Here are two constructors which can be used to
create a FileOutputStream object. Following constructor takes a file name as a string to create an input
stream object to write the file:
OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object to write the file. First, we
create a file object using File() method as follows:
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);

Methods with Description


1. public void close() throws IOException{} - This method closes the file output stream.
Releases any system resources associated with the file. Throws an IOException
2. protected void finalize()throws IOException {} - This method cleans up the connection to
the file. Ensures that the close method of this file output stream is called when there are no
more references to this stream. Throws an IOException.
3. public void write(int w)throws IOException{} - This methods writes the specified byte to the
output stream.
4. public void write(byte[] w) - Writes w.length bytes from the mentioned byte array to the
123
OutputStream.

University Questions

1. Write a java program to create two single dimensional arrays, initialize them and add them;
store the result in another array.
class Array
{
public static void main(String args[])
{
int a[] = {2,3,1,4,5};
int b[] = {4,5,3,2,7};
int c[] = new int[5];
for(int i=0; i<a.length; i++)
c[i] = a[i] + b[i];
System.out.println(“The Result Array:”);
for (int i=0;i<c.length;i++)
System.out.print(c[i]+”\t”);
}
}
Output:
The Result Array:
6 8 4 6 12

2. Write a menu-based java program that can calculate the area of a triangle, circle or square,
based on the user’s choice.
import java.io.*;
class area
{
void findarea(float a)
{
System.out.println( "\n Area of Square is :" + a*a);
}
void findarea(int a)
{
System.out.println( "\n Area of circle is :" + 3.14 * a);
}
void findarea(int a, int b, int c)
{
double temp = (a + b + c);
double s= temp/2;
double triarea = Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println( "\n Area of triangle is : "+ triarea);
}
public static void main(String args[]) throws IOException
{
area d = new area();
124
BufferedReader Br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("\n Find area of \n 1 . Square \n 2 . Triangle \n 3 .
Circle \n\nSelect a choice : ");
int choice =Integer.parseInt(Br.readLine());
switch(choice)
{
case 1:
d.findarea(10.5f);
break;
case 2:
d.findarea(10,15,7);
break;
case 3:
d.findarea(6);
break;
default:
System.out.println("Invalid choice");
}
}
}
Output:
Find area of
1 . Square
2 . Triangle
3 . Circle
Select a choice : 3
Area of circle is :18.84

3. 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.
class Complex
{
double real, imag;
Complex()
{
this( 0.0, 0.0 );
}
Complex( double r, double i )
{
real = r;
imag = i;
}
Complex add( Complex right )
{
Complex Temp = new Complex();
Temp.real = real + right.real;
Temp.imag = imag + right.imag;
125
return Temp;
}
public Complex subtract( Complex right )
{
Complex Temp = new Complex();
Temp.real = real - right.real;
Temp.imag = imag - right.imag;
return Temp;
}
public String toString()
{
return "(" + real + ", " + imag + ")";
}
}
class ComplexTest
{
public static void main( String args[] )
{
Complex a, b;
a = new Complex( 9.9, 7.7 );
b = new Complex( 1.2, 3.1 );
System.out.println("The Result "+ a.add( b) );
System.out.println("The Result "+ a.subtract( b));
}
}
Output:
The Result (11.1, 10.8)
The Result (8.7, 4.6)

4. Write a java program to find the maximum number of the given array.
import java.io.*;
class maximum
{
public static void main(String args[])
{
int a[] = {5,3,6,2,4,61};
int max=0;
for(int i=0;i<a.length;i++)
{
if(a[i]>max)
max=a[i];
}
System.out.println("The Max Value in the Given Array : " +max);
}
}
Output:
The Max Value in the Given Array : 61

126
Two Mark Questions
Unit-I
1. Compare Procedural Oriented Languages and Object Oriented Languages.

Procedure Oriented Programming Object Oriented Programming


In POP, program is divided into small parts In OOP, program is divided into parts called
called functions. objects.
In POP, Importance is not given to data but to In OOP, Importance is given to the data rather
functions as well as sequence of actions to be than procedures or functions because it
done. works as a real world.
POP follows Top Down approach. OOP follows Bottom Up approach.
OOP has access specifiers named Public,
POP does not have any access specifier.
Private, Protected, etc.
In POP, Data can move freely from function to In OOP, objects can move and communicate
function in the system. with each other through member functions.
To add new data and function in POP is not so OOP provides an easy way to add new data
easy. and function.
In POP, Most function uses Global data for In OOP, data can not move easily from
sharing that can be accessed freely from function to function,it can be kept public or
function to function in the system. private so we can control the access of data.
POP does not have any proper way for hiding OOP provides Data Hiding so provides more
data so it is less secure. security.
In OOP, overloading is possible in the form of
In POP, Overloading is not possible. Function Overloading and Operator
Overloading.
Example of OOP are : C++, JAVA, VB.NET,
Example of POP are : C, VB, FORTRAN, Pascal.
C#.NET.

2. What are the applications of OOP?


Real-time systems. Simulation and modeling.
Object-oriented databases. AI and expert systems.

3. Differentiate C and C++.

C C++
C was developed by Dennis Ritchie between C++ was developed by Bjarne Stroustrup in 1979
1969 and 1973 at AT&T Bell Labs. with C++'s predecessor "C with Classes".
C++ is a superset of C. C++ can run most of C code
When compared to C++, C is a subset of C++.
while C cannot run C++ code.
C++ supports both procedural and object oriented
C supports procedural programming
programming paradigms; therefore C++ is also
paradigm for code development.
called a hybrid language.
C does not support object oriented Being an object oriented programming language
127
programming; therefore it has no support for C++ supports polymorphism, encapsulation, and
polymorphism, encapsulation, and inheritance.
inheritance.
In C++, data and functions are encapsulated
In C (because it is a procedural programming
together in form of an object. For creating objects
language), data and functions are separate
class provides a blueprint of structure of the
and free entities.
object.
In C, data are free entities and can be In C++, Encapsulation hides the data to ensure that
manipulated by outside code. This is because data structures and operators are used as
C does not support information hiding. intended.
C, being a procedural programming, it is a While, C++, being an object oriented programming,
function driven language. it is an object driven language.
C does not support function and operator C++ supports both function and operator
overloading. overloading.
C does not allow functions to be defined
In C++, functions can be used inside a structure.
inside structures.
C++ uses NAMESPACE which avoid name
C does not have namespace feature.
collisions.
C uses functions for input/output. For C++ uses objects for input output. For example cin
example scanf and printf. and cout.
C does not support reference variables. C++ supports reference variables.
C has no support for virtual and friend
C++ supports virtual and friend functions.
functions.
C provides malloc() and calloc() functions for
C++ provides new operator for memory allocation
dynamic memory allocation, and free() for
and free operator for memory de-allocation.
memory de-allocation.
C++ provides support for exception handling.
C does not provide direct support for error
Exceptions are used for "hard" errors that make
handling (also called exception handling)
the code incorrect.

4. Define Object, class, Data Abstraction, Encapsulation, Polymorphism, Data Hiding,


Inheritance, Dynamic Binding,
Objects:
 Object is an instance of a class.
 Objects are basic run-time entities in object oriented programming.
 A variable of a class is an object. Using objects we can access the member variable and member
function of a class.
 Object represent a person, place or any item that the program has to handle.
 A single class can have any number of objects.

Class
 It is a collection of objects. Each object has attributes and operations. The entire set of data and
code of an object can be made a user – defined data type with the help of a class.
 Class is a user defined data type, which holds its own data members and member functions,
which can be accessed and used by creating instance of that class.
 The variables inside class definition are called as data members and the functions are called
member functions.

128
 Class name must start with an uppercase letter. If class name is made of more than one word,
then first letter of each word must be in uppercase. Example,
class Study, class StudyTonight etc

Data Abstraction
The insulation of data from direct access by the program is called as data hiding or information
binding. The data is not accessible to the outside world and only those functions, which are
wrapped in the class, can access it.

Encapsulation
 Encapsulation means binding of data and functions together in a single entity called class.
 Data abstraction and encapsulation provide two important advantages:
o Hiding the data item.
o The data is not accessible to the outside functions and only those functions which are
wrapped in the class can access it.

Polymorphism
 Polymorphism means the ability to take more than one form. For example, an operation may
exhibit different behavior in different instances. The behavior depends upon the types of data
used in the operation.
 Types of polymorphism
o Compile Time Polymorphism (Eg: Function Overloading, Operator Overloading)
o Run time Polymorphism (Eg: Virtual Function)

Data Hiding
 It is the process of hiding the members from outside the class.
 It is implemented by the concept of “private” access specifiers.
 It can be accessed only by the member functions of that class where it is defined. This is also
called as information hiding.

Inheritance
 Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
 It means the new classes can be developed using some of the properties of old classes.
 The newly derived class is called as a derived class or sub class or child class. The existing class
is called as a base class or parent class or super class.
 Inheritance supports the concept of hierarchical classification.
 In OOP, the concept of inheritance provides the idea of reusability.

Dynamic Binding
 Binding refers to the linking of a procedure call to the code to be executed in response to the
call.
 In Static binding which function is to be called for a particular object is determined at the
compile time.
 Dynamic binding is the runtime determination of which function to call for a particular object of
the class based on the type of argument. In dynamic binding the code associated with a given
procedure call is not known until the time of the call at runtime.

129
5. Differentiate Classes and Objects

Class Object
Class is mechanism of binding data
Instance of class or variable of
Definition members and associated methods
class.
in a single unit.
Existence It is logical existence It is physical existence
Memory space is not allocated , Memory space is allocated,
Memory Allocation
when it is created. when it is created.
it is created many time as you
Declaration/definition Definition is created once.
require.

6. Differentiate pointer and reference.

Pointer Reference
A pointer can be re-assigned any Reference cannot be re-seated after
number of times binding.
Pointers can point nowhere (NULL) Reference always refer to an object.
Pointers will take the address of Reference cannot take the address of
another pointer variable another reference
Perform pointer arithmetic operations There's no "reference arithmetic
linke +,-,*,/,++,--

7. What are the manipulators available in c++?


Manipulators are the most common way to control output formatting.
Example:
 endl
 setfill
 setw
 setprecision

8. What is a namespace?
A namespace is designed to overcome this difficulty and is used as additional information to
differentiate similar functions, classes, variables etc. with the same name available in different
libraries. Using namespace, you can define the context in which names are defined. In essence, a
namespace defines a scope.

9. Define friend function.


A function that has access to the private member of the class but is not itself a member of the class
is called friend functions. The general form is
friend data_type function_name(classname);
Friend function is preceded by the keyword “friend‟.

Properties
Friend function is not in the scope of the class to which it has been declared as friend.
Hence it cannot be called using the object of that class.
Usually it has object as arguments.
130
It can be declared either in the public or private part of a class.
It cannot access member names directly. It has to use an object name and dot
membership operator with each member name. eg: ( A . x )

10. What is inline function?


 C++ inline function is powerful concept that is commonly used with classes. If a function
is inline, the compiler places a copy of the code of that function at each point where the
function is called at compile time.
 To inline a function, place the keyword inline before the function name and define the
function before any calls are made to the function. The compiler can ignore the inline
qualifier in case defined function is more than a line.

11. Write some situations where inline expansion may not work.
 Inline functions are not working for functions returning values, if loop, a switch, or a
goto exists
 Inline functions are not working for functions not returning values, if a return statement
exists if function contain static variables
 Inline functions are not working if it is recursive

12. Define constructor. What are its types?


A constructor is a kind of member function that initializes an instance of its class. A constructor has
the same name as the class and no return value. A constructor can have any number of parameters
and a class may have any number of overloaded constructors.

Types of Constructor
• Default Constructor
• Parameterized Constructor
• Copy Constructor

13. What is the use of destructor?


o A destructor is a special member function that is called when the lifetime of an object
ends. The purpose of the destructor is to free the resources that the object may have
acquired during its lifetime.
~class_name ()
{
………………..
}
o It is implicit.

14. What is copy constructor?


These are special type of Constructors which takes an object as argument, and is used to copy
values of data members of one object into other object.
Syntax
ClassName (const ClassName &old_obj);

15. What is constructor overloading?


 Constructors can also be overloaded since the constructor in a class have the same name
as that of the class their signatures are differentiate as their parameter list. Overloading
131
of constructor allows appropriate initialization of objects on creation, depending upon
the constructors allow specifying or initializing the data members dynamically.
 Constructors overloading are used to increase the flexibility of a class by having more
number of constructor for a single class. By have more than one way of initializing
objects can be done using overloading constructors.

16. What is the use of scope resolution operator?


 Scope resolution operator(::) is used to define a function outside a class
 It is used to access global variable and local variable with same name.
 It is used to define the static data member outside of the class.

17. Define strings. Name any 4 string functions.


A string is a sequence of zero or more characters followed by a NULL '\0' character. All the string
handling functions are prototyped in: string.h header file.

String handling functions

Function Work of Function


strlen() Calculates the length of string
strcpy() Copies a string to another string
strcat() Concatenates(joins) two strings
strcmp() Compares two string
strlwr() Converts string to lowercase
strupr() Converts string to uppercase
strrev() Reverse the string

18. What is a default argument?


A default argument is a value provided in function declaration that is automatically assigned by the
compiler if caller of the function doesn’t provide a value for the argument with default value.

19. What is type casting?


A cast is a special operator that forces one data type to be converted into another. As an operator, a
cast is unary and has the same precedence as any other unary operator.
The most general cast supported by most of the C++ compilers is as follows:
(type) expression

Types of Conversion
• Basic to Class Type Conversion
• Class to Basic Type Conversion
• Class to Class Type Conversion
Unit-II

1. Draw C++ structure.

132
2. What is the use of private, public and protected? (Access Specifiers)
 A public member is accessible from anywhere outside the class but within a program.
 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
 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.

3. What is the use of static data member and member function?


Static Data Member
• A static member is shared by all objects of the class. All static data is initialized to zero when
the first object is created, if no other initialization is present.
• Example
static int Count;
Static Member Function
• A static member function can only access static data member, other static member functions
and any other functions from outside the class.
• Static member functions have a class scope and they do not have access to the this pointer
of the class. Example
static int getCount()
{
return objectCount;
}
4. Define compile time polymorphism.
The compiler is able to select the appropriate function for a particular call at compile-time itself.
This is known as compile-time polymorphism. The compile-time polymorphism is implemented
with templates. They are:

133
Ø Function overloading
Ø Operator overloading

5. Define function overloading & operator overloading.


(i) Function overloading
Function overloading is a feature of C++ that allows us to create multiple functions with the same
name, so long as they have different parameters. Function overloading is usually used to enhance
the readability of the program. If you have to perform one single operation but with different
number or types of arguments, then you can simply overload the function.

(ii) Operator overloading


C++ has the ability to provide the operators with a special meaning for a data type. This mechanism
of giving such special meanings to an operator is known as Operator overloading. It provides a
flexible option for the creation of new definitions for C++ operators.

Syntax
Returntype classname:: operator operatorsymbol(argument list)
{
\\Function body
}

6. List the operators that cannot be overloaded.


In C++, following operators cannot be overloaded:
. (Member Access or Dot operator)
?: (Ternary or Conditional Operator )
:: (Scope Resolution Operator)
.* (Pointer-to-member Operator )
sizeof (Object size Operator)

7. What are the rules for overloading an operator?


 Only the existing operators can be overloaded.
 The overload operator must have at least one operand that is of user defined data type.
 We cannot change the basic meaning of an operator. That is to say, we cannot redefine
the plus (+) operator to subtract one value from the other.
 Overloaded operators must follow the syntax rules of the original operators.
 Some of the operators cannot be simply overloaded.
 We cannot use friend function to overload certain operators. However, member
functions can be used to overload them.
 Unary operators, overloaded by means of a member function, take no explicit arguments
and return no explicit values, but, those overloaded by means of a friend function, take
one reference argument.
 Binary operators overloaded through a member function take one explicit argument and
those which are overloaded through a friend function take two explicit arguments.
 When using binary operators overloaded through a member function, the left hand
operand must be an object of the relevant class.
 Binary arithmetic operators such as +, -, * and / must explicitly return a value. They
must not attempt to change their own arguments.

134
8. Why cannot friend function be used to overload assignment operator?
If the operation modifies the state of the class object, it operates on, it must be a member function,
not a friend function Thus all operator such as =, *=, +=, etc are naturally defined as member
functions not friend functions Conversely, if the operator does not modify any of its operands, but
needs only a representation of the object, it does not have to be a member function and often less
confusing.

9. Define runtime polymorphism.


Run time polymorphism is achieving which object's method should invoked during Runtime
instead of compile time. he keyword virtual on a member function in base class indicates to the
compiler to delay the binding till run time. Every class with atleast one virtual function helps in
binding at run time.

10. What is virtual function & pure virtual function?


(i) Virtual function
A virtual function in C++ is :
- A simple member function of a class which is declared with “virtual” keyword
- It usually performs different functionality in its derived classes.
- The resolving of the function call is done at run-time.

Syntax
virtual void display()
{
……………..
}
(ii) Pure Virtual Functions
Pure virtual Functions are virtual functions with no definition. They start with virtual keywordand
ends
with= 0.

Syntax
virtual void show() = 0;

11. Define abstract Class.


Any class that has at least one pure virtual function is called an abstract class.

Example
// An abstract class
class Test
{
public:
virtual void show() = 0;
};
Unit-III
1. Define templates. What are its types?
Templates are a feature of the C++ programming language that allows functions and classes to
operate with generic types. This allows a function or class to work on many different data types
without being rewritten for each one.
135
Types
a. Function Template
b. Class template

(i) Function Template


• A function template behaves like a function except that the template can have arguments of
many different types. In other words, a function template represents a family of functions.
• Syntax
template <class identifier> function_declaration;
template <typename identifier> function_declaration;

(ii) Class template


A class template defines a family of classes. The syntax is
template < parameter-list > class-declaration

2. What is the difference between function template and template function?


A function template is body of a function that is bracketed around template keyword, which is not
an actual function, and will not be fully compiled by compiler, and is not accountable by the linker.
At least one call, for particular data-type(s) is needed to instantiate it, and be put into
accountability of compiler and linker. Therefore, the instance of function template Foo is
instantiated as Foo(int) or Foo(double).
A template function is simply an "instance of a function template", which is produced when you
call it, or cause it to get instantiated for particular data type. The instance of function-template is
actually a valid function.

3. Define inheritance. List the types.


Inheritance is one of the key feature of object-oriented programming including C++ which allows
user to create a new class (derived class) from a existing class(base class). The derived class
inherits all feature from a base class and it can have additional features of its own.

Types of Inheritance
6. Single Inheritance
7. Multiple Inheritance
8. Hierarchical Inheritance
9. Multilevel Inheritance
10. Hybrid Inheritance (also known as Virtual Inheritance)

4. What are the members that cannot be inherited?


a. Constructors, destructors and copy constructors of the base class.
b. Overloaded operators of the base class.
c. The friend functions of the base class.

5. Define STL. What are the components of STL?


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 algorithms and
data structures like vectors, lists, queues, and stacks.

136
Components of STL

6. Define containers.
 A container is a holder object that stores a collection of other objects (its elements). They are
implemented as class templates, which allows a great flexibility in the types supported as
elements.
 The container manages the storage space for its elements and provides member functions to
access them, either directly or through iterators (reference objects with similar properties to
pointers).

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

8. What is the use of try, catch & throw block?


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.
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.
throw: A program throws an exception when a problem shows up. This is done using a throw
keyword.

9. Define streams.
A stream is just a sequence of characters that can be accessed sequentially. Over time, a stream
may produce or consume potentially unlimited amounts of data. There is no need to know details
about the media associated to the stream or any of its internal specifications. All it needs to know is
that streams are a source/destination of characters, and that these characters are
provided/accepted sequentially (i.e., one after another).

Types of streams
 Input Streams
 Output Streams

10. List out any 4 file processing methods.

Function Operation
137
open() To create a file
close() To close an existing file
get() Read a single character from a file
put() write a single character in file.
read() Read data from file
write() Write data into file.

Unit-IV
1. Differentiate C++ and Java.

Java C++
Java does not support pointers, templates, unions, C++ supports structures, unions, templates,
operator overloading, structures etc. operator overloading, pointers and pointer
arithmetic.
Java support automatic garbage collection. It C++ support destructors, which is automatically
does not support destructors as C++ does. invoked when the object is destroyed.
Java does not support conditional compilation Conditional inclusion (#ifdef #ifndef type) is one
and inclusion. of the main features of C++.
Java has built in support for threads. C++ has no built in support for threads.
Java does not support default arguments. There is C++ supports default arguments. C++ has scope
no scope resolution operator (::) in Java. resolution operator (::)
There is no goto statement in Java. C++ has goto statement.
Java doesn't provide multiple inheritance. C++ does support multiple inheritance.
Exception handling in Java is different because
there are no destructors. Also, in Java, try/catch While in C++, you may not include the try/catch
must be defined if the function declares that it even if the function throws an exception.
may throw an exception.
Java has method overloading, but no operator C++ supports both method overloading and
overloading. operator overloading.
Java is interpreted for the most part and hence C++ generates object code and the same code
platform independent. may not run on different platforms.

2. What are the features of Java?


 Simple
 Platform Independent and Portable
 Object-oriented
 Robust and Secure
 Multithreaded
 Architecture-neutral
 Interpreted
 High performance
 Distributed
 Dynamic

3. Define JVM & JRE


JVM (Java Virtual Machine)
138
 The Java Compiler converts the Source code into the Byte code.
 But java compiler is not executable code. Rather, it is byte code.
 This bytecode will be stored in class files.
 Bytecode is highly optimized set of instructions designed to be executed by the Java
run – time system, which is called the Java Virtual Machine (JVM).
 Java Virtual Machine (JVM) is unique for each platform.
JRE (Java Runtime Environment)
 Java Runtime Environment contains JVM, class libraries and other supporting
components.
 Java source code is compiled into bytecode by Java compiler.
 This bytecode will be stored in class files.
 During runtime, this bytecode will be loaded, verified and JVM interprets the
bytecode into machine code which will be executed in the machine in which the Java
program runs.

4. Draw the structure of Java.

5. What is a command line argument?


The java command-line argument is an argument i.e. passed at the time of running the java
program. The arguments passed from the console can be received in the java program and it can be
used as an input.

Example
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}

6. What are tokens?

139
Smallest individual units in a program are known as tokens. The compiler recognizes them for
building up expressions and statements. A Java program is a collection of tokens, comments and
white spaces. Java language includes five types of tokens. They are:
1. Reserved Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators

7. List out Java data types.

8. Define byte code in java.


The Java Compiler converts the Source code into the Byte code. But java compiler is not executable
code. Rather, it is byte code. This byte code will be stored in class files. Byte code is highly
optimized set of instructions designed to be executed by the Java run – time system, which is called
the Java Virtual Machine (JVM).

9. Define packages. What is API package?


Packages are java‘s way of grouping a variety of classes and or interfaces together. The grouping is
usually done according to functionality. In fact, packages act as ―containers for classes.

Types of Packages
Java packages are therefore classified into two types.
1. Pre – defined packages (Java API Packages)
2. User – defined packages
Java API Packages

Package Contents
Name
java.lang Language support classes. These are classes that java compiler itself uses and

140
therefore they are automatically imported. They include classes for primitive
types, strings, math functions, threads and exceptions
java.util Language utility classes such as vectors, hash tables, random numbers, date,
etc.
java.io Input / Output support classes. They provide facilities for the input and
output of data.
java.awt Set of classes for implementing graphical user interface. They include classes
for windows, buttons, lists, menus and so on.
java.net Classes for networking. They include classes for communicating with local
computers as well as with internet servers.
java.applet Classes for creating and implementing applets.

10. Define arrays.


Array is a collection of similar type of elements that have contiguous memory location. Java array is
an object that contains elements of similar data type. It is a data structure where we store similar
elements. We can store only fixed set of elements in a java array. Array in java is index based, first
element of the array is stored at 0 index.

11. Define strings. Name any 4 string functions.


Strings, which are widely used in Java programming, are a sequence of characters. In the Java
programming language, strings are objects.The Java platform provides the String class to create
and manipulate strings. The java.lang.String class provides a lot of methods to work on string. By
the help of these methods, we can perform operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.

String Functions
1. toUpperCase() and toLowerCase()
2. trim()
3. startsWith() and endsWith()
4. charAt()
5. length()
6. replace()
7. substring()
8. equals()
9. equalsIgnoreCase()
10. Concatenation

Unit-V

141
1. Define Inheritance. What are its types?
Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance the information is made manageable in a hierarchical
order. The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class, parent
class).

Types of Inheritance
4. Single Inheritance (Only one Super Class and One Only Sub Class)
5. Multiple Inheritance using Interface(Many Super Class and Only one Sub Class)
6. Multilevel Inheritance (Derived from a Derived Class)
4 . Hierarchical Inheritance (One Super Class, Many Subclasses)

2. What is the use of final keyword?


The final keyword in java is used to restrict the user. The java final keyword can be used in many
contexts. Final can be:
4. variable
5. method
6. class
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only.

3. What is the use of super keyword?


In Java, super keyword is used to refer to immediate parent class of a class. In other words super
keyword is used by a subclass whenever it need to refer to its immediate super class.

Purpose of ‘super’ keyword


1. Using super to call Superclass Constructors
2. Using super to call Superclass Methods

4. What is the difference between final, finally and finalize?

final finally finalize


Final is used to apply restrictions
on class, method and variable. Finally is used to place Finalize is used to perform
Final class can't be inherited, final important code, it will be clean up processing just
method can't be overridden and executed whether before object is garbage
final variable value can't be exception is handled or not. collected.
changed.
Final is a keyword. Finally is a block. Finalize is a method.

5. Differentiate overloading and overriding.

overloading overriding
Overloading occurs when two or more Overriding means having two methods with
methods in one class have the same method the same method name and parameters (i.e.,
142
name but different parameters. method signature).
Polymorphism is not applies to overloading Polymorphism applies to overriding
Static binding is being used for overloaded Dynamic binding is being used for
methods overridden/overriding methods.
Overloading happens at compile-time Overriding happens at runtime
Static methods can be overloaded which means Static methods cannot be overridden
a class can have more than one static method
of same name.
Overloading is being done in the same class For overriding base and child classes are
required.
private and final methods can be overloaded private and final methods cannot be
overloaded
Return type of method does not matter in case The overriding method can have more
of method overloading, specific return type

6. Define interface.
An interface in java is a blueprint of a class. It has static constants and abstract methods only. The
interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in
the java interface not method body. It is used to achieve fully abstraction and multiple inheritance
in Java. It cannot be instantiated just like abstract class.

7. Define abstract class.


An abstract class is a class that is declared abstract—it may or may not include abstract methods.
Abstract classes cannot be instantiated, but they can be subclassed. An abstract method is a method
that is declared without an implementation (without braces, and followed by a semicolon), like
this:
abstract void display(int a, int b);

8. Differentiate abstract class & Interface.

Abstract Classes Interfaces


abstract class can extend only one class or interface can extend any number of interfaces at a
one abstract class at a time time
abstract class can extend from a class or
interface can extend only from an interface
from an abstract class
abstract class can have both abstract and
interface can have only abstract methods
concrete methods
A class can extend only one abstract class A class can implement any number of interfaces
In abstract class keyword ‘abstract’ is
In an interface keyword ‘abstract’ is optional to
mandatory to declare a method as an
declare a method as an abstract
abstract
abstract class can have protected , public Interface can have only public abstract methods
and public abstract methods i.e. by default
abstract class can have static, final or static interface can have only static final (constant)
final variable with any access specifier variable i.e. by default

9. Define exception.

143
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore these
exceptions are to be handled.

Example
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayStoreException Assignment to an array element of an incompatible type.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.

10. What is the difference between throw and throws?

Throw Throws
throw keyword is used to throw an Throws clause in used to declare an
exception explicitly exception
throw is followed by an instance throws is followed by exception class names
variable
The keyword throw is used inside throws clause is used in method
method body to invoke an exception declaration (signature)

11. Define Thread. What are its states?


A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of
execution. Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area. in a single thread.

12. What is multi-threading? Write the methods of threads.


Multithreading in java is a process of executing multiple threads simultaneously. Thread is
basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.

Thread Methods
144
 getName(): It is used for Obtaining a thread’s name
 getPriority(): Obtain a thread’s priority
 isAlive(): Determine if a thread is still running
 join(): Wait for a thread to terminate
 run(): Entry point for the thread
 sleep(): suspend a thread for a period of time
 start(): start a thread by calling its run() method

13. What are wrapper classes?


In Java, a wrapper class is defined as a class in which a primitive value is wrapped up. These
primitive wrapper classes are used to represent primitive data type values as objects. The Java
platform provides wrapper classes for each of the primitive data types.

Primitive data type Wrapper class


byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

14. Define an inner class.


 Java inner class or nested class is a class i.e. declared inside the class or interface.
 We use inner classes to logically group classes and interfaces in one place so that it can be
more readable and maintainable.
 Additionally, it can access all the members of outer class including private data members
and methods.

Question Bank
Unit-I (PART-A)

1. Compare Procedural Oriented Languages and Object Oriented Languages.


2. What are the applications of OOP?
3. Differentiate C and C++.
4. Define Object, class, Data Abstraction, Encapsulation, Polymorphism, Data hiding, Inheritance,
Dynamic Binding,
5. Differentiate Classes and Objects
6. Differentiate pointer and reference.
7. What are the manipulators available in c++?
8. What is a namespace?
9. Define friend function.
10. What is inline function?
11. Write some situations where inline may not work.
12. Define constructor. What are its types?
13. What is the use of destructor?
14. What is copy constructor?
145
15. What is constructor overloading?
16. What is the use of scope resolution operator?
17. Define strings. Name any 4 string functions.
18. Whatis default arguments?
19. What is type casting?

UNIT –I (PART-B)
1. Concepts of OOPS.
2. Types of constructor.
3. Function overloading.
4. Inline function.
5. Friend function.
6. Default arguments.
7.Static data member and member function.

Unit-II (PART-A)
1. Draw C++ structure.
1. What is the use of private, public and protected? (Access Specifiers)
2. What is the use of static data member and member function?
3. Define compile time polymorphism.
4. Define function & operator overloading.
5. List the operators that cannot be overloaded.
6. What are the rules for overloading an operator?
7. Why cannot friend function be used to overload assignment operator?
8. Define runtime polymorphism.
9. What is virtual function & pure virtual function?
10. Define abstract Class.

Unit-II (PART-B)
1. Operator Overloading
2. Inheritance
3. Runtime polymorphism

Unit-III (PART-A)
1. Define templates. What are its types?
2. What is the difference between function template and template function?
3. Define inheritance. List the types.
4. What are the members that cannot be inherited?
5. Define STL. What are the components of STL?
6. Define containers.
7. Define exception.
8. What is the use of try, catch & throw block?
9. Define streams.
10. List out any 4 file processing methods.

Unit-III (PART-B)
1. Templates
2. Exception Handling
3. File I/O
4. STL

Unit-IV (PART-A)
1. Differentiate C++ and Java.
146
2. What are the features of Java?
3. Define JVM& JRE.
4. Draw the structure of Java.
5. What is a command line argument?
6. What are tokens?
7. List out Java datatypes.
8. Define byte code in java.
9. Define packages. What is API package?
10. Define arrays.
11. Define strings. Name any 4 string functions.

Unit-IV (PART-B)
1. Java Virtual Machine
2. Java Arrays
3. Java Strings
4. Java Packages

Unit-V (PART-A)
1. Define Inheritance. What are its types?
2. What is the use of final keyword?
3. What is the use of super keyword?
4. What is the difference between final, finally and finalize?
5. Differentiate overloading and overriding.
6. Define interface.
7. Define abstract class.
8. Differentiate abstract class & Interface.
9. Define exception.
10. What is the difference between throw and throws?
11. Define Thread. What are its states?
12. What is multi-threading? Write methods of thread.
13. What are wrapper classes?
14. Define an inner class.

Unit-V (PART-B)
1. Interfaces
2. Java Inheritance
3. Java Exception Handling
4. Threads
5. Java I/O Streams

147

You might also like