Oopl Record(2)

129
CLASS AND OBJECT AIM: To write a c++ program to display Electricity Bill using Class & Objects. ALGORITHM: 1. Start the process. 2. Create a class Bill with its member function. 3. Declare the variables present, previous, consumed, serial number, receipt number, bill month and date. 4. Read Data, previous, present data. 5. Calculate, consumed = present – previous. 6. Check if consumed > = 200 then, total = consumed*2.50. 7. Otherwise, total = consumed*1.50. 8. Display the values. 9. Stop.

Transcript of Oopl Record(2)

Page 1: Oopl Record(2)

CLASS AND OBJECT

AIM:To write a c++ program to display Electricity Bill using Class & Objects.

ALGORITHM:

1. Start the process.

2. Create a class Bill with its member function.

3. Declare the variables present, previous, consumed, serial number, receipt number, bill

month and date.

4. Read Data, previous, present data.

5. Calculate, consumed = present – previous.

6. Check if consumed > = 200 then, total = consumed*2.50.

7. Otherwise, total = consumed*1.50.

8. Display the values.

9. Stop.

Page 2: Oopl Record(2)

SOURCE CODE:#include<iostream.h>#include<conio.h>class bill{protected: int present, previous, consumed, srlno;char name[20],rcpt_no[10],billmonth[15],date[12];float total;public: void getdata();void calculate();void showdata();};void bill::getdata(){cout<<"\nEnter the serial no.& reciept no:\n";cin>>srlno>>rcpt_no;cout<<"\n Enter the bill month & date:\n";cin>>billmonth>>date;cout<<"\n present and previous reading:\n";cin>>present>>previous;}void bill::calculate(){consumed=present-previous;if(consumed>=200)total=consumed*2.50;elsetotal=consumed*1.50;}void bill::showdata(){cout<<"\n\n \t ELECTRICITY BILL";cout<<"\n srl.no :"<<srlno;cout<<"\n reciept no :"<<rcpt_no;cout<<"\n total cost for consumed:"<<consumed;cout<<"\n unit in RS:"<<total;}void main(){bill b;clrscr();b.getdata();b.calculate();b.showdata();getch();}

Page 3: Oopl Record(2)

SAMPLE INPUT AND OUTPUT:

Enter the serial no.:01

Enter the receipt no:13

Enter the bill month:05

Enter the date :21

Enter the present reading: 400

Enter the previous reading:300

ELECTRICITY BILL

srl.no :01 reciept no :13 total cost for consumed :100 unit in RS :150

RESULT: Thus the c++ program has been executed successfully.

Page 4: Oopl Record(2)

CONSTRUCTOR AND DESTRUCTOR

AIM:

A program to print student details using constructor and destructor

ALGORITHAM:

1. Start the process

2. Invoke the classes

3. Call the read() function

a. Get the inputs name ,roll number and address

4. Call the display() function

a. Display the name, roll number and address of the student

5. Stop the process

Page 5: Oopl Record(2)

SOURCE CODE:#include<iostream.h>#include<conio.h>class stu{private: char name[20],add[20]; int roll,zip;public: stu ( );//Constructor ~stu( );//Destructor void read( ); void disp( );};stu :: stu( ){cout<<”This is Student Details”<<endl;}void stu :: read( ){cout<<”Enter the student Name”;cin>>name;cout<<”Enter the student roll no “;cin>>roll;cout<<”Enter the student address”;cin>>add;cout<<”Enter the Zipcode”;cin>>zip;}void stu :: disp( ){cout<<”Student Name :”<<name<<endl;cout<<”Roll no is :”<<roll<<endl;cout<<”Address is :”<<add<<endl;cout<<”Zipcode is :”<<zip;}stu : : ~stu( ){cout<<”Student Detail is Closed”;}void main( ){stu s;clrscr( );s.read ( );s.disp ( );getch( );}

Page 6: Oopl Record(2)

SAMPLE INPUT AND OUTPUT:

This is Student Details

Enter the student NameJamesEnter the student roll no01Enter the student addressNewyorkEnter the Zipcode919108

Student Name : JamesRoll no is : 01Address is : NewyorkZipcode is :919108

Student Detail is Closed

RESULT: Thus the c++ program has been executed successfully.

Page 7: Oopl Record(2)

OPERATING OVERLOADING

AIM:

To write a program to overload the unary and binary operator using the friend functions and to

experimentally verify the results.

ALGORITHM:

1. Start the process.

2. Declare a class ‘fun1’ to overload the unary operator(-) and also to display the overloaded

functionality of that operator.

3. And then declare a class named ‘fun2’ to overloaded the binary operator(*).

4. And in that class ‘fun2’ use a friend function to do the operation of the operator(*) and

then use a member function to display them.

5. In the main function, create an object each for class ‘fun1’ and ‘fun2’ such that the

corresponding operators are overloaded.

6. First call the unary operator to be overloaded and then the binary operator to be

overloaded.

7. Stop.

Page 8: Oopl Record(2)

SOURCE CODE:

#include<iostream.h>#include<conio.h>class fun1{int a,b;public:void get(){cout<<"\n Enter 2 numbers:";cin>>a>>b;}void operator-(){a=-a;b=-b;}void disp(){cout<<"\n** UNARY OPERATOR OVERLOADING ** \n";cout<<a<<"\t"<<b;}};class fun2{public:int x,y;void disp();void get(){cout<<"\n Enter 2 numbers:";cin>>x>>y;}friend fun2 operator*(fun2 a,fun2 b);};fun2 operator*(fun2 a,fun2 b){fun2 c;c.x=a.x*b.x;c.y=a.y*b.y;return c;}void fun2::disp(){

Page 9: Oopl Record(2)

cout<<"\n"<<x<<"\t"<<y;}void main(){clrscr();int m;fun1 z;z.get();-z;z.disp();fun2 f1,f2,f3;f1.get();f2.get();cout<<"\n ** BINARY OPERATOR OVERLOADING **";f3=f1*f2;f3.disp();getch();}

Page 10: Oopl Record(2)

SAMPLE INPUT AND OUTPUT:

Enter 2 numbers:1-3**UNARY OPERATOR OVERLOADING**-1 3Enter 2 numbers:43Enter 2 numbers:2 4**BINARY OPERATOR OVERLOADING**8 12

RESULT: Thus the c++ program has been executed successfully

Page 11: Oopl Record(2)

SINGLE INHERITANCE

AIM:-To write a c++ program salary calculation using single inheritance

ALGORITHM:-

1. Start the process

2. create a class base with its data members and member function.

3. Derived the derived class and inherit base class as a public.

4. Derived the read the values from base class function .

5. Calculate the values, from derived class function

i. Da=bs*0.12;

ii. Hra=bs*0.07;

iii. Pf=400;

6. Display the values.

7. Stop.

Page 12: Oopl Record(2)

SOURCE CODE:

#include<stdio.h>#include<iostream.h>#include<conio.h>class base{public:char nam[20],dofb[20];float bp,gp;void getdata();};class derived:public base{float da,hra,pf;public:void calculate();void display();};void base::getdata(){cout<<"\n\n\t Enter the Name :\t";cin>>nam;cout<<"\n\n\t Enter the date of birth :\t";cin>>dofb;cout<<"\n\n\t Enter the basic pay :\t";cin>>bp;}void derived::calculate(){da=bp*0.12;hra=bp*0.07;pf=400;gp=bp+da+hra+pf;}void derived::display(){cout<<"\n\n\t NAME :\t"<<nam;cout<<"\n\n\t DOB :\t"<<dofb;cout<<"\n\n\t BASIC PAY :\t"<<bp;cout<<"\n\n\t DA :\t"<<da;cout<<"\n\n\t HRA :\t"<<hra;cout<<"\n\n\t Pf :\t"<<pf;cout<<"\n\n\t GROSSPAY :\t"<<gp;}

Page 13: Oopl Record(2)

void main(){derived d;clrscr();cout<<"\n\n\n\t\t\t FRIEND FUNCTION";cout<<"\n\t INPUT:\n”;d.getdata();d.calculate();cout<<"\n\t OUTPUT:\n";d.display();getch();}

Page 14: Oopl Record(2)

SAMPLEINPUT AND OUTPUT:-

ENTER NAME :Gayathri

ENTER DATE OF BIRTH :21/05/1992

ENTER BASIC PAY :15000

NAME :Gayathri

DATE OF BIRTH :21/05/1992

BASIC SALARY :15000

DA :1800

HRA :1050

PF :400

RESULT: Thus the c++ program has been executed successfully.

Page 15: Oopl Record(2)

MULTIPLE INHERITANCE

AIM: To write a c++ program to implement students details using multiple inheritance.

ALGORITHM:

1. Start the process.

2. Create a class info with its data members and member function.

3. Read the values for reg.no, name, deg.

4. Create a class dept with its data members and function.

5. Read the values for semester and department name.

6. Create a class stud with its data members and member function.

7. Display the student details.

8. Stop.

Page 16: Oopl Record(2)

SOURCE CODE:

#include<iostream.h>#include<conio.h>class info{protected:long int reg_no;char name[20];char deg[10];public:void get(){cout<<"Enter reg.no, name and degree: ";cin>>reg_no>>name>>deg;}void put(){cout<<"Reg_no: "<<reg_no<<'\n';cout<<"Name: "<<name<<'\n';cout<<"Degree: "<<deg<<'\n';}};class dept{protected:int sem;char dname[10];public:void gets(){cout<<"Enter the dept. name and semester: ";cin>>dname>>sem;}void puts(){cout<<"Department: "<<dname<<'\n';cout<<"Semester: "<<sem<<'\n';}};class stud:public info,public dept{float cgpa;char remark[15];public:void read()

Page 17: Oopl Record(2)

{get();gets();cout<<"Enter the CGPA: ";cin>>cgpa;cout<<'\n'<<"Enter the remark: ";cin>>remark;}void write(){put();puts();cout<<"CGPA point: "<<cgpa<<'\n';cout<<"Remark: "<<remark<<'\n';}};void main(){clrscr();stud s;s.read();clrscr();cout<<'\n'<<'\t'<<'\t'<<'\t'<<"STUDENT DETAILS"<<'\n';s.write();getch();}

Page 18: Oopl Record(2)

SAMPLE INPUT AND OUTPUT:

STUDENT DETAILS

Reg_no: 8013Name: GayathriDegree: B.TechDepartment: CSESemester: 4CGPA point: 9.4Remark: Excellent

RESULT: Thus the c++ program has been executed successfully.

Page 19: Oopl Record(2)

MULTILEVEL INHERITANCE

AIM:To write a c++ program to add two marks using multilevel inheritance.

ALGORITHM:

1. Start the process.

2. Declare the class stu with its member function.

3. Derived the class test as stu base class as public, with its data members.

4. Derived the derived class test to result as public with its data members.

5. Read the roll numbers from derived class list.

6. Read the marks from derived class list.

7. Display to students details.

8. Stop.

Page 20: Oopl Record(2)

SOURCE CODE:

#include<iostream.h>#include<conio.h>class stu{protected:char roll[20];public:void getdata();void putdata();};class test:public stu{protected:float sub1,sub2;public:void getmark();void dismark();};class result:public test{float total;public:void display(){total=sub1+sub2;putdata();dismark();cout<<"\n\n TOTAL :"<<total;}};void stu::getdata(){cout<<"\n ENTER THE ROLL NUMBER :";cin>>roll;}void stu::putdata(){cout<<"\n\n ROLL NUMBER :"<<roll;}void test::getmark(){cout<<"\n\nENTER THE SUBJECT 1 MARK :";cin>>sub1;cout<<"\n\nENTER THE SUBJECT 2 MARK :";cin>>sub2;

Page 21: Oopl Record(2)

}void test::dismark(){cout<<"\n\n SUJECT 1 MARK :"<<sub1;cout<<"\n\n SUBJECT 2 MARK :"<<sub2;}void main(){result r;clrscr();r.getdata();r.getmark();r.display();getch();}

Page 22: Oopl Record(2)

SAMPLE INPUT AND OUTPUT:

Enter the roll.no:8013

Enter the sub1 mark:98

Enter the sub2 mark:99

ROLL NUMBER : 8013

SUBJECT 1 MARK: 98

SUBJECT 2 MARK: 99

TOTAL : 197

RESULT: Thus the c++ program has been executed successful

Page 23: Oopl Record(2)

HYBRID INHERITANCE

AIM: To write a c++ program to implement the hybrid inheritance.

ALGORITHM:

1. Start the process.

2. Create a class bank with its data members and its member functions.

3. Derived class fun as bank base class as public with its data members.

4. Derived class syst as bank, fun2 base class as public with its data members.

5. Read the values and calculate the balance amount.

6. Display all the values.

7. Stop.

Page 24: Oopl Record(2)

SOURCE CODE:

#include<iostream.h>#include<stdlib.h>#include<conio.h>class bank{public:int acno;char name[30];double am,dm,w;void getdata(){cout<<"\nACC NO.: ";cin>>acno;cout<<"\nNAME: ";cin>>name;cout<<"\nAMOUNT: ";cin>>am;}};class fun:virtual public bank{public:void deposit(int ano){if(ano==acno){cout<<"\nEnter the amount to deposit: ";cin>>dm;am=am+dm;cout<<"\nYour balance: "<<am;}}};class fun2:virtual public bank{public:void withdraw(int ano){double w;if(ano==acno){cout<<"\nEnter the amount to be withdrawn: ";cin>>w;if(am>w)

Page 25: Oopl Record(2)

{am=am-w;cout<<"\nRemaining amount is "<<am;}elsecout<<"\nCan't withdraw, amount not sufficient";}}};class syst:public fun,public fun2{public:void disp(){cout<<acno<<"\t\t"<<name<<"\t\t"<<am<<"\n";}}; void main(){clrscr();int a,n,i,x;syst s[10];cout<<"\nEnter the no. of users: ";cin>>n;for(i=0;i<n;i++)s[i].getdata();while(1){cout<<"\n\nMENU\n";cout<<"\n1.Deposit\n2.Withdraw\n3.Display\n4.Exit\n";cout<<"\nEnter your choice: ";cin>>a;switch(a){case 1:cout<<"\nEnter your acc.no.: ";cin>>x;for(i=0;i<n;i++)s[i].deposit(x);break;case 2:cout<<"\nEnter your acc.no.: ";cin>>x;for(i=0;i<n;i++)s[i].withdraw(x);break;

Page 26: Oopl Record(2)

case 3:cout<<"\nACC NO\t\tNAME\t\tAmount\n";for(i=0;i<n;i++)s[i].disp();break;case 4:exit(0);}getch();}}

Page 27: Oopl Record(2)

SAMPLE INPUT AND OUTPUT:

Enter the no. of users: 2ACC NO.: 101NAME: GayathriAMOUNT: 5000ACC NO.: 102NAME: AnithaAMOUNT: 6000

MENU

1.Deposit2.Withdraw3.Display4.ExitEnter your choice: 2Enter your acc.no.: 101Enter the amount to be withdrawn: 1500Remaining amount is 3500

MENU

1. Deposit2. Withdraw3. Display4. ExitEnter your choice: 3

ACC NO NAME Amount101 Gayathri 3500102 Anitha 6000

RESULT: Thus the c++ program has been executed successfully.

Page 28: Oopl Record(2)

HIERARCHICAL INHERITANCE

AIM: To write a c++ program to implement the hierarchical inheritance.

ALGORITHM:

1. Start the process.

2. Create the class comp with its member function.

3. Derived the class price as comp base class as public, with its data members.

4. Derived the derived class system as comp base class as public, with its data member.

5. Read the inputs using get and gets function.

6. Display the information from the derived class.

7. Stop.

Page 29: Oopl Record(2)

SOURCE CODE:

#include<iostream.h>#include<conio.h>class comp{char name[15];char model[10];public:void read(){cout<<"\n Enter the company name: ";cin>>name;cout<<"\n Enter the model: ";cin>>model;}void write(){cout<<"\n Company name: "<<name;cout<<"\n Model: "<<model;}};class price:public comp{long int price;public:void get(){read();cout<<"\n Enter the price: ";cin>>price;}void put(){write();cout<<"\n Price: "<<price;}};class system:public comp{char perform[10];public:void gets(){cout<<"\n Give the performance: ";cin>>perform;

Page 30: Oopl Record(2)

}void puts(){cout<<"\n Performance: "<<perform;}};void main(){clrscr();price p;system s;p.get();s.gets();clrscr();p.put();s.puts();getch();}

Page 31: Oopl Record(2)

SAMPLEINPUT AND OUTPUT:

Company name: Intel Model: laptop Price: 42000 Performance: good

RESULT: Thus the c++ program has been executed successfully.

Page 32: Oopl Record(2)

FUNCTION OVERLOADING

AIM:To write a c++ program to find the volume of cube, rectangle and cylinder using function

overloading.

ALGORITHM:

1. Start the process.

2. Define a class named shape.

3. Declare the function volume with one argument, two arguments and three arguments

as parameter.

4. Create a objects s of type shape in main function.

5. Get the value of r call member function s.volume(r).

6. Get the values of r, h call member function s.volume(r,h).

7. Get the values of r,b,h call member function s.volume (r,b,h).

8. Stop.

Page 33: Oopl Record(2)

SOURCE CODE:

#include<iostream.h>#include<conio.h>#include<math.h>#define pi 3.141class shape{public:void volume(int);void volume(int,float);void volume(int,float,double);};void shape::volume(int r){int vol=pow(r,3);cout<<"\n\n \tVolume of Cube is:\t"<<vol;}void shape::volume(int r,float h){float vol=pi*r*h;cout<<"\n\n \tVolume of Cylinder is :\t"<<vol;}void shape::volume(int l,float b,double h){double vol=l*b*h;cout<<"\n\n \tArea of Rectangle is :\t"<<vol;}void main(){shape s;int r; float h,l; double b;clrscr();cout<<"\n Enter the value for R:\t";cin>>r;s.volume(r);cout<<"\n\n Enter the value for R & H:\t";cin>>r>>h;s.volume(r,h);cout<<"\n\n Enter the value for L,B,H:\t";cin>>l>>b>>h;s.volume(l,h,b);getch();}

Page 34: Oopl Record(2)

SAMPLE INPUT AND OUTPUT:

Enter the value of r: 2

Volume of cube is: 8

Enter the value of r, h: 4,5

Volume of cylinder is: 251.199997

Enter the value of l, b, h: 1 2 3

Area of rectangle is: 6

RESULT: Thus the c++ program has been executed successfully.

Page 35: Oopl Record(2)

VIRTUAL FUNCTION

AIM:To write a c++ program to find the area of two shapes for virtual function.

ALGORITHM:

1. Start the process.

2. Declare a base class named figure with the variables x and y.

3. Set values for the variables using the function called setdim( ).

4. Define a virtual function called showarea( ).

5. Derived a class triangle from figure and define the function showarea ( ) to display the

area of triangle

6. Derived a class rectangle from figure and define the function showarea ( ) to display the

area of rectangle.

7. Declare a base class pointer variable and objects for the class rectangle and triangle.

8. Using the pointer variable assign the address of triangle and find the area of rectangle

using the virtual function showarea( ).

9. Using the pointer variable assign the address of rectangle and find the area of rectangle

using the virtual function showarea( ).

10. Stop.

Page 36: Oopl Record(2)

SOURCE CODE:

#include <iostream.h>class figure {protected:double x, y;public:void setdim(double i, double j) { x = i; y = j;}virtual void showarea( ) {cout << "No area computation defined ";cout << "for this class.\n";}} ;class triangle : public figure {public:void showarea( ){cout << "Triangle with height ";cout << x << " and base " << y;cout << " has an area of ";cout << x * 0.5 * y << ".\n";}};class rectangle : public figure {public:void showarea( ) {cout << "Rectangle with dimensions ";cout << x << "x" << y;cout << " has an area of ";cout << x *  y << ".\n";}};int main( ){figure *p;  triangle t;  rectangle s;

Page 37: Oopl Record(2)

p = &t;p->setdim(10.0, 5.0);p->showarea();p = &s;p->setdim(10.0, 5.0);p->showarea();  return 0;}

SAMPLE INPUT AND OUTPUT:

Triangle with height 10 and base 5 has an area of 25.Rectangle with dimensions 10x5 has an area of 50.

Page 38: Oopl Record(2)

RESULT:

Thus the c++ program has been executed successfully.

EXCEPTION HANDLING

AIM:

To write a c++ program to perform execution handling.

ALGORITHM:

Page 39: Oopl Record(2)

1. Start the process.

2. Get the values of the divided a and divisor b.

3. Check whether the divisor b is zero, if it is true then throw an exception to the catch

block.

4. Otherwise divide a by b and print the result.

5. Stop the process.

SOURCE CODE:

#include<iostream.h>#include<conio.h>int main(){int a,b;cout<<"\n Enter the value of a";cin>>a;int x=a%2;

Page 40: Oopl Record(2)

try{if(x==0){cout<<"\n result="<<x<<"is an even no.";}else{throw(x);}}catch(int i){cout<<"\n exception caught:";cout<<x<<"\n is an odd no";}getch();return 0;}

SAMPLE INPUT AND OUTPUT:

Enter the value of a: 4Result=0, is an even no.

Page 41: Oopl Record(2)

RESULT: Thus the c++ program has been executed successfully.

CLASS TEMPLATE

AIM:

To write a c++ program to perform sum of array of elements using class template.

ALGORITHM:

Page 42: Oopl Record(2)

1. Start the process.

2. Define the template with class t.

3. Create a class sum with its data member function.

4. Get the data using the function getelements().

5. Add the two elements.

6. Get integer and float array of elements and perform the addition process.

7. Stop.

SOURCE CODE:

#include<iostream.h>#include<conio.h>template<class t>class sum{

t a[10],result;

Page 43: Oopl Record(2)

int i;public:void getelements(){for(i=0;i<10;i++)cin>>a[i];}void addition(){result=0;for(i=0;i<10;i++)result=result+a[i];cout<<"Sum of array elements:"<<result;}};void main(){sum<int>s1;sum<float>s2;clrscr();cout<<"Enter the integer array of elements: \n";s1.getelements();s1.addition();getch();clrscr();cout<<"Enter float array elements:";s2.getelements();s2.addition();getch();}

SAMPLE INPUT AND OUTPUT:

Enter the integer array of elements:123456

Page 44: Oopl Record(2)

78910Sum of array elements:55

Enter float array elements:1.12.23.34.45.56.67.78.89.91.0Sum of array elements:50.5

RESULT: Thus the c++ program has been executed successfully.

TEMPLATE FUNCTION

AIM: To write a c++ program for sorting the values using template function.

ALGORITHM:

1. Start the process.

Page 45: Oopl Record(2)

2. Define the template with type1,type2 as class.

3. Read the n values.

4. Read n float values as d.

5. Read n character as C.

6. Read n integer values as A.

7. Sort elements using sort function with type1,type2.

8. Display the sorted elements.

9. Stop.

SOURCE CODE:

#include<iostream.h>#include<conio.h>template<class type1, class type2>void sort(type1 x[],type2 y){type1 t;type2 i,j;for(i=0;i<y;i++){

Page 46: Oopl Record(2)

for(j=0;j<y-1;j++){if(x[j]>=x[j+1]){t=x[j];x[j]=x[j+1];x[j+1]=t;}}}for(i=0;i<y;i++)cout<<"\t"<<x[i];}void main(){int n,i;float d[20];int a[20];char c[20];clrscr();cout<<"\n INPUT";cout<<"\n\tENTER THE VALUE";cin>>n;cout<<"\n\t ENTER"<<n<<"FLOAT VALUE";for(i=0;i<n;i++)cin>>d[i];cout<<"\n\t ENTER"<<n<<"INTEGER VALUE";for(i=0;i<n;i++)cin>>a[i];cout<<"\n\t ENTER"<<n<<"CHAR VALUE";for(i=0;i<n;i++)cin>>c[i];cout<<"\n\t AFTER SORTING";cout<<"\n\t FLOAT VALUES";

sort(d,n);cout<<"\n\t INTEGER VALUE";sort(a,n);cout<<"\n\t CHAR VALUE";sort(c,n);}

Page 47: Oopl Record(2)

SAMPLE INPUT AND OUTPUT:

ENTER THE N VALUE: 5

ENTER 5 FLOAT VALUE: 9.6 5.3 3.2 9.1 2.1

ENTER 5 INTEGER VALUE: 8 6 4 3 10

ENTER 5 CHAR VALUE: F K L E W

Page 48: Oopl Record(2)

AFTER SORTING

FLOAT VALUES : 2.1 3.2 5.3 9.1 9.6

INTEGER VALUES: 3 4 6 8 10

CHAR VALUES : E F K L W

RESULT: Thus the c++ program has been executed successfully.

I/O STREAMS

AIM:

To write a c++ program to perform student details using i/o streams.

ALGORITHM:

1. Start the process.

2. Declare the base class name with variable name and marks.

Page 49: Oopl Record(2)

3. Declare the function as input data.

4. Define a function input data.

5. Define a function display data from class.

6. Create a object to call the member function.

7. Stop.

SOURCE CODE:

#include<iostream.h>#include<conio.h>#include<iomanip.h>#define maxmarks 500class student{char name[10];int marks;public:void inputdata();

Page 50: Oopl Record(2)

void displaydata();};void student::inputdata(){cout<<"\n Enter the name of the student:";cin>>name;cout<<"\n Enter the marks :";cin>>marks;}void student::displaydata(){cout.width(20);cout<<name;cout.width(8);cout<<marks;cout.width(15);cout<<int((float)marks/maxmarks*100);}void main(){int i,n;student s[10];clrscr();cout<<"\n Enter the no. of students :";cin>>n;for(i=0;i<n;i++){cout<<"\n Enter student"<<i+1<<"details.."<<endl;s[i].inputdata();}cout<<" \n STUDENTS DETAILS"<<endl;cout<<" \n~~~~~~~~~~~~~~~~~"<<endl;cout.width(8);

cout<<" ROLL NO.";cout.width(20);cout<<" STUDENT NAME";cout.width(8);cout<<" MARKS:";cout.width(15);cout<<"% of marks"<<endl;for(i=0;i<n;i++){cout.width(8);cout<<i+1;s[i].displaydata();

Page 51: Oopl Record(2)

cout<<endl;}getch();}

SAMPLE INPUT AND OUTPUT:

Enter the no. of students :2

Enter student1details..

Enter the name of the student: Gayathri

Enter the marks :495

Enter student2details..

Page 52: Oopl Record(2)

Enter the name of the student: Anitha

Enter the marks :493

STUDENTS DETAILS

ROLL NO. STUDENT NAME MARKS: % of marks 1 Gayathri 495 99 2 Anitha 493 98

RESULT: Thus the c++ program has been executed successfully.

SAMPLE PROGRAM IN JAVA

AIM:

To write a java program to perform prime numbers.

ALGORITHM:

1. Start the program.

2. Declare the package needed by the program.

3. Create a class Prime.

Page 53: Oopl Record(2)

4. Declare the variable n,c,i,j.

5. Assign c=0, and check the condition.

6. Increment the counter.

7. Print the prime numbers.

8. Stop.

SOURCE CODE:

import java.lang.*;class Prime {public static void main(String arg[]){int n,c,i,j;n=Integer.parseInt(arg[0]);System.out.println("prime numbers are");for(i=1;i<=n;i++){c=0;

Page 54: Oopl Record(2)

for(j=1;j<=i;j++){if(i%j==0)c++;}if(c==2)System.out.println(" "+i);}}}

OUTPUT:

Page 55: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.

SAMPLE PROGRAM IN JAVA

Page 56: Oopl Record(2)

AIM:

To write a java program to perform the given string is palindrome or not.

ALGORITHM:

1. Start the program.

2. Declare the package needed by the program.

3. Create a class Palindrome.

4. Get the input by using datainputstream.

5. Initialize flag=1 and left=0.

6. If word in the left string is not equal to word in the right string.

7. Assign flag=0 and increment left and then decrement right.

8. If it is equal then print the given string is a palindrome.

9. Otherwise print not a palindrome.

10. Stop.

SOURCE CODE:

import java.lang.*;

Page 57: Oopl Record(2)

import java.io.*;import java.util.*;class Palindrome{

public static void main(String arg[ ]) throws IOException { DataInputStream dis=new DataInputStream(System.in); String word=dis.readLine( ); int flag=1; int left=0; int right=word.length( )-1; while(left<right) { if(word.charAt(left)!=word.charAt(right)) { flag=0; } left++; right--; } if(flag==1) System.out.println("palindrome"); else System.out.println("not palindrome"); } }

OUTPUT:

Page 58: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.

SINGLE INHERITANCE

Page 59: Oopl Record(2)

AIM:

To write a java program to perform area and volume using single inheritance.

ALGORITHM:

1. Start the program.

2. Create a class Room.

3. Declare the variable length and breadth.

4. Using the method room assign length=x and breadth=y.

5. Return the value for area.

6. Create a class BedRoom and extends room.

7. Declare the variable height.

8. Return the value for volume.

9. Allocate memory for bedroom and call the required method.

10. Print the values for area and volume.

11. Stop.

SOURCE CODE:

class Room{int length;

Page 60: Oopl Record(2)

int breadth;Room(int x,int y){length=x;breadth=y;}int area(){return(length*breadth);}}class BedRoom extends Room{int height;BedRoom(int x,int y,int z){super(x,y);height=z;}int volume( ){return(length*breadth*height);}}class InherTest{public static void main(String args[]){BedRoom room1=new BedRoom(14,12,10);int area1=room1.area( );int volume1=room1 . volume ( );System.out.println("Area1="+ area1);System.out.println("Volume="+ volume1);}}

OUTPUT:

Page 61: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.

MULTILEVEL INHERITANCE

Page 62: Oopl Record(2)

AIM:

To write a java program to display student details using multilevel inheritance.

ALGORITHM:

1. Start the program.

2. Declare the package needed by the program.

3. Create a class single and declare its variables.

4. Create a another class singleinh and allocate memory for each subjects.

5. In member function get the details for the student.

6. Create a class multilevel extends from the singlinh and display the name, rollno, subjects,

total and average.

7. Create a class simple

8. Display the student details.

9. Stop.

SOURCE CODE:import java.io.*;

Page 63: Oopl Record(2)

class single{int rollno[]=new int[100];}class singleinh extends single{DataInputStream d=new DataInputStream(System.in);int sub1[]=new int[23];int sub2[]=new int[23];int sub3[]=new int[23];int n;String name[]=new String[50];void getdetails(){try{System.out.print("Enter the no of Students: ");String data=d.readLine();n=Integer.parseInt(data);for(int i=0;i<n;i++){System.out.print("Enter the RollNo: ");String roll=d.readLine();rollno[i]=Integer.parseInt(roll);System.out.print("Enter the Name: ");name[i]=d.readLine();System.out.print("Enter the subject1: ");String subj1=d.readLine();sub1[i]=Integer.parseInt(subj1);System.out.print("Enter the subject2: ");String subj2=d.readLine();sub2[i]=Integer.parseInt(subj2);System.out.print("Enter the subject3:");String subj3=d.readLine();sub3[i]=Integer.parseInt(subj3);}}catch(Exception e){}}}class multilevel extends singleinh{void putdetails(){int total,average;System.out.println("\n\tRoll No.\tName \tSub1 \tSub2 \tSub3 \tTotal \tAvg");// + "\tTotal: " + total[i] + "\tAvg:"+ avg[i]);for(int i=0;i<n;i++)

Page 64: Oopl Record(2)

{total=sub1[i]+sub2[i]+sub3[i];average=total/3;System.out.println("\n\t " + rollno[i] + "\t\t"+name[i] + "\t " + sub1[i] + "\t " + sub2[i] + "\t " + sub3[i] + "\t "+ total + "\t "+ average);}}}public class Simple{public static void main(String arg[]){ System.out.println("\n=====STUDENT DATABASE=====\n");int stud,choice;String str,str1;try{DataInputStream obj=new DataInputStream(System.in); multilevel s=new multilevel();while(true){ System.out.println("\nChoose your choice...");System.out.println("1) ENTER STUDENT DETAIL");System.out.println("2) DISPLAY ALL RECORDS");System.out.println("3) Exit ");System.out.print("Enter your choice : ");str=obj.readLine();choice=Integer.parseInt(str);switch(choice){case 1 :

s.getdetails();break;

case 2 :s.putdetails();break;

case 3 : System.out.println("\nThanks for Visiting ....");System.exit(1);

}}}catch(Exception e){System.out.println(e);} }}OUTPUT:

Page 65: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.

INTERFACE

Page 66: Oopl Record(2)

AIM:

To write a java program to perform stack operations using interface.

ALGORITHM:

1. Start the program.

2. Declare the packages needed by the program.

3. Declare the member function.

4. Create a class Stackimp.

5. Initialize top=-1.

6. Using push() insert the element into the stack.

7. Using pop() delete the element from the stack.

8. Display the values present in the stack.

9. Stop.

SOURCE CODE:

Page 67: Oopl Record(2)

import java.lang.*;import java.io.*;import java.util.*;interface Mystack{ int n=10; public void pop(); public void push(); public void peek(); public void display();}class Stackimp implements Mystack{int stack[]=new int[n];int top=-1;public void push(){try{ DataInputStream dis=new DataInputStream(System.in); if(top==(n-1)){ System.out.println("overflow"); return; } else { System.out.println("enter element"); int ele=Integer.parseInt(dis.readLine()); stack[++top]=ele;}}catch(Exception e){System.out.println("e"); }} public void pop(){ if(top<0){ System.out.println("underflow"); return; } else{

Page 68: Oopl Record(2)

int popper=stack[top]; top--; System.out.println("popped element" +popper); } } public void peek(){if(top<0){System.out.println("underflow"); return;}else{int popper=stack[top];System.out.println("popped element" +popper);}} public void display(){if(top<0){System.out.println("empty");return;}else{String str=" ";for(int i=0;i<=top;i++) str=str+" "+stack[i];System.out.println("elements are"+str);}}} class Stackadt{ public static void main(String arg[])throws IOException{DataInputStream dis=new DataInputStream(System.in); Stackimp stk=new Stackimp(); int ch=0;do{System.out.println("enter ur choice for 1.push 2.pop 3.peek 4.display5.exit ");ch=Integer.parseInt(dis.readLine( )); switch(ch)

Page 69: Oopl Record(2)

{ case 1:stk.push(); break; case 2:stk.pop(); break; case 3:stk.peek(); break; case 4:stk.display(); break;case 5:System.exit(0);}}while(ch<=5);}}

OUTPUT:

Page 70: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.

PACKAGE

Page 71: Oopl Record(2)

AIM:

To write a java program to perform a package.

ALGORITHM:

1. Start the program.

2. Declare the package needed by the program.

3. Create a package div ,mul ,sub and add1.

4. Get the inputs through keyboard.

5. Create a class myclass.

6. Allocate memory for each packages.

7. Using while statement check the condition if it true perform the corresponding operations

else exit the loop structure.

8. Display the result.

9. Stop.

SOURCE CODE:

Page 72: Oopl Record(2)

package mypack;import java.io.*;public class Div{DataInputStream objd = new DataInputStream(System.in);public void divTwo(){try{System.out.print("\nEnter the First No: ");int dd1 = Integer.parseInt(objd.readLine());System.out.print("\nEnter the Second NO: ");int dd2 = Integer.parseInt(objd.readLine() );int d1 = dd1/dd2;System.out.print("\n\n Result is : " + d1);}catch(Exception e){}} }package mypack;import java.io.*;public class Mul{DataInputStream objm = new DataInputStream(System.in);public void mulTwo(){try{System.out.print("\nEnter the First No: ");int mm1 = Integer.parseInt(objm.readLine());System.out.print("\nEnter the Second NO: ");int mm2 = Integer.parseInt(objm.readLine() );int m1 = mm1*mm2;System.out.print("\n\n Result is : " + m1);}catch(Exception e){}} }

package mypack;import java.io.*;

Page 73: Oopl Record(2)

public class Sub{ DataInputStream objs = new DataInputStream(System.in); public void subTwo(){try {System.out.print("\nEnter the First No: ");int ss1 = Integer.parseInt(objs.readLine());System.out.print("\nEnter the Second NO: ");int ss2 = Integer.parseInt(objs.readLine() );int s1 = ss1-ss2;System.out.print("\n\n Result is : " + s1);}catch(Exception e){}}}

package mypack;import java.io.*;public class Add1{DataInputStream obja = new DataInputStream(System.in);public void addTwo(){try{System.out.print("\nEnter the First No: ");int aa1 = Integer.parseInt(obja.readLine());System.out.print("\nEnter the Second NO: ");int aa2 = Integer.parseInt(obja.readLine());int a1 = aa1+aa2;System.out.print("\n\n Result is : " + a1);}catch(Exception e){} }}

package mypack;import java.io.*;

Page 74: Oopl Record(2)

public class myClass{ public static void main(String agrs[])throws IOException{Add1 a = new Add1();Sub s = new Sub();Mul m = new Mul();Div d = new Div();DataInputStream obj = new DataInputStream(System.in);while(true){System.out.println("\n\n\t\tArithmetic Operation");System.out.println("\n\t1.Addition");System.out.println("\n\t2.Subtraction");System.out.println("\n\t3.Multiplication");System.out.println("\n\t4.Division");System.out.println("\n\t5.Exit");System.out.print("\nEnter the choice: ");String choice1 = obj.readLine();int choice = Integer.parseInt(choice1);switch(choice){case 1:a.addTwo();break;case 2:s.subTwo();break;case 3:m.mulTwo();break;case 4:d.divTwo();break;case 5:System.exit(1); break;}} }}

OUTPUT:

Page 75: Oopl Record(2)

RESULT: Thus the java program has been executed.

EXCEPTION HANDLING

Page 76: Oopl Record(2)

AIM:

To write a java program to perform exception handling.

ALGORITHM:

1. Start the program.

2. Create a class dividerdemo.

3. In try block get input elements in a and b.

4. In catch block catch the e.

5. Print error in denominator.

6. Again in catch block catch the e.

7. Print error in index value.

8. Again in catch block catch the n.

9. Print data type error and at last print finally block.

10. Stop.

SOURCE CODE:

Page 77: Oopl Record(2)

class dividerdemo{public static void main(String[] args){try{int a=Integer.parseInt(args[0] );int b=Integer.parseInt(args[1] );System.out.println("Quotient"+ a/b);}catch(ArithmeticException e){System.out.println("Error in denominator");}catch(ArrayIndexOutOfBoundsException e){System.out.println("Error in index value");}catch( NumberFormatException n){System.out.println("Data type error");}finally{System.out.println("Finally block");}}}

OUTPUT:

Page 78: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.

MULTITHREADED PROGRAMMING

Page 79: Oopl Record(2)

AIM:

To write a java program that creates three threads. First thread displays”Good Morning”

every one second, the second thread displays “Hello” every two seconds and the third thread

displays “Welcome” every three seconds using multithreading concept.

ALGORITHM:

1. Start the program.

2. Create a class Frst.

3. Create a thread t and using the method frst() print “Good Morning”.

4. In void run() method print the given values and set the time for every one second to print

good morning.

5. Create a class sec.

6. Create a thread t and using the method sec() print “Hello” for every two seconds

7. Create a class third and create a thread t.

8. Using the method third() and print “Welcome” for every three seconds.

9. Stop.

SOURCE CODE:

Page 80: Oopl Record(2)

class Frst implements Runnable{Thread t;Frst(){t=new Thread(this);System.out.println("Good Morning");t.start();}public void run(){for(int i=0;i<10;i++){ System.out.println("Good Morning"+i); try{ t.sleep(1000); } catch(Exception e) { System.out.println(e);}}}}class sec implements Runnable{Thread t;sec(){ t=new Thread(this); System.out.println("hello"); t.start(); } public void run() {for(int i=0;i<10;i++){ System.out.println("hello"+i); try{ t.sleep(2000); } catch(Exception e){ System.out.println(e);

Page 81: Oopl Record(2)

}}}} class third implements Runnable{Thread t;third(){t=new Thread(this);System.out.println("welcome"); t.start();} public void run(){for(int i=0;i<10;i++){System.out.println("welcome"+i);try{ t.sleep(3000);} catch(Exception e){ System.out.println(e);}}}}public class Multithread { public static void main(String arg[]){ new Frst(); new sec(); new third(); } }

