ECE 101 Introduction to Electrical and Computer Engineering Lab ...
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING LAB MANUAL ... · PDF fileCS1031/OOPS Lab...
Transcript of DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING LAB MANUAL ... · PDF fileCS1031/OOPS Lab...
CS1031/OOPS Lab CSE/SRM 1/57
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
LAB MANUAL
Academic Year: 2015-16 ODD SEMESTER
Programme (UG/PG) : UG
Semester : III
Course Code : CS1031
Course Title : OBJECT ORIENTED PROGRAMMING LAB
Prepared By
Mrs.G.Vijayalakshmi (Assistant Professor (O.G), Department of Computer Science and Engineering)
FACULTY OF ENGINEERING AND TECHNOLOGY
SRM UNIVERSITY (Under section 3 of UGC Act, 1956)
SRM Nagar, Kattankulathur- 603203
Kancheepuram District
CS1031/OOPS Lab CSE/SRM 2/57
LIST OF EXPERIMENTS & SCHEDULE
Course Code: CS1031 Course Title: OOPS Lab
Exp. No. Title Week No.
C++
1.A. STATIC MEMBER VARIABLES 1
1.B. DEFAULT ARGUMENTS 1
2.A CONSTRUCTORS AND DESTRUCTORS 2
2.B. OPERATOR OVERLOADING 3
3.A. SINGLE INHERTANCE 4
3.B. HYBRID INHERITANCE 5
4.A. VIRTUAL FUNCTIONS 6
4.B. DYNAMIC POLYMORPHISM 6
5.A. EXCEPTION HANDLING IN STACKS 7
5.B. EXCEPTION HANDLING IN QUEUE 7
Course Coordinator HoD
CS1031/OOPS Lab CSE/SRM 3/57
LIST OF EXPERIMENTS & SCHEDULE
Course Code: CS1031 Course Title: OOP Lab
Exp. No. Title Week No.
JAVA
1.A. TYPE CASTING 1
1.B. METHOD OVERLOADING 1
2. MULTI LEVEL INHERITANCE 2
3. DYNAMIC MEMORY DISPATCH AND
METHOD OVERRIDING
3
4. CREATION OF PACKAGES 4
5. IMPLEMENTING INTERFACES 5
6. STRING MANIPULATION 6
7. MULTITHREADING IN JAVA 6
8. JAVA APPLET 7
Course Coordinator HoD
CS1031/OOPS Lab CSE/SRM 4/57
HARDWARE AND SOFTWARE REQUIREMENTS
Hardware Requirements:
RAM – 1 GB
Processor – Dual core
Software Requirements:
Operating System – Windows 7
Tool – JDK 1.6
CS1031/OOPS Lab CSE/SRM 5/57
Internal Assessment Mark Split Up
Observation : 20 Marks
Attendance : 5 Marks
Mini Project with the Report
(Max. 8 Pages & 3 Students per Batch) : 20 Marks
Model Exam : 15 Marks
TOTAL MARKS : 60 Marks
CS1031/OOPS Lab CSE/SRM 6/57
STATIC VARIABLE
Exp. No: 1.A
i. OBJECTIVE:
To write a C++ program to illustrate the static variable functionality using sum of a Fibonacci series
as an example.
ii. ALGORITHM:
STEP 1: Create a class with a static variable
STEP 2: This class will contain a method which will increase the value of this static variable.<and this
method is a recursive function>.
STEP 3: Use scope resolution operator and increase the scope of the variable.
STEP 4: Create an object of this class in main.
STEP 5: Call this method
iii. SOURCE CODE :
#include<iostream.h>
class item
{
public:
static int sum;
void fibo(int f,int s)
{
if(s>100)
cout<<"Sum="<<sum<<endl;
else
{
sum+=s;
fibo(s,f+s);
}
}
};
int item::sum;
int main()
{
item a;
a.sum=1;
CS1031/OOPS Lab CSE/SRM 7/57
a.fibo(1,1);
return 0;
}
iv. SAMPLE INPUTS & OUTPUTS:
RESULT :
The program was successfully compiled & executed, and the output was verified.
CS1031/OOPS Lab CSE/SRM 8/57
DEFAULT ARGUMENTS
Exp. No: 1.B
i. OBJECTIVE:
To write a C++ program to demonstrate default arguments with a simple example.
ii. ALGORITHM:
STEP 1: Include the Header file.
STEP 2: Create a function which takes in three arguments of which one is a preset default argument.
STEP 3: Now call this function and while calling this pass in 2 arguments rather than 3.
STEP 4: The default argument is already set.
STEP 5: The function will execute without showing any error.
iii. SOURCE CODE :
#include<iostream.h>
int main()
{
float amount;
float value(float p,int n,float r=0.15);
amount=value(500.00,5);
cout<<"\nFinal Value="<<amount<<"\n";
amount=value(1000.00,5,0.30);
cout<<"\nFinal Value="<<amount<<"\n";
return 0;
}
float value(float p,int n,float r)
{
int year=1;
float sum=p;
while(year<=n)
{
sum*=(1+r);
year+=1;
}
return sum;
}
CS1031/OOPS Lab CSE/SRM 9/57
iv. SAMPLE INPUTS & OUTPUTS:
Final value=1005.68
Final value=3712.93
RESULT :
The program was successfully compiled & executed, and the output was verified.
v. Few (Min. 5) Questions related to the next Experiment:
1. What is a constructor?
2. What is Copyconstructor?
3. What is a Destructor?
CS1031/OOPS Lab CSE/SRM 10/57
4. What are the rules in defining Constructor?
5. What is overloading?
CONSTRUCTOR AND DESTRUCTOR (Dynamic memory allocation)
Exp. No: 2.A
i. OBJECTIVE:
To write a C++ program to demonstrate the use of constructors and destructors .
ii. ALGORITHM:
Step 1: Create a class
Step 2: Create a constructor for this class which will set the value of its member variables.
Step 3: Create the other required methods for the given class
Step 4: Define the destructor.
Step 5: Create an object of this class
Step 6: The constructor will be called upon creation and when the program is ending the destructor will be called.
iii. SOURCE CODE :
#include<iostream.h>
class Arr
{
int m,n;
int **a;
public:
Arr(int x,int y);
Arr(Arr &c){a=c.a;m=c.m;n=c.n;}
void getd();
void shd();
~Arr()
{delete a;}
};
Arr::Arr(int x,int y)
{
m=x;
n=y;
a=new int*[m];
for(int i=0;i<m;i++)
a[i]=new int[n];
}
CS1031/OOPS Lab CSE/SRM 11/57
void Arr::getd()
{
int j;
cout<<"\nEnter the matrix elements:";
for(int i=0;i<m;i++)
for(j=0;j<n;j++)
cin>>a[i][j];
}
void Arr::shd()
{
int j;
cout<<"\n\nMatrix elements:\n";
for(int i=0;i<m;i++){
for(j=0;j<n;j++)
cout<<a[i][j]<<" ";
cout<<endl;}
}
int main()
{
int m,n;
cout<<"Enter the size of matrix needed:";
cin>>m>>n;
Arr t(m,n),s(t);
cout<<"By help of constructor:";
t.getd();
t.shd();
cout<<"By help of copy constructor:";
s.shd();
s.getd();
s.shd();
return 0;
}
iv. SAMPLE INPUTS & OUTPUTS:
Enter the size of matrix needed: 2 2
By help of constructor:
Enter the matrix elements:
1 2
CS1031/OOPS Lab CSE/SRM 12/57
3 4
Matrix Elements
1 2
3 4
By help of copy constructor:
Matrix Elements
1 2
3 4
Enter the matrix elements:
1 2
3 4
Matrix Elements
2 2
3 4
CS1031/OOPS Lab CSE/SRM 13/57
v. RESULT :
The program was successfully compiled & executed, and the output was verified.
OPERATOR OVERLOADING
Exp. No: 2.B
i. OBJECTIVE:
To write a C++ program to illustrate the operator overloading concept using Matrix addition as an
example.
ii. ALGORITHM:
Step 1: Create a class ’matrix’ with constructor that sets the value of its member variables.
Step 2: This class also overloads the + and = operator with proper operator overloaded functions.
Step 3: Define the operators.
Step 4: Create the object of this class and call these overloaded functions.
iii. SOURCE CODE :
#include<iostream.h>
class Matrix
{
public:
float row,col;
float **arr;
Matrix();
Matrix(float,float);
int inputDim(float,float);
int getMatrix();
Matrix operator+(Matrix);
Matrix operator=(Matrix&);
};
int Matrix::getMatrix()
{
for(int i=0;i<row;i++)
CS1031/OOPS Lab CSE/SRM 14/57
for(int j=0;j<col;j++)
cin>>arr[i][j];
return 0;
}
Matrix::Matrix(float r,float c)
{
row=r;
col=c;
arr=new float*[row];
for(int i=0;i<row;i++)
arr[i]=new float[col];
}
Matrix::Matrix()
{row=col=0;
arr=NULL;}
int Matrix::inputDim(float r,float c)
{
row=r;
col=c;
arr=new float*[row];
for(int i=0;i<row;i++)
arr[i]=new float[col];
return 0;
}
Matrix Matrix::operator+(Matrix m)
{
Matrix t;
t.inputDim(m.row,m.col);
for(int i=0;i<m.row;i++)
for(int j=0;j<m.col;j++)
t.arr[i][j]=arr[i][j]+m.arr[i][j];
return t;
}
Matrix Matrix::operator=(Matrix &m)
{
for(int i=0;i<m.row;i++)
for(int j=0;j<m.col;j++)
arr[i][j]=m.arr[i][j];
return *this;
}
CS1031/OOPS Lab CSE/SRM 15/57
int main()
{
int r,c;
int getDimension(int &r,int &c);
int showResult(Matrix);
cout<<"\nEnter the matrix size of A\n";
getDimension(r,c);
Matrix a(r,c);
cout<<"\nEnter the matrix A\n";
a.getMatrix();
cout<<"\nEnter the matrix size of B\n";
getDimension(r,c);
Matrix b(r,c);
cout<<"\nEnter the matrix B\n";
b.getMatrix();
if(a.row==b.row && a.col==b.col)
{
Matrix x(r,c);
x=a+b;
cout<<"\nMatrix A:\n";
showResult(a);
cout<<"\nMatrix B:\n";
showResult(b);
cout<<"\nResultant Matrix:\n";
showResult(x);
}
else
cout<<"\nAddition not possible\n";
return 0;
}
int getDimension(int &r,int &c)
{
cout<<"\nEnter row and column:\n";
cin>>r>>c;
return 0;
}
int showResult(Matrix x)
{
for(int i=0;i<x.row;i++){
for(int j=0;j<x.col;j++)
cout<<x.arr[i][j]<<" ";
CS1031/OOPS Lab CSE/SRM 16/57
cout<<"\n";}
return 0;
}
iv. SAMPLE INPUTS & OUTPUTS:
Enter the matrix size of A:
Enter rows & columns 2 2
Enter the matrix A:
1 1 1 1
Enter the matrix size of B:
Enter rows & columns 2 2
Enter the matrix B:
1 1 1 1
Matrix A: 1 1 1 1
Matrix B: 1 1 1 1
Resultant Matrix:
2 2
2 2
RESULT :
The program was successfully compiled & executed, and the output was verified.
CS1031/OOPS Lab CSE/SRM 17/57
v. Few (Min. 5) Questions related to the next Experiment:
1. Define inheritance?
2. What is access specifier?
3. Which is the default access specifier in C++?
4. Difference between multiple and multilevel inheritance?
5. Advantages of using inheritance?
SINGLE INHERITANCE USING BANKING SYSTEM
Exp. No: 3.A
i. OBJECTIVE:
To write a C++ program to illustrate the single inheritance using banking system as an example.
ii. ALGORITHM:
STEP 1: Include the Header file.
STEP 2: Create a forward declaration of a class.
STEP 3:Create a new class that has certain member functions and methods.
STEP 4:Create the class earlier defined in step 2 and Create it inherit from the class in step 2 using the
resolution : operator
STEP 5: Now create an object of the sun class and Create it call some methods you defined in sgtep 2.
iii. SOURCE CODE :
#include<iostream.h>
class sav_acct
class account
{
char cust_name[20];
int acc_no;
char acc_type[20];
public:
int get_accinfo()
{
cout<<"\n\nEnter customer name:-";
cin>>cust_name;
cout<<"\n\nEnter Account no:-";
CS1031/OOPS Lab CSE/SRM 18/57
cin>>acc_no;
cout<<"\n\nEnter Account type:-";
cin>>acc_type;
return 0;
}
int display_accinfo()
{
cout<<"\n\nCustomer Name:-"<<cust_name;
cout<<"\n\nAccount Number:-"<<acc_no;
cout<<"\n\nAccount Type:-"<<acc_type;
return 0;
}
};
class sav_acct:public account
{
static float savbal;
public:
int disp_savbal()
{
cout<<"\nBalance:-"<<savbal;
return 0;
}
int deposit_savbal()
{
float deposit,interest;
cout<<"\n Enter the amount to Deposit:-";
cin>>deposit;
savbal=savbal+deposit;
interest=(savbal*2)/100;
savbal=savbal+interest;
return 0;
}
void withdraw_savbal()
{
float withdraw;
cout<<"\nBalance:-"<<savbal;
cout<<"\nEnter amount to be withdrawn:-";
cin>>withdraw;
savbal-=withdraw;
if(withdraw>savbal)
{
cout<<"\n\nYou have to take permission for Bank overdraft Facility\n";
CS1031/OOPS Lab CSE/SRM 19/57
savbal+=withdraw;
}
else
cout<<"\nAfter withdrawl your Balance reveals:"<<savbal;
}
};
float sav_acct::savbal;
int main()
{
sav_acct s1;
int choice;
s1.get_accinfo();
while(1)
{
cout<<"\nchoose your choice\n";
cout<<"\n1)Deposit\n";
cout<<"\n2)Withdraw\n";
cout<<"\n3)Display Balance\n";
cout<<"\n4)Display with full details\n";
cout<<"\n5)Exit\n";
cout<<"Enter your choice:-";
cin>>choice;
switch(choice)
{
case 1:s1.deposit_savbal();
break;
case 2:s1.withdraw_savbal();
break;
case 3:s1.disp_savbal();
break;
case 4:s1.display_accinfo();
s1.disp_savbal();
break;
case 5:return(0);
default:cout<<"\n\nEntered choice is invalid";
}
}
return 0;
}
CS1031/OOPS Lab CSE/SRM 20/57
iv. SAMPLE INPUTS & OUTPUTS:
Enter customer name: Ajai
Enter account No: 123
Enter account type: Savings
Choose your choice
1) Deposit
2) withdraw
3) display Balance
4) Display with full details
5) Exit
Enter your Choice: 1
Enter the amount to Deposit 500
Enter your Choice: 1
3
Balance:- 510
Enter your Choice: 5
CS1031/OOPS Lab CSE/SRM 21/57
RESULT :
The program was successfully compiled & executed, and the output was verified.
HYBRID INHERITANCE USING STUDENT DATABASE
Exp. No: 3.B
i. OBJECTIVE:
To write a C++ program to illustrate hybrid inheritance concept using student database creation as an
example.
ii. ALGORITHM:
Step 1:Create a class with some methods and variables.
Step 2:Create a new class that extends this class.
Step 3:Create a new class with some new methods.
Step 4:Create a new class again which inherits from classes defined in step 2 and step 3.
Step 5.Create an object of class defined in step 4 and Create it call methods defined in step 1 and step 3.
iii. SOURCE CODE :
#include<iostream.h>
class tests;
class sports;
class result;
class Student{
protected :int rn;
public:
void get()
{cout<<"\n\nEnter roll no.:";
cin>>rn;}
void put()
{cout<<"\nRoll no.:"<<rn<<endl;
CS1031/OOPS Lab CSE/SRM 22/57
}
};
class tests:public Student
{
protected:
float sub1,sub2;
public:
void get_m()
{cout<<"\nenter marks:";
cin>>sub1>>sub2;}
void put_m()
{
cout<<"\nMarks in subject 1="<<sub1<<endl;
cout<<"\nMarks in subject 2="<<sub2<<endl;
}
};
class sports
{
protected:
char g;
public:
void get_g()
{
cout<<"Enter the grade:";
cin>>g;
}
void put_g()
{
cout<<"\nGrade in sports:"<<g<<endl;
}
};
class result:private tests,private sports
{
public:
void res()
{
get();
get_m();
get_g();
cout<<"\n------\nRESULT\n------\n";
put();
put_m();
CS1031/OOPS Lab CSE/SRM 23/57
put_g();
float total=sub1+sub2;
cout<<"TOTAL="<<total;
}
};
void main()
{
result s1;
s1.res();
}
iv. SAMPLE INPUTS & OUTPUTS:
Enter roll no.:100
Enter Marks: 89 90
Enter the Grade: A
Result
roll no.:100
Marks in subject 1=89
Marks in subject 2=90
Grade in sports: A
Total= 179
CS1031/OOPS Lab CSE/SRM 24/57
RESULT :
The program was successfully compiled & executed, and the output was verified.
v. Few (Min. 5) Questions related to the next Experiment:
1. Define polymorphism?
2. What is virtual function?
3. Difference between function overloading & virtual function?
4. What is use of base class pointer?
5. How to achieve run time polymorphism?
VIRTUAL FUNCTION
Exp. No: 4.A
i. OBJECTIVE:
To write a C++ program to illustrate virtual function implementation.
ii. ALGORITHM:
Step 1:Create a class base with a method marked as virtual.
Step 2:Create a subclass of base called derived and redefine the method defined in step 1.
Step 3:Create an object pointer of type base and Create it point to an object of type base first and call the
methods you had marked as virtual using -> operator.
Step 4: repeat the same steps but by making the pointer point to an object of derived type now.
iii. SOURCE CODE :
#include<iostream.h>
class base
{
public:
void display()
{cout<<"\nDisplay base";}
virtual void show(){cout<<"\nShow base.";}
};
class derived:public base
{
public:
CS1031/OOPS Lab CSE/SRM 25/57
void display(){cout<<"\nDisplay derived";}
void show(){cout<<"\nShow Derived.";}
};
int main()
{
base b;
derived d;
base *bptr;
bptr=&b;
cout<<"\nbptr points to base\n";
bptr->display();
bptr->show();
cout<<"\n\nbptr points to derived.";
bptr=&d;
bptr->display();
bptr->show();
return 0;
}
iv. SAMPLE INPUTS & OUTPUTS:
bptr points to base
Show base
Display base
bptr points to derived
Show derived
Display derived
CS1031/OOPS Lab CSE/SRM 26/57
RESULT :
The program was successfully compiled & executed, and the output was verified.
DYNAMIC POLYMORPHISM
Exp. No: 4.B
i. OBJECTIVE:
To write a C++ program to illustrate dynamic polymorphism using different shapes as an example.
ii. ALGORITHM:
Step 1:Make a class area which has a method.
Step 2:Make subclasses to this which have constructors that will take in the value for the required
fields and will compute the area and put it in one of the member variables.
Step 3:call the method defined in step 1, which is overridden in all the subclasses to show their
respective areas .
iii. SOURCE CODE :
#include<iostream.h>
class Circle;
class Rectangle;
class Square;
class Triangle;
class Trapezium;
class Area
{
CS1031/OOPS Lab CSE/SRM 27/57
protected:
float area;
public:
Area(float a)
{
area=a;
}
virtual void display(){}
};
class Circle:public Area
{
protected:
float ar;
public:
Circle(float a):Area( a)
{ar=3.14*a*a;}
void display()
{
cout<<"Area of Circle="<<ar;
}
};
class Rectangle:public Area
{
protected:
float ar;
public:
Rectangle(float a,float b):Area( a)
{ar=a*b;}
void display()
{
cout<<"Area of Rectangle="<<ar;
}
};
class Square:public Area
{
protected:
float ar;
public:
Square(float a):Area( a)
{ar=a*a;}
void display()
{
CS1031/OOPS Lab CSE/SRM 28/57
cout<<"Area of Square="<<ar;
}
};
class Triangle:public Area
{
protected:
float ar;
public:
Triangle(float a,float b):Area( a)
{ar=0.5*a*b;}
void display()
{
cout<<"Area of Triangle="<<ar;
}
};
class Trapezium:public Area
{
protected:
float ar;
public:
Trapezium(float a,float b):Area( a)
{ar=0.5*(a+b);}
void display()
{
cout<<"Area of Trapezium="<<ar;
}
};
int main()
{
cout<<"\nEnter radius of circle:";
int ra;
cin>>ra;
Circle c(ra);
cout<<"\nEnter length and breadth of rectangle:";
int a,b;
cin>>a>>b;
Rectangle r(a,b);
cout<<"Enter side of square:";
int sq;
cin>>sq;
CS1031/OOPS Lab CSE/SRM 29/57
Square s(sq);
cout<<"Enter height and base of circle:";
int h,ba;
cin>>h>>ba;
Triangle t(h,ba);
cout<<"Enter parallel sides's length of trapezium:";
int p,pt;
cin>>p>>pt;
Trapezium tr(p,pt);
Area *bptr[5];
bptr[0]=&c;
bptr[1]=&r;
bptr[2]=&s;
bptr[3]=&t;
bptr[4]=&tr;
bptr[0]->display();
bptr[1]->display();
bptr[2]->display();
bptr[3]->display();
bptr[4]->display();
return 0;
}
iv. SAMPLE INPUTS & OUTPUTS:
Enter radius of circle: 2
Enter length and breadth of rectangle: 4 6
Enter side of square: 2
Enter height and base of circle: 3 2
Enter parallel sides's length of trapezium: 3 3
Area of circle=12.56
Area of rectangle=24
Area of square=4
Area of triangle=3
Area of Trapezium=1.5
CS1031/OOPS Lab CSE/SRM 30/57
RESULT :
The program was successfully compiled & executed, and the output was verified.
v. Few (Min. 5) Questions related to the next Experiment:
1. What is exception handling?
2. Blocks of exception handling?
3. What is throw statement?
4. Strategy of Stack & Queue operation?
5. Catching all exceptions?
EXCEPTION HANDLING IN STACKS
Exp. No: 5.A
i. OBJECTIVE:
To write a C++ program to illustrate exception handling concept using stack operation as an example.
ii. ALGORITHM:
STEP 1: Include the Header file.
STEP 2: Create a class Stack which initialize size of the stack
STEP 3: Create function push to do insert operation which in turn throws an exception when it overflow.
STEP 4: Create function pop to do delete operation which in turn throws an exception when it
underflow.
STEP 5: Display the operation on console using display function.
iii. SOURCE CODE :
#include<iostream.h>
class Stack
{
public:
int size;
CS1031/OOPS Lab CSE/SRM 31/57
int top;
int *a;
Stack(int sz)
{
size=sz;
a=new int[sz];
top =-1;
}
void push(int c)
{
if(top==size-1){
throw top;
}
else
{
a[++top]=c;
}
}
void pop()
{
if(top==-1)
throw top;
else
cout<<"\n"<<a[top--]<<" removed\n";
}
void display();
};
void Stack::display()
{
cout<<"\nStack:\n";
for(int i=0 ;i<=top;i++)
cout<<a[i]<<" ";
}
int main()
{
int sz,x,ch;
cout<<"\nEnter stack size:";
cin>>sz;
Stack s(sz);
try
{
CS1031/OOPS Lab CSE/SRM 32/57
do
{
cout<<"\nEnter choice:\n1 for push\n2 for pop\n3 for display\n4 to exit\n";
cin>>ch;
switch(ch)
{
case 1:cout<<"\nEnter a no.:";
cin >>x;
s.push(x);
break;
case 2:s.pop();
break;
case 3:s.display();
break;
case 4:return 0;
break;
default:
cout<<"Enter a valid choice.";
}
}while(1);
}
catch(int a)
{
if(a==s.size-1)
cout<<"\nOverflow\n";
else
cout<<"\nUnderflow";
}
return 0;
}
iv. SAMPLE INPUTS & OUTPUTS:
Enter the size of stack: 3
Enter choice:
1 for push
2 for pop
3 for display
4 to exit
1
Enter a no 2
1
CS1031/OOPS Lab CSE/SRM 33/57
Enter a no 3
3
3
2
2
Removed
3
2
RESULT :
The program was successfully compiled & executed, and the output was verified.
EXCEPTION HANDLING IN QUEUES
Exp. No: 5.B
i. OBJECTIVE:
To write a C++ program to illustrate exception handling concept using queue operation as an
example.
ii. ALGORITHM:
STEP 1: Include the Header file.
STEP 2: Create a class Stack which initialize size of the stack
STEP 3: Create function push to do insert operation which in turn throws an exception when it overflow.
STEP 4: Create function pop to do delete operation which in turn throws an exception when it
undererflow.
STEP 5: Display the operation on console using display function.
iii. SOURCE CODE :
#include<iostream.h>
class queue
{
CS1031/OOPS Lab CSE/SRM 34/57
public:
int size;
int front ,rear;
int *a;
queue(int sz)
{
size=sz;
a=new int[sz];
front =-1;
rear=-1;
}
void insert(int c)
{
if(rear==size-1){
throw rear;
}
else
{
a[++rear]=c;
}
}
void remove()
{
if(front==rear)
throw 'u';
else
cout<<"\n"<<a[++front]<<" removed\n";
}
void display();
};
void queue::display()
{
cbout<<"\nQueue:\n";
for(int i=front + 1 ;i<=rear;i++)
cobut<<a[i]<<" ";
}
int main()
{
int sz,x,ch;
cout<<"\nEnter queue size:";
cin>>sz;
queue s(sz);
CS1031/OOPS Lab CSE/SRM 35/57
try
{
do
{
cout<<"\nEnter choice:\n1 for insert\n2 for remove\n3 for display\n4 to exit\n";
cin>>ch;
switch(ch)
{
case 1:cout<<"\nEnter a no.:";
cin >>x;
s.insert(x);
break;
case 2:s.remove();
break;
case 3:s.display();
break;
case 4:return 0;
break;
default:
cout<<"Enter a valid choice.";
}
}while(1);
}
catch(int a)
{
if(a==s.size-1)
cout<<"\nOverflow\n";
}
catch(char c)
{
if(c=='u')
cout<<"\nUnderflow.";
}
return 0;
}
iv. SAMPLE INPUTS & OUTPUTS:
Enter the size of queue: 3
Enter choice:
1 for insert
CS1031/OOPS Lab CSE/SRM 36/57
2 for delete
3 for display
4 to exit
1
Enter a no 2
1
Enter a no 3
3
2
3
2
Removed
2
2
RESULT :
The program was successfully compiled & executed, and the output was verified.
CS1031/OOPS Lab CSE/SRM 37/57
JAVA
TYPE CASTING
Exp. No: 1.A
i. OBJECTIVE:
To write a program to demonstrate typecasting in java.
ii. ALGORITHM:
Step 1: create a class containing main function
Step 2: declare an integer, byte, double variable.
Step 3: convert integer to byte using (byte).
Step 4: convert double to integer using (int).
Step 5: convert double to byte using (byte).
iii. SOURCE CODE :
class Coversion
CS1031/OOPS Lab CSE/SRM 38/57
{
public static void main(String args[])
{
byte b;
int i=255;
double d=323.142;
System.out.println("\nConversion of int into byte:-");
b=(byte)i;
System.out.println("i and b:"+i+" and "+b);
System.out.println("\nConversion of double to int:-");
i=(int)d;
System.out.println("d and i:"+d+" and "+i);
System.out.println("\nConversion of double to byte:-");
b=(byte)d;
System.out.println("d and b:"+d+" and "+b);
}
}
iv. SAMPLE INPUTS & OUTPUTS:
Conversion of int into byte:-
i and b:255 and -1
Conversion of double to int:-
d and i:323.142 and 323
Conversion of double to byte:-
d and b:323.142 and 67
RESULT :
The program was successfully compiled & executed, and the output was verified.
METHOD OVERLOADING
Exp. No: 1.B
i. OBJECTIVE:
To write a program to demonstrate method overloading in java.
ii. ALGORITHM:
Step1:Create a class with main function
Step2:Create one more class with an overloaded function called test.There is a difference in the type of
return values and the signature arguments.
Step 3:Create an object ofthis class in side the main function and call the overloadedmethodwith different
arguments.
CS1031/OOPS Lab CSE/SRM 39/57
iii. SOURCE CODE :
class Overload{
public static void main(String args[])
{
OvDe o=new OvDe();
double s;
o.test();
o.test(10);
o.test(32,64);
s=o.test(5.5);
System.out.println("Result of o.test(5.5): "+s);
}
}
class OvDe
{
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a: "+a);
}
void test(int a,int b)
{
System.out.println("a and b: "+a+" "+b);
}
double test(double a)
{
System.out.println("double a: "+a);
return a*a; }}
iv. SAMPLE INPUTS & OUTPUTS:
No parameters
a: 10
a and b: 32 64
double a: 5.5
Result of o.test(5.5): 30.25
CS1031/OOPS Lab CSE/SRM 40/57
RESULT :
The program was successfully compiled & executed, and the output was verified.
v. Few (Min. 5) Questions related to the next Experiment:
1. Define inheritance?
2. What is access specifier?
3. Which is the default access specifier in C++?
4. Difference between multiple and multilevel inheritance?
5. Advantages of using inheritance?
MULTILEVEL INHERITANCE
Exp. No: 2
i. OBJECTIVE:
To write a java program to illustrate the multilevel inheritance using database creation as an example.
ii. ALGORITHM:
S t e p 1 : Create a class with main function.
CS1031/OOPS Lab CSE/SRM 41/57
Step 2 : Create a class ‘Staff' with member variables and setter and getter methods
S t e p 3 : Create a class ‘typist ' which extends the class ‘staff' again with some setter methods .
Step 4: create a class ‘casual’ which extends the class ‘typist’ again with some setter methods.
Step 5: create an object of class ‘casual’ and call methods that were originally defined in the department
class ( and not overridden)
S t e p 6 : Call the getter methods to retrieve the details .
iii. SOURCE CODE :
class Imps
{
public static void main(String args[])
{
casual s= new casual();
s.getD("Ankit","Typist");
s.getS('m');
s.prF();
}
}
class Staff
{
String na;
String c;
void getD(String n,String co)
{
na=n;
c=co;
}
void prD()
{
System.out.println("Staff Detail:\nName:"+na+"\nCode:"+c);
}
}
class typist extends Staff
{
char speedCode;
void getS(char s)
{
speedCode=s;
}
void disS()
{
CS1031/OOPS Lab CSE/SRM 42/57
prD();
System.out.println("Speed Code:"+speedCode);
}
}
class casual extends typist
{
void prF()
{
int daw=0;
switch(speedCode)
{
case 's':daw=100;
break;
case 'm':daw=300;
break;
case 'f':daw=500;
break;
default:
System.out.println("Invalid Code entered .");
}
disS();
System.out.println("Daily Wages:Rs"+daw);
}
}
iv. SAMPLE INPUTS & OUTPUTS:
Staff Details:
Name:XYZ
Code:Typist
SpeedCode:m
Daily Wages:Rs 300
CS1031/OOPS Lab CSE/SRM 43/57
RESULT :
The program was successfully compiled & executed, and the output was verified.
v. Few (Min. 5) Questions related to the next Experiment:
1. Difference between overloading & overriding?
2. How to invoke superclass constructor?
3. Use of super keyword?
4. Implementing overriding?
5. Use of throws keyword?
DYNAMIC MEMORY DISPATCH AND METHOD OVERRIDING
Exp. No: 3
i. OBJECTIVE:
To write a java program to illustrate the dynamic memory dispatch and method overriding concept
with a simple example.
ii. ALGORITHM:
CS1031/OOPS Lab CSE/SRM 44/57
Step 1:Create a class with the main function
Step 2:Create a class ‘Figure' which is extended to other classes:Rectangle,Circle and triangle.
Step 3:in class figure there is a method called area and thismethod is given a new definition in the subclasses.
So it is overridden
Step 4:Now construct the objects ofthe subclasses with the required attributes , that are set in the constructor.
Step 5:Call the area function of all the three objects of different classes(having the same parent class).
iii. SOURCE CODE :
import java.io.*;
class DyMemDisp
{
public static void main(String args[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
Figure f;
System.out.println("Enter the length of rectangle:");
float l=Float.parseFloat(b.readLine());
System.out.println("Enter the breadth of rectangle:");
float g=Float.parseFloat(b.readLine());
Rectangle r=new Rectangle(l,g);
System.out.println("Enter the radius of circle:");
float ra=Float.parseFloat(b.readLine());
Circle c=new Circle(ra);
System.out.println("Enter the base of triangle:");
float br=Float.parseFloat(b.readLine());
System.out.println("Enter the height of triangle:");
float he=Float.parseFloat(b.readLine());
Triangle t=new Triangle(br,he);
f=r;
f.area();
f=c;
f.area();
f=t;
f.area();
}
}
class Figure
{
float d1,d2;
Figure(float a,float b)
{
d1=a;
d2=b;
CS1031/OOPS Lab CSE/SRM 45/57
}
void area()
{}
}
class Rectangle extends Figure
{
float l,ba;
Rectangle(float a,float b)
{
super(a,b);
l=a;
ba=b;
}
void area()
{
System.out.println("Area of rectangle="+(l*ba));
}
}
class Circle extends Figure
{
float r;
Circle(float a)
{
super(a,0);
r=a;
}
void area()
{
System.out.println("Area of circle="+(3.14f*r*r));
}
}
class Triangle extends Figure
{
float ba,h;
Triangle(float a,float b)
{
super(a,b);
CS1031/OOPS Lab CSE/SRM 46/57
ba=a;
h=b;
}
void area()
{
System.out.println("Area of Triangle="+(0.5f*ba*h));
}
}
iv. SAMPLE INPUTS & OUTPUTS:
Enter the length of rectangle:
5
Enter the breadth of rectangle:
2
Enter the radius of circle:
2
Enter the base of triangle:
2
Enter the height of triangle:
8
Area of rectangle=10.0
Area of circle=12.56
Area of Triangle=8.0
v. RESULT :
The program was successfully compiled & executed, and the output was verified.
vi. Few (Min. 5) Questions related to the next Experiment:
1. What are packages?
2. How to create a package?
3. How to run a package program?
4. Define protected access specifier?
5. How to import a user defined package?
CREATION OF PACKAGES
Exp. No: 4
i. OBJECTIVE:
To write a java program to demonstrate the package concept using a simple example.
ii. ALGORITHM:
CS1031/OOPS Lab CSE/SRM 47/57
STEP 1: Create a package of user defined.
STEP 2: Create a classes of specific user defined and save them in the package folder created.
STEP 3: All the classes are saved in a separate file and used in a package folder just by importing them.
STEP 4: The members and methods and class defined as protected specifier can be accessed throughout
the package.
iii. SOURCE CODE :
File name: Check.java
package rear;
public class Check
{
int n=1;
private int np=2;
protected int npro=3;
public int npub=4;
public Check()
{
System.out.println("Base constructor:");
System.out.println("default n:"+n);
System.out.println("private n(np):"+np);
System.out.println("protected n(npro):"+npro);
System.out.println("public n(npub):"+npub);
System.out.println(" ");
}
}
File name: DerSame.java
package rear;
class DerSame extends Check
{
DerSame()
{
System.out.println("Derived Constructor");
System.out.println("n:"+n);
System.out.println("npro:"+npro);
System.out.println("npub:"+npub);
System.out.println(" ");
}
}
File name: Create.java
package rear;
class Create
CS1031/OOPS Lab CSE/SRM 48/57
{
public static void main(String args[])
{
DerSame d=new DerSame()
}
}
File name: DerAno.java
package Front;
import rear.Check;
class DerAno
{
public static void main(String args[])
{
System.out.println("Importing class Constructor");
Check c=new Check();
System.out.println("npub:"+c.npub);
System.out.println(" ");
}
}
iv. SAMPLE INPUTS & OUTPUTS:
Running Create.class
Base constructor:
default n:1
private n(np):2
protected n(npro):3
public n(npub):4
Derived Constructor
n:1
npro:3
npub:4
Running DerAno.class
Importing class Constructor
Base constructor:
default n:1
private n(np):2
CS1031/OOPS Lab CSE/SRM 49/57
protected n(npro):3
public n(npub):4
npub:4
RESULT :
The program was successfully compiled & executed, and the output was verified.
v. Few (Min. 5) Questions related to the next Experiment:
1. Define interface?
2. What is abstract class?
3. Use of implements keyword?
4. Difference between extends and implements?
5. Use of interface?
IMPLEMENTING INTERFACES
Exp. No: 5
i. OBJECTIVE:
To write a java program to illustrate the interfaces concept.
ii. ALGORITHM:
CS1031/OOPS Lab CSE/SRM 50/57
Step 1: Create a class with main function
Step 2:Create an interface ‘Show' with an abstract method. Create an interface ‘Greater' which extends
this interface.
Step 3:Create a class'Doo' which implents this interface and it also defines all the abstractmethods of this
interface .
Step 4:Create an object ofthis class and call these redefined methods.
iii. SOURCE CODE :
import java.io.*;
class Cv
{
public static void main(String args[])throws IOException
{
Doo d=new Doo();
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter value of x:");
d.x=Integer.parseInt(b.readLine());
System.out.println("Enter value of y:");
d.y=Integer.parseInt(b.readLine());
System.out.println("Output:");
d.print();
d.check();
}
}
class Doo implements Greater
{
int x;
int y;
public void print()
{
System.out.println("x:"+x+"\ny:"+y);
}
public void check()
{
System.out.println("Greater out of x and y:"+((x>y)?x:y));
}
}
interface Show
{
void print();
}
interface Greater extends Show
{
CS1031/OOPS Lab CSE/SRM 51/57
void check();
}
iv. SAMPLE INPUTS & OUTPUTS:
Enter value of x:
21
Enter value of y:
2
Output:
x:21
y:2
Greater out of x and y :21
RESULT :
The program was successfully compiled & executed, and the output was verified.
v. Few (Min. 5) Questions related to the next Experiment:
1. Explain about string class?
2. What is string tokenizer?
3. List any 5 string methods?
STRING MANIPULATION
Exp. No: 6
i. OBJECTIVE:
To manipulate strings in java.
CS1031/OOPS Lab CSE/SRM 52/57
ii. ALGORITHM:
Step 1:create a class with the main function.
Step2:Get a string input from the user using the BufferedrEADER STREAM.
Step 3:call the following functions on the string: .toLowerCase(),.toUpperCase()
Step 4:Place an integer in the wrapper class Integer and parse it to strings using toString()
Step 5:Try calling 4 more methods on the strings.
iii. SOURCE CODE :
import java.io.*;
class StrMan
{
public static void main(String args[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a String:");
String s=b.readLine();
System.out.println("Trimmed String:"+s.trim());
System.out.println("Entered string in lowwer case: "+s.toLowerCase());
System.out.println("Entered string in upper case: "+s.toUpperCase());
Integer a=new Integer(8);
System.out.println("a= "+ a);
System.out.print("a.toString():");
System.out.println(a.toString());
System.out.println("Enter the position to extract character:");
int p=Integer.parseInt(b.readLine());
if(p<=s.length())
System.out.println("Charachter at pos "+p+" in String "+s+" is '"+s.charAt(p-1)+"'.");
else
System.out.println("Valid position not entered.");
for(int i=0;i<s.length();i++)
System.out.println("Index of '"+s.charAt(i)+"' is "+s.indexOf(s.charAt(i)));
System.out.println("Enter the index to replace charachter:");
p=Integer.parseInt(b.readLine());
if(p<s.length())
{
System.out.println("Enter the charachter to replace with:");
char c=(char)b.read();
System.out.println("Replaced String:"+s.replace(s.charAt(p),c));
}
else
System.out.println("Enter a valid position.");
}
CS1031/OOPS Lab CSE/SRM 53/57
}
iv. SAMPLE INPUTS & OUTPUTS:
Enter a String:
Ankit
Trimmed String:Ankit
Entered string in lowwer case: ankit
Entered string in upper case: ANKIT
a= 8
a.toString():8
Enter the position to extract character:
2
Charachter at pos 2 in String Ankit is 'A'.
Index of is 0
Index of 'A' is 1
Index of 'n' is 2
Index of 'k' is 3
Index of 'i' is 4
Index of 't' is 5
Enter the index to replace charachter:
0
Enter the charachter to replace with:
S
Replaced String:SAnkit
v. RESULT :
The program was successfully compiled & executed, and the output was verified.
vi. Few (Min. 5) Questions related to the next Experiment:
1. Define thread?
2. Which interface is driven by thread?
3. What is the base class for thread?
4. List some of the static methods of thread?
5. Difference between sleep & wait?
MULTITHREADING
Exp. No: 7
i. OBJECTIVE:
To write a java program to multithreading concept .
ii. ALGORITHM:
CS1031/OOPS Lab CSE/SRM 54/57
Step 1:Create a class which either extends Thread or implements Runnable.
Step 2:This class itself makes its own object to the thread and calls the start methodwhich will call the run
method.
Step 3:Define the run method.
Step 4:Create an object ofthis class in main and the thread willstart automatically as the start is called in its
constructor.
Step 5:So we have 2 threads: onewhich you have made and the other is the main thread running
simultaneously.
iii. SOURCE CODE :
class ThreadDemo {
public static void main(String args[])
{ new NewThread();
try {
for(int i = 5; i > 0; i--)
{ System.out.println("Main Thread: " + i);
Thread.sleep(1000); } } catch (InterruptedException e)
{System.out.println("Main thread interrupted.");
} System.out.println("Main thread exiting.");
}
}
class NewThread implements Runnable { Thread t;
NewThread() {
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start();
}
public void run() {
try {
for(int i = 5; i > 0; i--)
{ System.out.println("Child Thread: " + i);
Thread.sleep(500); } }
catch (InterruptedException e)
{ System.out.println("Child interrupted."); }
System.out.println("Exiting child thread."); }
}
iv. SAMPLE INPUTS & OUTPUTS:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
CS1031/OOPS Lab CSE/SRM 55/57
Child Thread: 2
Child Thread: 1
Main Thread: 3
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
RESULT :
The program was successfully compiled & executed, and the output was verified.
v. Few (Min. 5) Questions related to the next Experiment:
1. Define applet?
2. Give the interface used ti implement applet?
3. What is the base class of applet?
4. List the static methods of awt?
5. What is the use of applet viewer?
JAVA APPLET
Exp. No: 8
i. OBJECTIVE:
To write a java program to implement java applet concept .
CS1031/OOPS Lab CSE/SRM 56/57
ii. ALGORITHM:
Step1: Create a html file which holds the width and height of the form.
Step2: Create a class which implements the runnable interface of thread.
Step3: use the methods of applet class and set the color of background and foreground.
Step4: use the thread methods to invoke the functions.
Step5: Run the code through appletviewer online.
iii. SOURCE CODE :
/* A simple banner applet.
This applet creates a thread that scrolls the message contained in msg right to left across the
applet's window.
*/ import java.awt.*; import java.applet.*; /* <applet code="SimpleBanner" width=300
height=50> </applet> */
public class SimpleBanner extends Applet implements Runnable { String msg = " A Simple Moving
Banner."; Thread t = null; int state; boolean stopFlag;
// Set colors and initialize thread.
public void init() { setBackground(Color.cyan); setForeground(Color.red); }
// Start thread
public void start() { t = new Thread(this); stopFlag = false; t.start();}
// Entry point for the thread that runs the banner.
public void run() { char ch;
// Display banner
for( ; ; ) { try { repaint(); Thread.sleep(250); ch = msg.charAt(0); msg = msg.substring(1,
msg.length()); msg += ch; if(stopFlag) break; } catch(InterruptedException e) {} }
}
// Pause the banner.
public void stop() { stopFlag = true; t = null; }
// Display the banner.
public void paint(Graphics g) { g.drawString(msg, 50, 30); }
}
iv. SAMPLE INPUTS & OUTPUTS: