Sunteți pe pagina 1din 53

1

SNS COLLEGE OF ENGINEERING


COIMBATORE- 641107

DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING

S6461

Object Oriented Programming Laboratory


IV Semester EEE

Prepared By,
Mr.Jebakumar Immanuel.D
Mr.P.Baskaran

CS6461

OBJECT ORIENTED PROGRAMMING LABORATORY

1. Program Using Functions

functions with default arguments


implementation of call by value, address, reference
2. Simple classes for understanding objects, member functions & constructors

classes with primitive data members,


classes with arrays as data members
classes with pointers as data members
classes with constant data members
classes with static member functions

3. Compile time polymorphism

operator overloading
function overloading
4. Run time polymorphism

inheritance
virtual functions
virtual base classes
templates

5. File Handling

sequential access
random access
JAVA:
6. Simple Java Applications

for understanding references to an instant of a class


handling strings in JAVA
7. Simple Package Creation

developing user defined packages in java


8. Interfaces

developing user defined interfaces


use predefined interfaces
9. Threading

creation of threading in java applications


multi threading
10. Exception Handling Mechanism In Java

handling predefined exceptions

handling user defined exceptions

Ex: No: 1(a)


DEFAULT ARGUMENT IN C++
Date :
Aim:
To write a c ++ program to implement the default argument
Prerequisite:
In C++ programming, you can provide default values for function parameters. The
idea behind default argument is very simple. If a function is called by passing argument/s,
those arguments are used by the function. But if all argument/s are not passed while invoking
a function then, the default value passed to arguments are used. Default value/s are passed to
argument/s in function prototype.
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Declare the simple interest function with default argument.
Step 3: From main function call the required data.
Step 4: Define simple interest function.
Step 5: Calculating simple interest.
Step 6: Display the details given.
Step 7: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
void volume(int l=10,int b=20,int h=15);
void volume(int l,int b,int h)
{
int vol;
vol=l*b*h;
cout<<"\n\nVOLUME OF RECTANGLE IS:\t"<<vol;
}
void main()
{
clrscr();
cout<<"\n\n When length, breadth, height are default arguments";
volume();
cout<<"\n\n When breadth, height are default arguments";
volume(90);
cout<<"\n\n When height is default argument";
volume(20,15);
cout<<"\n\n When No default arguments";
volume(20,20,10);
getch();
}

OUTPUT:
When length, breadth, height are default arguments
VOLUME OF RECTANGLE IS: 3000
When breadth, height are default arguments
VOLUME OF RECTANGLE IS: 27000
When height is default argument
VOLUME OF RECTANGLE IS:

20000

When No default arguments


VOLUME OF RECTANGLE IS:

4000

Postlab :
What is Default argument?
What is function call?

Result:

Thus the implementation of c ++ program for default argument is executed and the
output has been verified.

Ex: No: 1(b) IMPLEMENTATION OF CALL BY VALUE, ADDRESS, REFERENCE


Date :
Aim:
To write a c ++ program to implement the call by value, address, reference
Prerequisite:
Call by value: In C++ by default a function call passes parameters by value
In this mechanism the values of actual parameters will be passed to a separate
set of variables known as formal parameters
The formal parameters of type value parameters
Any changes made to formal parameters will not affect the corresponding
actual parameters.
Only one value to be return from function
Call by address: In C++ it is possible to call a function by passing address this technique is
known as call by address.
In call by address technique the formal parameters must be a pointer type and
they receive the addresses of actual parameters.
Any changes to the formal parameters are automatically reflected back to the
actual parameters in the main program.
It is possible to make a function to return more than one value to the calling
program
The address can be generated by using address operator &.
Call by Reference: The formal parameters must be of type reference.
When we pass parameters by reference the formal parameters becomes like an alias
variable to the formal parameters.
To pass arguments by reference, the function call is similar to that of call by value. Ex
swap(a,b)
In the function decelerator the formal parameters are preceded by the & operator.
It is possible to return more than one value from a function to the main program
Any changes to the formal parameters are automatically reflected back to the actual
parameters in the main program.
Using this method no duplicate set of variables are crated.

Prelab:

Algorithm:
Step 1: Start the program.
Step 2: Create the class and declare the variable and functions of the class.
Step 3: In main function, objects are created and the respective functions are called
for the Function.
Step 4: Get n value and calculation function is repeat by using for swap.
Step 5: Stop the program.
Program:
CALL BY VALUE
#include<iostream.h>
#include<conio.h>
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
cout<<"\n The value of a and b in swap fun is\t "<<x<<"\t"<<y;
}
void main()
{
int a,b;
clrscr();
cout<<"\n Enter the value of a and b:\n";
cin>>a>>b;
cout<<"\n The value of a and b before the swap fun is:\t"<<a<<"\t"<<b;
swap(a,b);
cout<<"\n\n The value of a and b after the swap fun is:\t"<<a<<"\t"<<b;
getch();
}
CALL BY ADDRESS
#include<iostream.h>
#include<conio.h>
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=*temp;
cout<<"\n The value of a and b in swap fun is\t "<<*x<<"\t"<<*y;
}
void main()
{
int a,b;
clrscr();
cout<<"\n Enter the value of a and b:\n";
cin>>a>>b;
cout<<"\n The value of a and b before the swap fun is:\t"<<a<<"\t"<<b;
swap(&a,&b);
cout<<"\n\n The value of a and b after the swap fun is:\t"<<a<<"\t"<<b;
getch();
}

CALL BY REFERENCE
#include<iostream.h>
#include<conio.h>
void swap(int &x,int &y)
{
int temp;
temp=x;
x=y;
y=temp;
cout<<"\n The value of a and b in swap fun is\t "<<x<<"\t"<<y;
}
void main()
{
int a,b;
clrscr();
cout<<"\n Enter the value of a and b:\n";
cin>>a>>b;
cout<<"\n The value of a and b before the swap fun is:\t"<<a<<"\t"<<b;
swap(a,b);
cout<<"\n\n The value of a and b after the swap fun is:\t"<<a<<"\t"<<b;
getch();
}
OUTPUT:
CALL BY VALUE
Enter the value of a and b:
7
2
The value of a and b before the swap fun is: 7
The value of a and b in swap fun is: 2 7
The value of a and b after the swap fun is: 7
CALL BY ADDRESS
Enter the value of a and b:
6
8
The value of a and b before the swap fun is: 6
The value of a and b in swap fun is: 8 6
The value of a and b after the swap fun is: 6

2
2

8
8

CALL BY REFERENCE
Enter the value of a and b:
4
3
The value of a and b before the swap fun is:4
The value of a and b in swap fun is: 3 4
The value of a and b after the swap fun is:4

3
3

Post Lab:
What is parameter passing?
Differentiate value, address and reference?

Result:
Thus the implementation of c ++ program for implementation of call by value, address,
reference.

10

Ex: No: 2(a)


CLASSES WITH PRIMITIVE DATA MEMBERS,
Date :
Aim:
To write a c ++ program classes with primitive data members.
Prerequisite:
A class is used to specify the form of an object and it combines data representation
and methods for manipulating that data into one neat package. The data and functions within
a class are called members of the class.
A class definition starts with the keyword class followed by the class name; and the
class body, enclosed by a pair of curly braces. A class definition must be followed either by a
semicolon or a list of declarations.
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Create the class and declare the variable and functions of the class.
Step 3: In main function, objects are created and the respective functions are called
for the Function.
Step 4: Get n value
Step 5: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
#define pi 3.14
class AREA
{
int area1,area2;
public:
void circle(int r);
void rectangle(int l,int b);
};
void AREA::circle(int r)
{
area1=pi*r*r;
cout<<"AREA OF THE CIRCLE : "<<area1;
}
void AREA::rectangle(int l,int b)
{
area2=l*b;
cout<<"AREA OF THE RECTANGLE : "<<area2;
}
void main()
{
int r,l,b;
clrscr();
AREA JJ;
cout<<"\nEnter the radius of the circle : ";
cin>>r;
JJ.circle(r);
cout<<"\n\nEnter the length & breadth of the rectangle : ";
cin>>l>>b;
JJ.rectangle(l,b);

11

getch();}
OUTPUT :
Enter the radius of the circle : 7
AREA OF THE CIRCLE : 153
Enter the length & breadth of the rectangle : 15 7
AREA OF THE RECTANGLE : 105
Post lab :
What is meant by Classes?
What is meant by objects.?
How do you access functions outside of the classes?

Result:
Thus the implementation of c ++ program for primitive data members is executed and
the output has been verified.

12

13

Ex: No: 2(b)


CLASSES WITH ARRAYS AS DATA MEMBERS
Date :
Aim:
To write a c ++ program classes with primitive data members.
Prerequisite:
C++ provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type. All arrays
consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.
type arrayName [ arraySize ]; // Array declaration
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; Array Initialization
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Create the class and declare the variable and functions of the class.
Step 3: In main function, objects are created and the respective functions are called
for the Function.
Step 4: Get n value and initialize array
Step 5: Stop the program.
Inlab:
Program:
#include<iostream.h>
#include<conio.h>
class student
{
char name[30];
int m[5],i,sum;
float avg;
public:
void get();
void total();
void average();
};
void student::get()
{
cout<<"\nEnter a Name : ";
cin>>name;
cout<<"\nEnter the 5 marks : ";
for(i=0;i<5;i++)
{
cin>>m[i];
}
}
void student::total()
{
for(i=0;i<5;i++)
{
sum+=m[i];
}
cout<<"\nSum is "<<sum;
}
void student::average()
{

14

avg=sum/5;
cout<<"\nAverage is "<<avg;
}
void main()
{
clrscr();
student JJ;
JJ.get();
JJ.total();
JJ.average();
getch();
}

OUTPUT :
Enter a Name : JEBASTIN
Enter the 5 marks :
100
99
95
80
100
Sum is 474
Average is 94.8
Postlab:
What is meants by array?
How Array is declared inC++?
How Array is initialized?

Result:
Thus the implementation of c ++ program is classes with arrays as data members is executed
and the output has been verified.

15

Ex: No: 2(c)


Date :

CLASSES WITH POINTERS AS DATA MEMBERS

Aim:
To write a c ++ program classes with pointers as data members data members.
Prerequisite:
A pointer is a variable whose value is the address of another variable. Like any
variable or constant, you must declare a pointer before you can work with it. The general
form of a pointer variable declaration is:
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type and var-name is the
name of the pointer variable. The asterisk you used to declare a pointer is the same asterisk
that you use for multiplication. However, in this statement the asterisk is being used to
designate a variable as a pointer.
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Create the class and declare the variable and functions of the class.
Step 3: In main function, objects are created and the respective functions are called
for the Function.
Step 4: Initialize pointers
Step 5: Get n value and calculation function is repeat by using for loop.
Step 6: Stop the program.
Program:
#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);
}
void display()
{
cout<<name<<endl;
}
void join(string &a,string &b);
};
void string::join(string &a,string &b)
{
length=a.length+b.length;

16

delete name;
name=new char[length+1];
strcpy(name,a.name);
strcat(name,b.name);
}
void main()
{
char *first="JEBASTIN";
string name1(first),name2("MADURAVOYAL"),name3("CHENNAI"),s1,s2;
s1.join(name1,name2);
s2.join(s1,name3);
name1.display();
name2.display();
name3.display();
s1.display();
s2.display();
}
OUTPUT :
JEBASTIN
MADURAVOYAL
CHENNAI
JEBASTINMADURAVOYAL
JEBASTIN MADURAVOYALCHENNAI
Post lab:
What is pointer data type?
How to declare pointer in c++?
How to access address of a data item using pointer?
Mention syntax for pointer.

Result:

17

Thus the implementation of c ++ program is classes with pointers as data members is


executed and the output has been verified.
Ex: No: 2(d)
Date :

CLASSES WITH CONSTANT DATA MEMBERS

Aim:
To write a c ++ program classes with constant data members,
Prelab :
Constants refer to fixed values that the program may not alter and they are
called literals. Constants can be of any of the basic data types and can be divided into Integer
Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values. Again,
constants are treated just like regular variables except that their values cannot be modified
after their definition. It can be achieved by const and define keyword.
Example:
#define PI 3.14159
const double pi = 3.1415926;
Algorithm:
Step 1: Start the program.
Step 2: Create the class and declare the variable and functions of the class.
Step 3: In main function, objects are created and the respective functions are called
for the Function.
Step 4: Get n value
Step 5: Declare constant variable
Step 6: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class student
{
char name[30],dep[30];
const int RollNo;
public:
void getdata();
void putdata();
};
void student::getdata()
{
cout<<"\nEnter the Name : ";
cin>>name;
cout<<"\nEnter the department : ";
cin>>dep;
}
void student::putdata()
{
cout<<"\nStudent's Name:"<<name;
cout<<"\nStudent's Roll No:"<<RollNo;
cout<<"\nStudent's Department:"<<dep;
}
void main()
{
clrscr();
student JJ;
JJ.getdata();
JJ.putdata();

18
getch();
}
ERROR:
Constant member student::RollNo in class without constructors

Post Lab:
How to use constants in programs?
What are all the ways used to make a variable as constants?
What is the use of Constants?

Result:
Thus the implementation of c ++ program is classes with arrays as data members is executed
and the output has been verified.

19

Ex: No: 2(e)


Date :

CLASSES WITH STATIC MEMBER FUNCTIONS

Aim:
To write a c ++ program classes with static data members.
Prerequisite:
We can define class members static using static keyword. When we declare a
member of a class as static it means no matter how many objects of the class are created,
there is only one copy of the static 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. We can't put it in the class definition but it can be initialized outside
the class as done in the following example by redeclaring the static variable, using the scope
resolution operator:: to identify which class it belongs to.
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Declare the class name as Stat with data member s and member functions.
Step 3: The constructor Stat() which is used to increment the value of count as 1 to to assign
the variable code.
Step 4: The function showcode() to display the code value.
Step 5: The function showcount() to display the count value.
Step 6: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class s
{
float deposit,withdrawal;
static float balance;
public:
void dep();
static void input();
void withdraw();
};
void s::dep()
{
cout<<"\nDeposit the amount : ";
cin>>deposit;
balance+=deposit;
}
void s::input()
{
cout<<"\nYour Current Balance is Rs."<<balance<<"/-"<<endl;
}
void s::withdraw()
{
cout<<"\nHow much you want to withdraw?: ";
cin>>withdrawal;
balance-=withdrawal;
}
float s::balance=1000;
void main()
{
s J;

20
clrscr();
J.dep();
s::input();
J.withdraw();
s::input();
getch();
}
OUTPUT :
Deposit the amount : 1500
Your Current Balance is Rs.2500/How much you want to withdraw? : 2000
Your Current Balance is Rs. 500/-

Post Lab:
What is the use of declaring variable as static and function as static?
How public and private static members are used in C++ program?

Result:

21

Thus the implementation of c ++ program is classes Static data members is executed and the
output has been verified.
Ex: No: 3(a)
Date :

OPERATOR OVERLOADING

Aim:
To write a c ++ program classes operator overloading..
Prerequisite:
C++ allows you to specify more than one definition for a function name or
an operator in the same scope, which is called function overloading and operator
overloading respectively. An overloaded declaration is a declaration that had been declared
with the same name as a previously declared declaration in the same scope, except that both
declarations have different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most
appropriate definition to use by comparing the argument types you used to call the function
or operator with the parameter types specified in the definitions.
Operators overloading in C++:
You can redefine or overload most of the built-in operators available in C++. Thus a
programmer can use operators with user-defined types as well. Overloaded operators are
functions with special names the keyword operator followed by the symbol for the operator
being defined. Like any other function, an overloaded operator has a return type and a
parameter list.
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Declare the class.
Step 3: Declare the variables and its member function.
Step 4: Using the function getvalue() to get the two numbers.
Step 5: Define the function operator +() to add two complex numbers.
Step 6: Define the function operator ()to subtract two complex numbers.
Step 7: Define the display function.
Step 8: Declare the class objects obj1,obj2 and result.
Step 9: Call the function getvalue using obj1 and obj2
Step 10: Calculate the value for the object result by calling the function operator + and
operator -.
Step 11: Call the display function using obj1 and obj2 and result.
Step 12: Return the values.
Step 13: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class sample
{
int x,y,z;
public:
void getdata(int a,int b,int c);
void display();
void operator-();
};
void sample::getdata(int a,int b,int c)
{
x=a; y=b; z=c;

22
}
void sample::display()
{
cout<<"\n"<<"X="<<x<<"\tY="<<y<<"\tZ="<<z<<"\n";
}
void sample::operator-()
{
x=-x; y=-y; z=-z;
}
void main()
{
sample s;
clrscr();
s.getdata(10,-20,30);
s.display();
-s;
s.display();
getch();
}
OUTPUT:
Input X=10 Y=-20 Z=30
Output X=-10 Y=20 Z=-30
PostLab:

How to achieve polymorphism in C++?


What is operator overloading?
What are all the operators that cant be overloaded?

23

Result:
Thus the implementation of c ++ program is classes with operator overloading is executed
and the output has been verified.
Ex: No: 3(a)
Date :

FUNCTIONOVERLOADING

Aim:
To write a c ++ program classes with function overloading..
Prerequisite:
C++ allows you to specify more than one definition for a function name or
an operator in the same scope, which is called function overloading and operator
overloading respectively. An overloaded declaration is a declaration that had been declared
with the same name as a previously declared declaration in the same scope, except that both
declarations have different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most
appropriate definition to use by comparing the argument types you used to call the function
or operator with the parameter types specified in the definitions.
Function Overloading:
We can have multiple definitions for the same function name in the same scope. The
definition of the function must differ from each other by the types and/or the number of
arguments in the argument list. You can not overload function declarations that differ only by
return type.
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Declare the class.
Step 3: Declare the variables and its member function.
Step 4: Define the function operator ()to subtract two complex numbers.
Step 5: Define the display function.
Step 6: Declare the class objects obj1,obj2 and result.
Step7: Call the function getvalue using obj1 and obj2
Step 8: Calculate the value for the object result by calling the function operator + and
operator -.
Step 9: Call the display function using obj1 and obj2 and result.
Step 10: Return the values.
Step 11: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
void swap(int x,int y)
{
int temp;
cout<<"\n Before swapping of two Intger values:\t"<<x<<"\t "<<y;
temp=x;
x=y;
y=temp;
cout<<"\n After swapping of two Intger values:\t"<<x<<"\t "<<y;
}
void swap(float x,float y)
{
float temp;
cout<<"\n Before swapping of two Float values:\t"<<x<<"\t "<<y;
temp=x;
x=y;

24
y=temp;
cout<<"\n After swapping of two Float values:\t"<<x<<"\t "<<y;
}
void swap(char x,char y)
{
char temp;
cout<<"\n Before swapping of two Characters:\t"<<x<<"\t "<<y;
temp=x;
x=y;
y=temp;
cout<<"\n After swapping of two Characters:\t"<<x<<"\t "<<y;
}
void main()
{
int a,b;
float c,d;
char e,f;
clrscr();
cout<<"\n\n Enter two integer values:\t";
cin>>a>>b;
swap(a,b);
cout<<"\n\n Enter two float values:\t";
cin>>c>>d;
swap(c,d);
cout<<"\n\n Enter two characters:\t";
cin>>e>>f;
swap(e,f);
getch();
}
OUTPUT:
Enter two integer values:
10
20
Before swapping of two Integer values: 10
20
After swapping of two Integer values: 20
10
Enter two float values:
10.25 20.25
Before swapping of two Float values: 10.25 20.25
After swapping of two Float values:
20.25 10.25
Enter two characters: A
z
Before swapping of two Characters: A
z
After swapping of two Characters:
z
A

Post Lab:
How to achieve polymorphism in C++?
What is function overloading?
Mention use of function overloading?

25

Result:
Thus the implementation of c ++ program is classes with function overloading is executed
and the output has been verified.
Ex: No: 4(a)
Date :

INHERITANCE

Aim:
To write a c ++ program classes with inheritance..
Prerequisite:
One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance allows us to define a class in terms of another class, which makes it easier to
create and maintain an application. This also provides an opportunity to reuse the code
functionality and fast implementation time. When creating a class, instead of writing
completely new data members and member functions, the programmer can designate that the
new class should inherit the members of an existing class. This existing class is called
the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal,
dog IS-A mammal hence dog IS-A animal as well and so on.
Base & Derived Classes:
A class can be derived from more than one classes, which means it can inherit data and
functions from multiple base classes. To define a derived class, we use a class derivation list
to specify the base class(es). A class derivation list names one or more base classes and has
the form:
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the name of
a previously defined class. If the access-specifier is not used, then it is private by default.
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Declare the base class emp.
Step 3: Define and declare the function get() to get the employee details.
Step 4: Declare the derived class salary.
Step 5: Declare and define the function get1() to get the salary details.
Step 6: Define the function calculate() to find the net pay.
Step 7: Define the function display().
Step 8: Create the derived class object.
Step 9: Read the number of employees.
Step 10: Call the function get(),get1() and calculate() to each employees.
Step 11: Call the display().
Step 12: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class base
{
int a;
public:
int b;
void get_ab();
int get_a();
void show();
};
void base::get_ab()
{

26
cout<<"\n Enter the value for a and b:\n";
cin>>a>>b;
}
int base::get_a()
{
return a;
}
void base::show()
{
cout<<"\n\nThe entered values are:\t"<<a<<"\t "<<b;
}
class derived:public base
{
int add;
public:
void cal();
void display();
};
void derived::cal()
{
get_ab();
add=get_a()+b;
}
void derived::display()
{
show();
cout<<"\n\n Addition="<<add;
}
void main()
{
derived D;
D.cal();
D.display();
getch();
}
OUTPUT:
Enter the value for a and b:
20
30
The entered values are: 20 30
Addition=50

Post Lab:
What is inheritance in C++?
What is the use of Inheritance?
Mention the types in inheritance?

27

Result:
Thus the implementation of c ++ program for the operator overloading with friend
function is executed and the output has been verified.
Ex: No: 4(b)
Date :

VIRTUAL FUNCTIONS

Aim:
To write a c ++ program classes with virtual function.
Prerequisite:
If there are member functions with same name in base class and derived class, virtual
functions gives programmer capability to call member function of different class by a same
function call depending upon different context. This feature in C++ programming is known as
polymorphism which is one of the important feature of OOP. If a base class and derived class
has same function and if you write code to access that function using pointer of base class
then, the function in the base class is executed even if, the object of derived class is
referenced with that pointer variable.
In C++, virtual methods are declared by prepending the virtual keyword to the
function's declaration in the base class. This modifier is inherited by all implementations of
that method in derived classes, meaning that they can continue to over-ride each other and be
late-bound.
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Declare the base class base.
Step 3: Declare and define the virtual function show().
Step 4: Declare and define the function display().
Step 5: Create the derived class from the base class.
Step 6: Declare and define the functions display() and show().
Step 7: Create the base class object and pointer variable.
Step 8: Call the functions display() and show() using the base class object and pointer.
Step 9: Create the derived class object and call the functions display() and show() using the
derived class object and pointer.
Step 10: Stop the program.
Program
#include<iostream.h>
#include<conio.h>
class base
{
public:
virtual void show()
{
cout<<"\n Show base";
}
void display()
{
cout<<"\n Display base";
}
};
class derived:public base
{
public:
void show()
{

28
cout<<"\n\n Show derived";
}
void display()
{
cout<<"\n\n display derived";
} };
void main()
{
derived D;
base B;
clrscr();
base *p;
p=&B;
p->show();
p->display();
p=&D;
p->show();
p->display();
getch();
}
OUTPUT:
Show base
Display base
Show derived
Display base

Post lab:
What is meant by virtual functions?
What is the use of using it?
How it Works?

29

Result:
Thus the implementation of c ++ program for the operator overloading with friend
function is executed and the output has been verified.
Ex: No: 4(c)
Date :

VIRTUAL BASE CLASSES

Aim:
To write a c ++ program classes with virtual base class.
Prerequisite:
An ambiguity can arise when several paths exist to a class from the same base class.
This means that a child class could have duplicate sets of members inherited from a single
base class. C++ solves this issue by introducing a virtual base class. When a class is made
virtual, necessary care is taken so that the duplication is avoided regardless of the number of
paths that exist to the child class. When two or more objects are derived from a common base
class, we can prevent multiple copies of the base class being present in an object derived
from those objects by declaring the base class as virtual when it is being inherited. Such a
base class is known as virtual base class. This can be achieved by preceding the base class
name with the word virtual.
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Declare the base class student.
Step 3: Declare and define the functions getnumber() and putnumber().
Step 4: Create the derived class test virtually derived from the base class student.
Step 5: Declare and define the function getmarks() and putmarks().
Step 6: Create the derived class sports virtually derived from the base class student.
Step 7: Declare and define the function getscore() and putscore().
Step 8: Create the derived class result derived from the class test and sports.
Step 9: Declare and define the function display() to calculate the total.
Step 10: Create the derived class object obj.
Step 11: Call the function get number(),getmarks(),getscore() and display().
Step 12: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class student
{
protected:
int rollno;
public:
void get_roll();
void put_roll();
};
void student::get_roll()
{
cout<<"\n Enter the Rollno:\t";
cin>>rollno;
}
void student::put_roll()
{
cout<<"\n The Rollno is:\t"<<rollno;
}
class subject:virtual public student

30
{
protected:
int sub1,sub2;
public:
void get_sub();
void put_sub();
};
void subject::get_sub()
{
cout<<"\n Enter the subject marks:\t";
cin>>sub1>>sub2;
}
void subject::put_sub()
{
cout<<"\n\n Marks scored in Subjects:\t";
cout<<sub1<<"\t"<<sub2<<"\n";
}
class sports:public virtual student
{
protected:
int spo;
public:
void get_spo();
void put_spo();
};
void sports::get_spo()
{
cout<<"\n Enter the sports marks:\t";
cin>>spo;
}
void sports::put_spo()
{
cout<<"\n Marks scored in Sports:\t"<<spo<<"\n";
}
class result:public subject,public sports
{
int res;
public:
void input();
void calculate();
void output();
};
void result::input()
{
get_roll();
get_sub();
get_spo();
}
void result::calculate()
{
res=sub1+sub2+spo;
}
void result::output()
{
put_roll();
put_sub();
put_spo();
cout<<"\n Total Result:\t"<<res;
}

31
void main()
{
result R;
clrscr();
R.input();
R.calculate();
R.output();
getch();
}
OUTPUT:
Enter the Rollno:
5072
Enter the subject marks:
80
Enter the sports marks:
75
The Rollno is: 5072
Marks scored in Subjects:
80
Marks scored in Sports:
75
Total Result: 235
Postlab:

80
80

What is a virtual base class?


What is Virtual base class? Explain its uses.

32

Result:
Thus the implementation of c ++ program for the virtual base class is executed and the
output has been verified.
Ex: No: 4(c)
Date :

Templates

Aim:
To write a c ++ program classes with templates
Prerequisite:
Templates are the foundation of generic programming, which involves writing code in a way
that is independent of any particular type. A template is a blueprint or formula for creating a
generic class or a function. The library containers like iterators and algorithms are examples
of generic programming and have been developed using template concept.
The general form of a template function definition is shown here:
template <class type> ret-type func-name(parameter list)
{
// body of function
}
Here, type is a placeholder name for a data type used by the function. This name can be used
within the function definition.
Prelab:
Algorithm:
STEP 1: Start the program.
STEP 2: Declare the template class.
STEP 3: Declare and define the functions to swap the values.
STEP 4: Declare and define the functions to get the values.
STEP 5: Read the values and call the corresponding functions.
STEP6: Display the results.
STEP 7: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
template<class T>
void swap(T &x,T &y)
{
T temp = x;
x = y;
y = temp;
}
void fun(int m,int n, float a,float b)
{
cout<<"m and n before swap : "<<m<<" "<<n<<"\n";
swap(m,n);
cout<<"m and n after swap : "<<m<<" "<<n<<"\n";
cout<<"a and b before swap : "<<a<<" "<<b<<"\n";
swap(a,b);
cout<<"a and b after swap : "<<a<<" "<<b<<"\n";
}
void main()
{
clrscr();
fun(100,200,11.22,33.44);

33
getch();
}

OUTPUT:
m and n before swap : 100
200
m and n after swap : 200 100
a and b before swap : 11.22 33.439999
a and b after swap : 33.439999 11.22

Postlab:
What is template class?
What is a template function?
What is the use of it?

34

Result:
Thus the implementation of c ++ program for the template is executed and the output
has been verified.
Ex: No: 5(a)
Date :

SEQUENTIAL ACCESS