OUTPUT:

Page 82: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.

FILES

Page 83: Oopl Record(2)

AIM:

To write a java program that displays the number of characters, lines and words in a

textfile.

ALGORITHM:

1. Start the program.

2. Declare the packages needed by the program.

3. Create a class filecount.

4. Declare ccount,lcount and wcount to zero.

5. Set the path in fileinputstream.

6. Check the condition if i is not equal to -1 .

7. Increment the ccounter.

8. If it is string means increment the lcounter and if it is a character means increment the

wcounter.

9. Display the result.

10. Close the file.

11. Stop.

SOURCE CODE

Page 84: Oopl Record(2)

import java.lang.*;import java.io.*;class FileCount{public static void main(String arg[]){int ccount=0,lcount=0,wcount=0;try{FileInputStream f=new FileInputStream("Z:/week 3/Palindrome.java");int i;do{i=f.read();if(i!=-1){ccount++;if(i=='\n')lcount++;if((char)i==' '||(char)i=='\n')wcount++;} }while(i!=-1);f.close();System.out.println("line count is "+lcount);System.out.println("Character count is "+ccount);System.out.println("word count is "+wcount);}catch(Exception e){System.out.println(e);}}}

OUTPUT:

Page 85: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.

SOCKETS

Page 86: Oopl Record(2)

AIM:

To write a java program to perform sockets.

ALGORITHM:

1. Start the program.

2. Declare the packages needed by the program.

3. Create a class DatagramProgram1.

4. Allocate memory for socket and packet.

5. Receive the input from the packet and store the result in str.

6. Display the result.

7. Create a class DatagramProgram2.

8. Get the ip address and allocate memory for socket and packet.

9. Declare the string1=hello.

10. Display the string.

11. Stop.

SOURCE CODE:

Page 87: Oopl Record(2)

SERVER SIDE:import java.net.*;class DatagramProgram1{public static void main(String[] args){try{int port=Integer.parseInt("4444");DatagramSocket ds=new DatagramSocket(port);byte buffer[]=new byte[20];while(true){DatagramPacket dp=new DatagramPacket(buffer,buffer.length);ds.receive(dp);String str=new String(dp.getData());System.out.println(str);}}catch(Exception e){e.printStackTrace();}}}

CLIENT SIDE:import java.net.*;class DatagramProgram2{public static void main(String[] args){try{InetAddress ia=InetAddress.getByName("127.0.0.1");int port=Integer.parseInt("4444");DatagramSocket ds=new DatagramSocket();String s1="Hello";byte buffer[]=s1.getBytes();DatagramPacket dp=new DatagramPacket(buffer,buffer.length,ia,port);ds.send(dp);}catch(Exception e){System.out.println("Exception:"+e);}}}OUTPUT:

Page 88: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.

APPLET

Page 89: Oopl Record(2)

AIM:

To write a java program that works as a simple calculator. Use a grid layout to arrange

buttons for the digits +,-,*,/,% operations. Add text field to display the result.

ALGORITHM:

1. Start the program.

2. Declare the packages needed by the applet program.

3. Create a class calculator.

4. Declare textfield, button, panel and operators.

5. In init() method create panel and button that used for calculator.

6. Compare the event with operator.

7. If it is equal return result. Otherwise not.

8. Display the calculator using appletviewer.

9. Stop.

SOURCE CODE:

Page 90: Oopl Record(2)

import java.awt.*;import java.applet.*;import java.awt.event.*;

/*<applet code=Calculator width=200 height=200></applet>*/

public class Calculator extends Applet implements ActionListener{TextField t1;String a="",b;String oper="",s="",p="";int first=0,second=0,result=0;Panel p1;Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9;Button add,sub,mul,div,mod,res,space;public void init(){Panel p2,p3;p1=new Panel();p2=new Panel();p3=new Panel();t1=new TextField(a,20);p1.setLayout(new BorderLayout());p2.add(t1);b0=new Button("0");b1=new Button("1");b2=new Button("2");b3=new Button("3");b4=new Button("4");b5=new Button("5");b6=new Button("6");b7=new Button("7");b8=new Button("8");b9=new Button("9");add=new Button("+");sub=new Button("-");mul=new Button("*");div=new Button("/");mod=new Button("%");res=new Button("=");space=new Button("c");p3.setLayout(new GridLayout(4,4));b0.addActionListener(this);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);

Page 91: Oopl Record(2)

b4.addActionListener(this);b5.addActionListener(this);b6.addActionListener(this);b7.addActionListener(this);b8.addActionListener(this);b9.addActionListener(this);add.addActionListener(this);sub.addActionListener(this);mul.addActionListener(this);div.addActionListener(this);mod.addActionListener(this);res.addActionListener(this);space.addActionListener(this);p3.add(b0);p3.add(b1);p3.add(b2);p3.add(b3);p3.add(b4);p3.add(b5);p3.add(b6);p3.add(b7);p3.add(b8);p3.add(b9);p3.add(add);p3.add(sub);p3.add(mul);p3.add(div);p3.add(mod);p3.add(res);p3.add(space);p1.add(p2,BorderLayout.NORTH);p1.add(p3,BorderLayout.CENTER);add(p1);} public void actionPerformed(ActionEvent ae){a=ae.getActionCommand();if(a=="0"||a=="1"||a=="2"||a=="3"||a=="4"||a=="5"||a=="6"||a=="7"||a=="8"||a=="9"){t1.setText(t1.getText()+a);}if(a=="+"||a=="-"||a=="*"||a=="/"||a=="%"){first=Integer.parseInt(t1.getText());oper=a;

Page 92: Oopl Record(2)

t1.setText("");} if(a=="="){if(oper=="+")result=first+Integer.parseInt(t1.getText());if(oper=="-")result=first-Integer.parseInt(t1.getText());if(oper=="*")result=first*Integer.parseInt(t1.getText());if(oper=="/")result=first/Integer.parseInt(t1.getText());if(oper=="%")result=first%Integer.parseInt(t1.getText());t1.setText(result+"");}if(a=="c")t1.setText("");}}

OUTPUT:

Page 93: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.

MOUSE EVENT HANDLING

Page 94: Oopl Record(2)

AIM:

To write a java program for handling mouse events.

ALGORITHM:

1. Start the program.

2. Declare the packages needed by the program.

3. Create a class mouse and initialize x and y values.

4. Inside the member function declare the text as we need to display in the appletviewer.

5. Set the background and foreground color to display on the appletviewer.

6. Display the text.

7. Stop.

SOURCE CODE:

Page 95: Oopl Record(2)

import java.io.*;import java.applet.Applet;import java.awt.*;import java.awt.event.*;

/*<applet code=Mouse height=200 width=300></applet>*/