Aim:
To write a c ++ program file handling using sequential acess.
Prerequisite:
To perform file processing in C++, header files <iostream> and <fstream> must be
included in your C++ source file. This data type represents the file stream generally, and has
the capabilities of both ofstream and ifstream which means it can create files, write
information to files, and read information from files.
Writing to a File:
While doing C++ programming, you write information to a file from your program
using the stream insertion operator (<<) just as you use that operator to output information to
the screen. The only difference is that you use an ofstream or fstream object instead of
the cout object.
Reading from a File:
You read information from a file into your program using the stream extraction
operator (>>) just as you use that operator to input information from the keyboard. The only
difference is that you use an ifstreamor fstream object instead of the cin object.
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Declare the variables.
Step 3: Read the file name.
Step 4: open the file to write the contents.
Step 5: writing the file contents up to reach a particular condition.
Step 6: Stop the program
Programm
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<iomanip.h>
class INVENTORY
{
char name[10];
int code;
float cost;
public:
void readdata(void);
void writedata(void);
};
void INVENTORY::readdata(void)
{
cout<<"Enter name: ";
cin>>name;
cout<<"Enter code: ";
cin>>code;
cout<<"Enter cost: ";

35
cin>>cost;
}
void INVENTORY::writedata(void)
{
cout<<setiosflags(ios::left)<<setw(10)<<name<<setiosflags(ios::right)<<setw(10)<<code
<<setprecision(2)<<setw(10)<<cost<<endl;
}
void main()
{
clrscr();
INVENTORY item[3];
fstream file;
file.open("STOCK.DAT",ios::in|ios::out);
cout<<"ENTER DETAILS FOR THREE ITEMS\n";
for(int i=0;i<3;i++)
{
item[i].readdata();
file.write((char *)&item[i],sizeof(item[i]));
}
file.seekg(0);
cout<<"\nOUTPUT\n\n";
for(i=0;i<3;i++)
{
file.read((char *)&item[i],sizeof(item[i]));
item[i].writedata();
}
file.close();
getch();
}
OUTPUT:
ENTER DETAILS FOR THREE ITEMS
Enter name:C++
Enter code:101
Enter cost:175
Enter name:FORTRAN
Enter code:102
Enter cost:150
Enter name:JAVA
Enter code:115
Enter cost:225
C++
101
175
FORTRAN
102
150
JAVA
115
225
Post lab:
What is the namespace required for file handling in C++?
How declare a file handling in c++?
How to read a file?
How to write a file?

36

Result:
Thus the implementation of c ++ program for the sequential access is executed and the
output has been verified.

37

Ex: No: 5(b)


Date :

RANDOM ACCESS

Aim:
To write a c ++ program file handling using random access.
Prerequisite:
Using file streams, we can randomly access binary files. By random access, you can go to
any position in the file as you wish (instead of going in a sequential order from the first
character to the last). Earlier in this chapter we discussed about a bookmarker that will keep
moving as you keep reading a file. This bookmarker will move sequentially but you can also
make it move randomly using some functions. Technically this bookmarker is a file pointer
and it determines as to where to write the next character (or from where to read the next
character). We have seen that file streams can be created for input (ifstream) or for output
(ofstream). For ifstream the pointer is called as get pointer and for ofstream the pointer is
called as put pointer. fstream can perform both input and output operations and hence it has
one get pointer and one put pointer. The get pointer indicates the byte number in the file
from where the next input has to occur. The put pointer indicates the byte number in the file
where the next output has to be made. There are two functions to enable you move these
pointers in a file wherever you want to:
seekg ( ) - belongs to the ifstream class
seekp ( ) - belongs to the ofstream class
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Declare the variables.
Step 3: Read the file name.
Step 4: open the file to write the contents.
Step 5: writing the file contents up to reach a particular condition.
Step 6: Stop the program
Program:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<iomanip.h>
class INVENTORY
{
char name[10];
int code;
float cost;
public:
void getdata(void)
{
cout<<"Enter name: ";
cin>>name;
cout<<"Enter code: ";
cin>>code;
cout<<"Enter cost: ";
cin>>cost;
}
void putdata(void)
{
cout<<setw(10)<<name<<setw(10)<<code<<setprecision(2)<<setw(10)<<cost<<endl;
}
};

38
void main()
{
clrscr();
INVENTORY item;
fstream inoutfile;
inoutfile.open("STOCK.DAT",ios::ate|ios::in|ios::out|ios::binary);
inoutfile.seekg(0,ios::beg);
cout<<"CURRENT CONTENTS OF STOCK\n";
while(inoutfile.read((char*)&item,sizeof item))
{
item.putdata();
}
inoutfile.clear();
cout<<"\nADD AN ITEM\n";
item.getdata();
char ch;
cin.get(ch);
inoutfile.write((char *)&item,sizeof item);
inoutfile.seekg(0);
cout<<"CONTENTS OF APPENDED FILE\n";
while(inoutfile.read((char *)&item,sizeof item))
{
item.putdata();
}
int last=inoutfile.tellg();
int n=last/sizeof(item);
cout<<"Number of objects = "<<n<<"\n";
cout<<"Total bytes in the file = "<<last<<"\n";
cout<<"Enter object number to be updated : ";
int object;
cin>>object;
cin.get(ch);
int location = (object-1)*sizeof(item);
if(inoutfile.eof())
inoutfile.clear();
inoutfile.seekp(location);
cout<<"Enter new values of the object\n";
item.getdata();
cin.get(ch);
inoutfile.write((char *)&item,sizeof item)<<flush;
inoutfile.seekg(0);
cout<<"CONTENTS OF UPDATED FILE\n";
while(inoutfile.read((char *)&item,sizeof item))
{
item.putdata();
}
inoutfile.close();
getch();
}
OUTPUT:
CURRENT CONTENTS OF STOCK
AA 11 100
BB 22 200
CC 33 300
DD 44 400
XX 99 900
ADD AN ITEM

39
Enter name:YY
Enter code:10
Enter cost:101
CONTENTS OF APPENDED FILE
AA 11 100
BB 22 200
CC 33 300
DD 44 400
XX 99 900
YY 10 101
Number of objects = 6
Total bytes in the file = 96
Enter object number to be updated : 6
Enter new values of the object
Enter name:ZZ
Enter code:20
Enter cost:201
CONTENTS OF UPDATED FILE
AA 11 100
BB 22 200
CC 33 300
DD 44 400
XX 99 900
YY 10 101
ZZ 20 201

Postlab:
How to randomly access a file in C++?
What are all the functions required for move the pointers to fstream.

Result:
Thus the implementation of c ++ program for the random access is executed and the
output has been verified.

40

Ex: No: 6(a)


Date :

Simple Java Applications For Understanding References To An


Instant Of A Class

Aim:
To write a JAVA program to implement the instant of a class.
Prerequisite:
The instanceof operator has this general form:
object instanceof type
Here, object is an instance of a class, and type is a class type. If object is of the specified type
or can be cast into the specified type, then the instanceof operator evaluates to true.
Otherwise, its result isfalse. Thus, instanceof is the means by which your program can obtain
run-time type information about an object
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Declare n=10 and find the sum of 10 numbers.
Step 3: Initialize s=0.
Step 4: For i value from 1 to 10 repeat the process by using for loop.
Step 5: Display the loop.
Step 6: Stop the program.
Program:
class Area
{
int l,b;
Area(int x,int y)
{
l=x;
b= y;
}
int Result()
{
return l*b;
}
}
class Rectangle
{
public static void main(String args[])
{
Area A=new Area(10,5);
System.out.println("The Area of the Rectangle is : \t"+ A.Result());
}
}
OUTPUT :
The Area of the Rectangle is :

50

Post lab:
What is instance of class in java?
Why we need instance of class?
Result:
Thus the implementation of JAVA program for the sum of n numbers is executed and
the output has been verified.

41

Ex: No: 6(b)


Date:

Simple Java Applications For handling strings

Aim:
To write a JAVA program to implement. Java Applications For handling strings
Prerequisite:
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. Java String is a powerful concept because everything is
treated as a string if you submit any form in window based, web based or mobile application.
There are two ways to create String object:
1. By string literal
2. By new keyword
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Create class multi table and declare the variable column and row.
Step 3: For the row value for 1 to 10 repeat the step 4 and 5.
Step 4: For column value from the 1 to 10 repeat the step 5.
Step 5: Multiply row and column.
Step 6: Print the output data y.
Step 7: Stop the program.
Program:
public class StringOrdering
{
Static String name[]={"CHENNAI","TIRUNELVELI","DELHI","BOMBAY","CALCUTTA"};
public static void main(String args[])
{
int size=name.length;
String temp=null;
System.out.println("\n........Before Sorting.......\n");
for(int i=0;i<size;i++)
{
System.out.println(name[i]);
}
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(name[j].compareTo(name[i])<0)
{
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
System.out.println("\n.........After Sorting........\n");
for(int i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
}

42
OUTPUT :
........Before Sorting.......
CHENNAI
TIRUNELVELI
DELHI
BOMBAY
CALCUTTA
.........After Sorting........
BOMBAY
CALCUTTA
CHENNAI
DELHI
TIRUNELVELI

Post Lab:
How to create a string object?
What is the package required for string handling in java?

Result:
Thus the implementation of JAVA program for the sum of n numbers is executed and
the output has been verified

43

.
Ex: No: 7

Simple Package Creation Developing User Defined packages In Java

Date :

Aim:
To write a JAVA programs to implement designing package with JAVA package .
Prerequisite:
Packages in Java are a way of grouping similar types of classes / interfaces together. It is a
great way to achieve reusability. We can simply import a class providing the required
functionality from an existing package and use it in our program. A package basically acts as
a container for group of related classes. The concept of package can be considered as means
to achieve data encapsulation. A package may consists of a lot of classes but only few needs
to be exposed as most of them are required internally. Thus, we can hidethe classes and
prevent programs or other packages from accessing classes which are meant for internal
usage only.
Packages are categorized as :
1 ) Built-in packages ( standard packages which come as a part of Java Runtime
Environment )
2 ) User-defined packages ( packages defined by programmers to bundle group of related
classes )
Suppose, we want to create a package namedrelational which contains a class
named Compare. First, we will create a directory named relational ( the name should be
same as the name of the package ). Then create the Compare class with the first statement
being package relational;. Now, the package is ready to be imported.
We can add a class to an existing package by using the package name at the top of the
program as shown above and saving the .java file under the package directory. We need a
new java file if we want to define a public class, otherwise we can add the new class to an
existing java file and recompile it.
Prelab:
Algorithms:
Step 1: Start the program.
Step 2: Create a package called name which contains the class addition with
member function to perform addition operation.
Step 3: Impact the created package in the main class.
Step 4: From the main class make a function call to the package.
Step 5: Display the resultant values.
Step 6: Stop the program.
Programs:
classA.java
package package1;
public class classA
{
public void displayA()
{
System.out.println("class A");
}
}
classB.java
package package2;
public class classB
{
protected int m=100;
public void displayB()
{
System.out.println("class B");

44
System.out.println("m = "+m);

}
PackageTest.java
import package1.*;
import package2.*;
class PackageTest
{
public static void main(String a[])
{
classA objA = new classA();
classB objB = new classB();
objA.displayA();
objB.displayB();
}
}
OUTPUT :
class A
class B
m = 100

Post lab:
What is package?
Mention the most used packages in java?
How used defined package is created and used?
What are all the built in packages?

Result:
Thus the implementation of JAVA program for package is executed and the output has
been verified.

45

Ex: No: 8

SIMPLE PACKAGE CREATION FOR DEVELOPING INTERAFCAE

Date :
Aim:
To write a JAVA programs for interface and inheritance.
Prerequisite:
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 inheritances in Java. Java Interface also represents IS-A relationship. It cannot be
instantiated just like abstract class. The interface keyword is used to declare an interface.
Prelab:
Algorithm:
Step 1: Start the programs.
Step 2: Create and interface named sports which contains member function.
Step 3: Created three classes are inherited.
Step 4: Created an object for the class result.
Step 5: With respect to create object make a function call to the function on other
classes including interface.
Step 6: Stop the program.
Programs:
Interface.java
interface Area
{
final static float PI=(float) 3.14;
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);
}
}
public class Interface
{
public static void main(String[] J)
{
Rectangle rec=new Rectangle();
circle cir=new circle();
Area area;
area=rec;
System.out.println("Area of the Rectangle = "+area.compute(10,20));
area=cir;
System.out.println("Area of the Circle = "+area.compute(10,0));
}

46
}
OUTPUT :
Area of the Rectangle = 200.0
Area of the Circle = 314.0

Post lab:

How to achieve inheritance in java?


What is the use of interface in java?
What is the syntax for implementing interfaces in java?

Result:

47

Thus the implementation of JAVA program for interface is executed and the output
has been verified.
Ex: No: 9(a)
Date :

CREATION OF THREADING IN JAVA APPLICATIONS