public class Mouse extends Applet implements MouseListener,MouseMotionListener{String txt="";int x=10,y=30;public void init(){addMouseListener(this);addMouseMotionListener(this);}

public void mouseClicked(MouseEvent me){txt="Mouse Clicked";setForeground(Color.pink);repaint();}

public void mouseEntered(MouseEvent me){txt="Mouse Entered";repaint();}

public void mouseExited(MouseEvent me){txt="Mouse Exited";setForeground(Color.blue);repaint();}

public void mousePressed(MouseEvent me){txt="Mouse Pressed";setForeground(Color.blue);repaint();}

Public void mouseMoved(MouseEvent me){

Page 96: Oopl Record(2)

txt="Mouse Moved";setForeground(Color.red);repaint();}

public void mouseDragged(MouseEvent me){txt="Mouse Dragged";setForeground(Color.green);repaint();}

public void mouseReleased(MouseEvent me){txt="Mouse Released";setForeground(Color.yellow);repaint();}

public void paint(Graphics g){g.drawString(txt,30,40);showStatus("Mouse events Handling");}}

OUTPUT:

Page 97: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.

SWINGAIM:

Page 98: Oopl Record(2)

To write a java program to perform arithmetic operation using the swing component

JOptionPane.

ALGORITHM:

1. Start the program.

2. Declare the packages needed by the program.

3. Create a class addition.

4. In member function addtwo() obtain the user input from JOptionPane input dialogues.

5. Convert String inputs to integer values for use in a calculation.

6. Display result in a JOptionPane message dialog.

7. Create a class sub.

8. In member function subtwo() obtain the user input from JOptionPane input dialogues.

9. Covert String inputs to integer values for use in a calculation.

10. Display result in a JOptionPane message dialog.

11. Create a class mul.

12. In member function multwo() obtain the user input from JOptionPane input dialogues.

13. Covert String inputs to integer values for use in a calculation.

14. Display result in a JOptionPane message dialog.

15. Create a class div.

16. In member function divtwo() obtain the user input from JOptionPane input dialogues.

17. Convert String inputs to integer values for use in a calculation.

18. Display result in a JOptionPane message dialog.

19. Create a class myclass and allocate memory for each operations.

20. Display the result.

21. Stop.

SOURCE CODE:

Page 99: Oopl Record(2)

import java.io.*;import javax.swing.*;class Addition{ void addTwo(){String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); String secondNumber = JOptionPane.showInputDialog( "Enter second integer" );int number1 = Integer.parseInt( firstNumber );int number2 = Integer.parseInt( secondNumber ); int sum = number1 + number2; // add numbers JOptionPane.showMessageDialog( null, "The sum is " + sum, "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE ); }} class Sub{public void subTwo(){ String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); String secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); int number1 = Integer.parseInt( firstNumber ); int number2 = Integer.parseInt( secondNumber ); int sum = number1 - number2; // add numbers JOptionPane.showMessageDialog( null, "The sum is " + sum, "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE ); }} class Mul{public void mulTwo(){ String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); String secondNumber = JOptionPane.showInputDialog( "Enter second integer" );int number1 = Integer.parseInt( firstNumber );int number2 = Integer.parseInt( secondNumber ); int sum = number1 * number2; // add numbersJOptionPane.showMessageDialog( null, "The sum is " + sum, "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE ); }} class Div{public void divTwo(){String firstNumber = JOptionPane.showInputDialog( "Enter first integer" );

Page 100: Oopl Record(2)

String secondNumber = JOptionPane.showInputDialog( "Enter second integer" );int number1 = Integer.parseInt( firstNumber );int number2 = Integer.parseInt( secondNumber ); int sum = number1 / number2; // add numbersJOptionPane.showMessageDialog( null, "The sum is " + sum, "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE ); }} public class myclass{ public static void main(String agrs[])throws IOException { Addition a = new Addition(); Sub s = new Sub(); Mul m = new Mul(); Div d = new Div();

DataInputStream obj = new DataInputStream(System.in);

while(true) { System.out.println("\n\n\t\tArithmetic Operation"); System.out.println("\n\t1.Addition"); System.out.println("\n\t2.Subtraction"); System.out.println("\n\t3.Multiplication"); System.out.println("\n\t4.Division"); System.out.println("\n\t5.Exit");

System.out.print("\nEnter the choice: "); String choice1 = obj.readLine(); int choice = Integer.parseInt(choice1);

switch(choice) { case 1: a.addTwo(); break; case 2: s.subTwo(); break; case 3: m.mulTwo(); break; case 4: d.divTwo(); break;

Page 101: Oopl Record(2)

case 5: System.exit(1); break; } } }}

OUTPUT:

Page 102: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.

REMOTE METHOD INVOCATION

Page 103: Oopl Record(2)

AIM:

To write a java program to add and array of elements using the concept of the remote

method invocation.

ALGORITHM:

INTERFACE:

1. Open notepad and create a interface named one and this inherits in the remote class.

2. Give the function in the interface and save as the file with java extension.

3. The file is saved in the name of the AddServerInterface.

IMPLEMENTATION:

1. In the implementation file we have receive the input of the number in the array from the

user through command line output.

2. We add all the values given in the array and we store it in a variable.

3. We then it returns the value in the variable that holds the same value.

SERVER:

1. In the server side we first create object. For the implementation file and bind the names

of the function.

2. This is just to bind the name of the function given in server with the implementation.

CLIENT:

1. In the client side we first get the input method.

2. After getting the input we pass it to the implement for it do the process.

3. Now the implementation file, after completing work return a value.

4. The client catches this value and the value of the sum of array number is printed.

SOURCE CODE:

Page 104: Oopl Record(2)

INTERFACE:

import java.rmi.*;public interface AddServerInterface extends Remote{double add(double d1,double d2)throws RemoteException;}

IMPLEMENTATION:

import java.rmi.*;import java.rmi.server.*;public class AddServerImplementingClass extends UnicastRemoteObject implements AddServerInterface{public AddServerImplementingClass()throws RemoteException{}public double add(double d1,double d2)throws RemoteException{return d1+d2;}}

SERVER:

import java.net.*;import java.rmi.*;public class AddServer{public static void main(String args[]){try{AddServerImplementingClass obj=new AddServerImplementingClass();Naming.rebind("AddServer",obj);}catch(Exception e){System.out.println("Exception"+e);}}}

CLIENT:

Page 105: Oopl Record(2)

import java.rmi.*;public class AddClient{public static void main(String[] args){try{String addServerURL="rmi://"+args[0]+"/AddServer";AddServerInterface obj=(AddServerInterface)Naming.lookup(addServerURL);System.out.println("The first number is ="+args[1]);double d1=Double.parseDouble(args[1]);System.out.println("The second number is ="+args[2]);double d2=Double.parseDouble(args[2]);System.out.println("The sum is "+obj.add(d1,d2));}catch(Exception e){System.out.println("Exception="+e);}}}

OUTPUT:

Page 106: Oopl Record(2)

RESULT: Thus the java program has been executed successfully.