Aim:
To write a JAVA programs for creation of threading in java applications
Prerequisite:
Java is multithreaded programming language which means we can develop
multithreaded program using Java. A multithreaded program contains two or more parts that
can run concurrently and each part can handle different task at the same time making optimal
use of the available resources specially when your computer has multiple CPUs.
By definition multitasking is when multiple processes share common processing
resources such as a CPU. Multithreading extends the idea of multitasking into applications
where you can subdivide specific operations within a single application into individual
threads. Each of the threads can run in parallel. The OS divides processing time not only
among different applications, but also among each thread within an application.
Multithreading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
Creating a thread in Java is done like this:
Thread thread = new Thread();
To start the thread you will call its start() method, like this:
thread.start();
Prelab:
Algorithm:
Step 1: Start the program.
Step 2: Create the thread class.
Step 3: Create the main class thread.
Step 4: Create the memory space.
Step 5: Execute the program.
Step 6: Display the output.
Step 7: Stop the program
Program:
import java.io.*;
public class csj01x1
{
public static void main(String args[]) throws Throwable
{
new csj01x1().myfunc();
}
void myfunc() throws Throwable
{
for (int i=0; i<100; i++) {
System.out.println("thread "
+Thread.currentThread().getName()+" step "+i);
Thread.sleep(500);
} }}
OUTPUT:
Postlab:
How to achieve multitasking?
Mention the use of thread?
Mention the life cycle of a thread?
Result:

48

Thus the implementation of JAVA program for creation of thread is executed and the
output has been verified.

Ex: No: 9(b)


Date :

DESIGN MULTITHREAD PROGRAM IN JAVA

Aim:
To write a JAVA programs to implement the design multithread program.
Prerequisite:
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. But we use multithreading than
multiprocessing because threads share a common memory area. They don't allocate separate
memory area so saves memory, and context-switching between the threads takes less time
than process. Java Multithreading is mostly used in games, animation etc.
A thread can be created in two ways:
1)By extending Thread class
2) By implementing Runnable interface.
Before we learn how to create the thread. Lets have a look at the methods that helps in
managing the threads.
getName(): It is used for Obtaining a threads name
getPriority(): Obtain a threads 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
Algorithm:
Step 1: Start the program.
Step 2: Create the thread class.
Step 3: Create the main class thread.
Step 4: Create the memory space.
Step 5: Execute the program.
Step 6: Display the output.
Step 7: Stop the program
Program:
import java.lang.Thread;
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
if(i==1)yield();
System.out.println("\tFrom Thread A : i="+i);
}
System.out.println("Exit From A");
}
}
class B extends Thread
{
public void run()
{

49
for(int j=1;j<=5;j++)
{
System.out.println("\tFrom Thread B : j="+j);
if(j==3)stop();
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("\tFrom Thread C : k="+k);
if(k==1)
try
{sleep(1000);}
catch(Exception e)
{}}
System.out.println("Exit from C");
}}
class MultiThread
{public static void main(String args[])
{A threadA=new A();
B threadB=new B();
C threadC=new C();
System.out.println("Start thread A");
threadA.start();
System.out.println("Start thread B");
threadB.start();
System.out.println("Start thread C");
threadC.start();
System.out.println("End of main thread");
}}
OUTPUT:
Start thread A Start thread B Start thread C
End of main thread
From Thread B : j=1
From Thread B : j=2
From Thread B : j=3
From Thread C : k=1
From Thread A : i=1
From Thread A : i=2
From Thread A : i=3
From Thread A : i=4
From Thread A : i=5
Exit From A
From Thread C : k=2
From Thread C : k=3
From Thread C : k=4
From Thread C : k=5
Exit from C
Post lab:
What is multithreading?

Use of multithreading?

50

Result:
Thus the implementation of JAVA program for design multithread program is executed
and the output has been verified.

Ex: No: 10(a)


Date :

PRE-DEFINED EXCEPTIONS HANDLING IN JAVA

Aim:
To write a java program to implement the exception handling.
Prerequisite:
An exception is a problem that arises during the execution of a program. An exception can
occur for many different reasons, including the following:
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.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three
categories of exceptions:
Checked exceptions: A checked exception is an exception that is typically a user
error or a problem that cannot be foreseen by the programmer. For example, if a file is
to be opened, but the file cannot be found, an exception occurs. These exceptions
cannot simply be ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably
could have been avoided by the programmer. As opposed to checked exceptions,
runtime exceptions are ignored at the time of compilation.
Errors: These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer. Errors are typically ignored in your code because you can
rarely do anything about an error. For example, if a stack overflow occurs, an error
will arise. They are also ignored at the time of compilation.
We have try, catch and finally block in exception handling.
Algorithm:
Step 1: Start the programs.
Step 2: Include the import statement.
Step 3: Declare the main class method.
Step 4: Declare the class and definite them.
Step 5: In that through a exception in the try.
Step 6: The exception will be caught by the catch block.
Step 7: Stop the program.
Program:
Exception.java
public class Exception
{
public static void main(String args[])
{
int a[]={5,10};

51

int b=5;
try
{
int x;
x=a[2]/a[1];
}
catch(ArithmeticException e)
{ System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Error");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}
int y=a[1]/a[0];
System.out.println("y = "+y);
}
}
OUTPUT :
Array Index Error
y=2
Post lab:
What is the use of exception handling?
What is the work of catch, try block?

52

Result:
Thus the implementation of JAVA program for design of pre-defined exceptions
handling in java is executed and the output has been verified.

53

Ex: No: 10(b)


Date :

USER-DEFINED EXCEPTIONS HANDLING IN JAVA

Aim:
To write a java program to implement the exception handling.
Prerequisite:
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.
Algorithm:
Step 1: Start the programs.
Step 2: Include the import statement.
Step 3: Declare the main class method.
Step 4: Declare the class and definite them.
Step 5: In that through a exception in the try.
Step 6: The exception will be caught by the catch block.
Step 7: Stop the program.
Exception.java
import java.lang.Exception.*;
class MyException extends Exception
{
MyException(String message)
{
super(message);}}
class TestMyException
{public static void main(String args[])
{int x=5,y=100;
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:
Caught my Exception
Number is too small
I am always here
Postlab:
How to create a user defined exception handling?
How it works?

Result:
Thus the implementation of JAVA program for design of user-defined exceptions
handling in java is executed and the output has been verified.

S-ar putea să vă placă și