You are on page 1of 49

 

 
 
 
 
 
CS6461- Object Oriented Programming Lab
 
 
 
  Manual
 
 
 
 
 
( IV Semester
 
B.E./EEE Students
for the Academic Year 2017-18 ) 

VALLIAMMAI ENGINEERING COLLEGE  

SRM NAGAR, KATTANKULATHUR – 603 203 

Prepared by 

Mr. M. Mayuranathan, Asst. Professor (Sr.G)


Mr. T. Rajasekaran, Asst. Professor (O.G)
Ms. N. Poornima, Asst. Professor (O.G)

Department of Computer Science & Engineering

Private circulation only


CS6461-OBJECT ORIENTED PROGRAMMING LABORATORY
OBJECTIVES:

• To get a clear understanding of object-oriented concepts.


• To understand object oriented programming through C++ & JAVA.

LIST OF EXPERIMENTS:
Ex.No. Name of the Exercise Page No.
C++ PROGRAMMING
Program using Functions
A (i). Functions with Default Arguments 1
1 A (ii).Functions with Default Arguments 2
B (i).Implementation of Call by Value 3
B (ii).Implementation of Call by Address 4
Simple Classes for understanding Objects, Member Functions &
Constructors
A. Classes with Primitive Data Members 5
2 B. Classes with Arrays as Data Members 7
C. Classes with Pointers as Data Members 9
D. Classes with Constant Data Members 10
E. Classes with Static Member Functions 11
Compile Time Polymorphism
A (i). Unary Operator Overloading 12
3
A (ii). Binary Operator Overloading 14
B. Function Overloading 16
Run Time Polymorphism
A. Inheritance 17
4 B. Virtual Functions 19
C. Templates 20
D. Virtual Base Classes 22
File Handling
5 A. Sequential Access 24
B. Random Access 25
JAVA PROGRAMMING
Simple Java Applications
6 A. Understanding References to an Instant of a Class 26
B. Handling Strings 27
Simple Package Creation
7 A. Creating User Defined Packages 29
B. Creating User Defined Packages - Array of Objects 30
Interfaces
8 A. Implementing User Defined Interfaces 31
B. Implementing Pre Defined Exceptions 32
Threading
9 A. Creation of Threading 34
B. Multi Threading 36
Exception Handling Mechanism in Java
10 A. Implementing Predefined Exceptions 38
B. Implementing User Defined Exceptions 39
11 Additional Exercises in Java 40
OUTCOMES:
• Gain the basic knowledge on Object Oriented concepts.
• Ability to develop applications using Object Oriented Programming Concepts.
• Ability to implement features of object oriented programming to solve real
world problems
Ex. No: 1.A.(i) DEFAULT ARGUMENTS IN C++

AIM:
To write a C++ program to find the sum for the given variables using function with default
arguments.

ALGORITHM:

1) Start
2) Declare the variables and functions.
3) Give the values for two arguments in the function declaration itself.
4) Call function sum() with three values such that it takes one default arguments.
5) Call function sum() with two values such that it takes two default arguments.
6) Call function sum() with one values such that it takes three default arguments
7) Inside the function sum(), calculate the total.
8) Return the value to the main() function.
9) Display the result.
10) Stop.

SOURCE CODE:

#include<iostream.h>
#include<conio.h>
void main()
{
float sum(float p, int q=10, int r=15, int s=20);
int a=2,b=3,c=4,d=5;
clrscr();
cout<<"\n sum="<<sum(0);
cout<<"\n sum="<<sum(a,b,c,d);
cout<<"\n sum="<<sum(a,b,c);
cout<<"\n sum="<<sum(a,b);
cout<<"\n sum="<<sum(a);
cout<<"\n sum="<<sum(b,c,d);
getch();
}
float sum(float i, int j, int k, int l)
{
return(i+j+k+l);
}

OUTPUT:

sum=45
sum=14
sum=29
sum=40
sum=47
sum=32

RESULT:

Thus, the given program for function with default arguments has been written and executed
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 1


Ex. No: 1.A.(ii) DEFAULT ARGUMENTS IN C++

AIM:
To implement function with default arguments.

ALGORITHM:

1. Start
2. Declare the default function.
3. Invoke the default function.
4. Display the result
5. Stop

SOURCE CODE:

#include<iostream.h>
#include<conio.h>
void printLine(char =’_’, int =70);

void main()
{
printLine();
printLine(‘/’);
printLine(‘*’,40);
printLine(‘R’,55);
getch();
}

void printLine(char ch, int count)


{
int i;
cout<<endl;
for(i=0;i<count;i++)
{
cout<<ch;
}
}

OUTPUT:
-----------------------------------
///////////////////////////////////////
****************************
RRRRRRRRRRRRRRRRRRRRRRR

RESULT:

Thus, the given program for function with default arguments has been written and executed
successfully

Prepared by T.Rajasekaran, AP/CSE Page 2


Ex. No: 1.B.(i) IMPLEMENTATION OF CALL BY VALUE

AIM:
To write a C++ program to find the value of a number raised to its power that demonstrates a
function using call by value.

ALGORITHM:
1) Start the program.
2) Declare the variables.
3) Get two numbers as input
4) Call the function power to which a copy of the two variables is passed .
5) Inside the function, calculate the value of x raised to power y and store it in p.
6) Return the value of p to the main function.
7) Display the result.
8) Stop the program.

SOURCE CODE:
#include<iostream.h>
#include<conio.h>
void main()
{
int x,y;
double power(int, int);
clrscr();
cout<<"Enter X, Y:"<<endl;
cin>>x>>y;
cout<<x<<" to the power "<<y <<" is "<< power(x,y);
getch();
}
double power(int x, int y)
{
double p;
p=1.0;
if(y>=0)
{
while(y--)
p=p*x;
}
else
{
while(y++)
p=p/x;
}
return(p);
}

OUTPUT:
Enter X , Y:
2 3
2 to the power 3 is 8

RESULT:
Thus, the given program for implementation of call by value has been written and executed
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 3


Ex. No: 1.B.(ii) IMPLEMENTATION OF CALL BY ADDRESS

AIM:
To write a c++ program and to implement the concept of Call by Address

ALGORITHM:
1. Start the program
2. Include suitable header file
3. Declare a function swap with two pointes variables arguments
4. Declare and initialize the value as two variable in main()
5. Print the value of two variable before swapping
6. Call the swap function by passing address of the two variable as arguments
7. Print the value of two variable after swapping
8. Stop the program

SOURCE CODE:

#include<iostream.h>
#include<conio.h>
void swap(int *x, int *y);
void main()
{
clrscr();
int i,j;
i=10;
j=20;
cout<<"\n the value of i before swapping is:"<<i;
cout<<"\n the value of j before swapping is:"<<j;
swap (&i,&j);
cout<<"\n the value of i after swapping is:"<<i;
cout<<"\n the value of j after swapping is:"<<j;
getch();
}
void swap(int *x, int *y)
{
int temp=*x;
*x=*y;
*y=temp;
}

OUTPUT:
The value of i before swapping is: 20
The value of j before swapping is: 10
The value of i after swapping is: 10
The value of j after swapping is: 20

RESULT:

Thus to write a C++ program and to implement the concept of Call by Address was
successfully completed.

Prepared by T.Rajasekaran, AP/CSE Page 4


Ex.No: 2.A CLASSES WITH PRIMITIVE DATA MEMBERS

AIM:
To write a program in C++ to prepare a student Record using class and object.

ALGORITHM:

1. Start
2. Create a class record.
3. Read the name, Regno ,mark1,mark2,mark3 of the student.
4. Calculate the average of mark as Avg=mark1+mark2+mark3/3
5. Display the student record.
6. Stop.

SOURCE CODE:

#include<iostream.h>
#include<conio.h>
class record
{
public:
char name[20];
int regno;
int m1,m2,m3;
float avg;
void getdata()
{
cout<<"\nenter the name: " ;
cin>>name;
cout<<"enter the regno: ";
cin>>regno;
cout<<"enter the m1,m2,m3: \n";
cin>>m1>>m2>>m3;
}
void calculate()
{
avg=(m1+m2+m3)/3;
}
void display()
{
cout<<"\nName: "<<name;
cout<<"\nRegno: "<<regno;
cout<<"\nMark1: "<<m1;
cout<<"\nMark2: "<<m2;
cout<<"\nMark3: "<<m3;
cout<<"\nAvg: "<<avg;
}
};

void main()
{
record r;
clrscr();
r.getdata();
r.calculate();
r.display();
getch();
}

Prepared by T.Rajasekaran, AP/CSE Page 5


OUTPUT:

Enter the name: Arun


Enter the reg no: 101
Enter the m1, m2, m3: 90 90 90
Name: Arun
Regno: 101
Mark1: 90
Mark2: 90
Mark3: 90
Average:90

RESULT:

Thus the C++ program for implementation of classes and objects was created, executed and
output was verified successfully.

Prepared by T.Rajasekaran, AP/CSE Page 6


Ex.No: 2.B CLASSES WITH ARRAYS AS DATA MEMBERS

AIM:
To write a program in C++ to prepare product information using arrays.

ALGORITHM:

1. Stop
2. Create a class product.
3. Read the product name and cost.
4. Calculate the sum
5. Display the product information.
6. Stop the program.

PROGRAM:
#include<iostream.h>
#include<conio.h>
#include<process.h>
class product
{
int pro_code[50];
float pro_price[50];
int count;
public:
void cnt() { count=0; }
void getproduct();
void displaysum();
void displayproducts();
};

void product::getproduct()
{
cout<<"Enter Product Code: ";
cin>>pro_code[count];
cout<<"Enter Product Cost: ";
cin>>pro_price[count];
count++;
}

void product::displaysum()
{
float sum=0;
for(int i=0;i<count;i++)
{
sum=sum+pro_price[i];
}
cout<<"Total Value:"<<sum<<"\n";
}
void product::displayproducts()
{
cout<<"\n Code Price\n";
for(int i=0;i<count;i++)
{
cout<<"\n"<<pro_code[i];
cout<<" "<<pro_price[i];
}
cout<<"\n";
}
Prepared by T.Rajasekaran, AP/CSE Page 7
void main()
{
product p;
p.cnt(); int x; clrscr();
do
{
cout<<"\n1. Add a product";
cout<<"\n2. Display the product total value";
cout<<"\n3. Display all products";
cout<<"\n4. Quit ";
cout<<"\n Enter your choice: ";
cin>>x;
switch(x)
{
case 1: p.getproduct();break;
case 2: p.displaysum();break;
case 3: p.displayproducts(); break;
case 4: exit(0);
default: cout<<"\n Invalid choice";
}
}while(x!=5);
}

OUTPUT:
1. Add a product
2. Display the product total value
3. Display all products
4. Quit
Enter choice: 1
Enter Product Code : 101
Enter Product Cost : 1000

1. Add a product
2. Display the product total value
3. Display all products
4. Quit
Enter choice: 1
Enter Product Code : 102
Enter Product Cost : 2000

1. Add a product
2. Display the product total value
3. Display all products
4. Quit
Enter choice: 3

Code Price
101 1000
102 2000

RESULT:

Thus the C++ program for implementing arrays as data members was created, executed and
output was verified successfully.

Prepared by T.Rajasekaran, AP/CSE Page 8


Ex.No: 2.C CLASSES WITH POINTERS AS DATA MEMBERS

AIM:
To implement classes with pointers as data members

ALGORITHM:
1. Start
2. Create a class called pointer
3. Define a function called getdata() and display() the variable called r, a and pointer *ptr.
4. Declare a pointer to object in main function
5. Call the function with the help of getdata() and display the result with the help of display()
6. Stop

SOURCE CODE:
#include<iostream.h>
#include<conio.h>
class pointer
{
private:
int r;
float a, *ptr;
public:
void getdata();
void display();
};
void pointer::getdata()
{
cout<<"\n Enter the radius of the Circle: ";
cin>>r;
a=3.14*r*r;
ptr=&a;
}
void pointer::display()
{
cout<<" Value of a = "<<a;
cout<<"\n Address of a = "<<&a;
cout<<"\n Address of ptr = "<<ptr;
cout<<"\n Value stored at ptr = "<<*ptr;
}
void main()
{
clrscr();
cout<<" Area of Circle \n";
pointer obj;
obj.getdata();
obj.display();
getch();
}
OUTPUT:
Enter the radius of the circle: 4
Value of a = 50.24
Address of a = 0x8fa2ffec
Address of ptr = 0x8fa2ffec
Value stored at ptr = 50.24

RESULT:
Thus the C++ program for implementing classes with pointers as data members was created,
executed and output was verified successfully.

Prepared by T.Rajasekaran, AP/CSE Page 9


Ex.No: 2.D CLASSES WITH CONSTANT DATA MEMBER

AIM:
To implement classes with constant data member.

ALGORITHM:

1. Start
2. Create the class called test
3. Declare the integer const variable called i
4. Initialization is occurred during constructor
5. i is a const data member in every object its independent copy is present.
6. Initialize using constructor and the value of i cannot be changed
7. Display the result.

SOURCE CODE:

#include<iostream.h>
#include<conio.h>
class Test
{
const int i;
public:
Test (int x)
{
i=x;
}
};

int main()
{
Test t(10);
Test s(20);
getch();
}

RESULT:

Thus the C++ program for implementing classes with constant data members was created,
executed and output was verified successfully.

Prepared by T.Rajasekaran, AP/CSE Page 10


Ex.No:2.E CLASSES WITH STATIC MEMBER FUNCTION

AIM:
To implement static member function in class.

ALGORITHM:
1. Create class count with static data member as total.
2. Create a member function to increment the count.
3. Declare the static data member using scope resolution operator.
4. Display the count and total value.

SOURCE CODE:
#include <iostream.h>
#include<conio.h>
class count
{
private:
int number;
static int total;
public:
count();
int get_number();
static int get_total();
};
count::count()
{
number=100+ total++;
}
int count::get_number()
{
return number;
}
int count::get_total()
{
return total;
}
int count::total=0;

void main ()
{
clrscr();
cout<<" Total count = "<<count::get_total() <<endl;
count a, b, c;
cout<<" a="<<a.get_number() << endl;
cout<<" b="<<b.get_number() << endl;
cout<<" b="<<c.get_number() << endl;
cout<<" Total count="<<count::get_total() << endl;
getch();
}
OUTPUT:
Total count = 0
a=100
b=101
c=102
Total count = 3
RESULT:
Thus to write a c++ program and to implement the concept of Static Data member function was
successfully completed.

Prepared by T.Rajasekaran, AP/CSE Page 11


EX NO 3.A(1) COMPILE TIME POLYMORPHISM-UNARY OPERATOR OVERLOADING

AIM
To implement the concept of unary operator overloading by creating a C++ program.

ALGORITHM

1. Start the Program


2. Create a class named space and declare necessary data members and member functions and
operator function as member function
3. The operator unary minus is overloaded to perform the operation of changing sign
4. Define member function getdata(), to get three values that is passed as arguments.
5. The operator function is defined where the sign of values is changed.
6. Function display() is defined where the values is displayed before and after sign change.
7. Stop the program.

SOURCE CODE:
#include<iostream.h>
#include<conio.h>
class space
{
int x,y,z;
public:
void getdata(int a,int b,int c);
void display(void);
void operator-();
};
void space::getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void space::display(void)
{
cout<<x<<" ";
cout<<y<<" ";
cout<<z<<"\n";
}
void space::operator-()
{
x=-x;
y=-y;
z=-z;
}
void main()
{
clrscr();
space s;
s.getdata(10,-20,30);
cout<<"s:";
s.display();
-s;
cout<<"s:";
s.display();
getch();

Prepared by T.Rajasekaran, AP/CSE Page 12


OUTPUT:

S = 10 -20 30
S = -10 20 -30

RESULT:

Thus to write a C++ program and to implement the concept of unary operator overloading was
successfully completed.

Prepared by T.Rajasekaran, AP/CSE Page 13


EX No 3.A.(2) COMPILE TIME POLYMORPHISM - BINARY OPERATOR OVERLAODING

AIM :
To write a C++ program to implement the concept of Binary operator overloading.

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

SOURCE CODE:

#include<iostream.h>
#include<conio.h>
class complex
{
float x;
float y;
public:
complex(){}
complex(float real,float imag)
{
x=real;y=imag;
}
complex operator+(complex c);
void display(void);
};

complex complex::operator+(complex c)
{
complex temp;
temp.x=x+c.x;
temp.y=y+c.y;
return(temp);
}

void complex::display(void)
{
cout<<x<<"+j"<<y<<"\n";
}

Prepared by T.Rajasekaran, AP/CSE Page 14


void main()
{
clrscr();
complex c1,c2,c3;
c1=complex(2.5,3.5);
c2=complex(1.6,2.7);
c3=c1+c2;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
cout<<"c3=";
c3.display();
getch();
}

OUTPUT:
C1 = 2.5+j3.5
C2 = 1.6+j2.7
C3 = 4.1+j6.2

RESULT:

Thus to write a C++ program and to implement the concept of binary operator overloading was
successfully completed.

Prepared by T.Rajasekaran, AP/CSE Page 15


Ex.No:3.B FUNCTION OVERLOADING

AIM :
To write a C++ program to implement the concept of Function Overloading

ALGORITHM:
1. Start the program.
2. Create the class printData and functions.
3. In the main(),create the objects.
4. Use print() function to print different values.
5. The values that are passed inside the function call will be matched with the definition
part and appropriate calculations are done.
6. Stop

SOURCE CODE:

#include<iostream.h>
#include<conio.h>
class printData
{
public:
void print(int i)
{
cout << "Printing int: " << i << endl;
}
void print(double f)
{
cout << "Printing float: " << f << endl;
}
void print(char* c)
{
cout << "Printing character: " << c << endl;
}
};

void main()
{
clrscr();
printData pd;
pd.print(5); // Call print to print integer
pd.print(10.5); // Call print to print float
pd.print("Hello C++"); // Call print to print character
getch();
}
OUTPUT:

Printing int:5
Printing float: 10.5
Printing character: Hello C++

RESULT:
Thus to write a C++ program and to implement the concept of function overloading was
successfully completed.

Prepared by T.Rajasekaran, AP/CSE Page 16


Ex.No:4.A INHERITANCE

AIM:
To write a C++ program for implementing the inheritance concept.

ALGORITHM:
1. Start the process.
2. Define the base class with variables and functions.
3. Define the derived class with variables and functions.
4. Get two values in main function.
5. Define the object for derived class in main function.
6. Access member of derived class and base class using the derived class object.
7. Stop the process.

PROGRAM:

#include<iostream.h>
#include<conio.h>
class base
{
public:
int x;
void set_x(int n)
{
x=n;
}
void show_x()
{
cout<<"\n\t Base class...";
cout<<"\n\t x="<<x;
}
};

class derived:public base


{
int y;
public:
void set_y(int n)
{
y=n;
}
void show_xy()
{
cout<<"\n\n\t Derived class...";
cout<<"\n\t x="<<x;
cout<<"\n\t y="<<y;
}
};
void main()
{
derived obj;
int x,y;
clrscr();
cout<<"\n Enter the value of x: ";
cin>>x;
cout<<"\n Enter the value of y: ";
cin>>y;
obj.set_x(x); // inherits the base class

Prepared by T.Rajasekaran, AP/CSE Page 17


obj.set_y(y); // access the member of derived class
obj.show_x(); // inherits the base class
obj.show_xy(); // access the member of derived class
getch();
}

OUTPUT:

Enter the value of x: 10


Enter the value of y: 20

Base class….
x=10

Derived class…..
x=10
y=20

RESULT:

Thus the C++ program for inheritance was created, executed and output was verified
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 18


Ex No 4.B VIRTUAL FUNCTION

AIM:
To write a C++ program to implement the concept of Virtual functions
ALGORITHM:
1. Start the program.
2. Define a base class called base and define a function called display as virtual in it.
3. Derive a new class called derv1,derv2 using a base class called base and define a function
‘display’ in the respective classes.
4. Declare a base class pointer in main function and objects for derv1 and derv2 classes.
6. Assign derv1 and derv2 obj to base pointer
7. Now display function shows the derv1 and derv2 class’ function respectively.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class base
{
public:
virtual void display() {
cout<<"Base class display function is called \n";
}
};
class derv1:public base
{
public:
void display() {
cout<<"\n Derived1's class display function is called \n";
}
};
class derv2:public base
{
public:
void display() {
cout<<"\n Derived2's class display function is called \n";
}
};
void main()
{
clrscr();
base *ptr, b;
ptr=&b;
ptr->display();
derv1 d1;
derv2 d2;
ptr=&d1;
ptr->display();
ptr=&d2;
ptr->display();
getch();
}
OUTPUT:
Base class display function is called
Derived1's class display function is called
Derived2's class display function is called

RESULT:
Thus the C++ program for virtual function was created, executed and output was verified
successfully

Prepared by T.Rajasekaran, AP/CSE Page 19


EX. NO:4.C FUNCTION TEMPLATE
AIM:
To write a C++ program for sorting elements by bubble sort using function templates
ALGORITHM:
1. Start the program
2. Create a class with templates.
3. Create a class for sort functions.
4. Swap the values for using bubble sort
5. Display the result.
SOURCE CODE:
#include<iostream.h>
#include<conio.h>
#define size 10
template <class T>
void bubble(T A[size], int n)
{
T temp;
int i,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(A[i]>A[j])
{
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
}
cout<<"\nThe Sorted List is...";
for(i=0;i<n;i++)
cout<<A[i]<<" ";
}
void main()
{
clrscr();
int A1[size];
float A2[size];
char A3[size]={'s','r','m'};
int i,n;
cout<<"\n\t\t Bubble Sort\n";
cout<<"\t\t-------------------\n";
cout<<"\n Enter the no. of Integer elements: ";
cin>>n;
cout<<"\n Enter the Integer array elements: ";
for(i=0;i<n;i++)
cin>>A1[i];
bubble(A1,n);
cout<<"\n\n Enter the no. of Float elements: ";
cin>>n;
cout<<"\n Enter the Float array elements: ";
for(i=0;i<n;i++)
cin>>A2[i];
bubble(A2,n);
bubble(A3,3);
getch();
}

Prepared by T.Rajasekaran, AP/CSE Page 20


OUTPUT:
Bubble Sort
--------------
Enter the no. of Integer elements: 4
Enter the Integer array elements: 12 11 15 13
The Sorted List is...11 12 13 15

Enter the no. of Float elements: 4


Enter the Float array elements: 10.6 7.5 15.2 13.5
The Sorted List is...7.5 10.6 13.5 15.2

The Sorted List is...m r s

RESULT:
Thus the C++ program for function template was created, executed and output was verified
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 21


EX. NO: 4.D. VIRTUAL BASE CLASS

AIM:
To write a C++ program to implement the concept of virtual base class.

ALGORITHM:
1. Start the program
2. Include suitable header files
3. Create a base class student and sports
4. In the base class student define the function void get number and put number
5. In the base class sports define the function void get score and void put score
6. Derive a class test form base student and define the function get mark and put mark
7. Derive a class result from test and sports class and define function void display
8. Get the value for get number, get marks and get score function through main function
9. Call the display function in class result
10. Stop the program

PROGRAM:
#include<iostream.h>
#include<conio.h>
class student
{
protected:
int roll_number;
public:
void get_number(int a)
{
roll_number=a;
}
void put_number()
{
cout<<"ROLL NO:"<<roll_number<<"\n";
}
};
class test:public virtual student
{
protected:
int part1,part2;
public:
void get_marks(int x, int y)
{
part1=x;
part2=y;
}
void put_marks()
{
cout<<"MARKS:"<<"\n"<<"Part1="<<part1<<"\n"<<"Part2="<<part2<<"\n";
}
};
class sports: public virtual student
{
protected:
float score;
public:
void get_score(int s)
{
score=s;
}

Prepared by T.Rajasekaran, AP/CSE Page 22


void put_score()
{
cout<<"Sports:"<<score<<"\n\n";
}
};

class result: public test, public sports


{
int total;
public:
void display()
{
total=part1+part2+score;
put_number();
put_marks();
put_score();
cout<<"TOTAL SCORE:"<<total<<"\n";
}
};

void main()
{
clrscr();
result student;
student.get_number(1234);
student.get_marks(80,70);
student.get_score(20);
student.display();
getch();
}

OUTPUT:

ROLL NO: 1234


MARKS:
Part1=80
Part2=70
Sports:20
Total score: 170

RESULT:

Thus the C++ program for virtual base class was created, executed and output was verified
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 23


EX.NO: 5.A. FILE HANDLING-SEQUENTIAL ACCESS

AIM:
To write a C++ program to implement a file handling concept using sequential access.

ALGORITHM:

1. Start
2. Get the input string
3. Write the input string character by character into a file called “sample” using put() function
4. Read the input string character by character from the file called “sample” using get() function
5. Display the result

SOURCE CODE:

#include<iostream.h>
#include<fstream.h>
#include<string.h>
#include<conio.h>

void main()
{
clrscr();
char str[100],ch;
int i,len;
cout<<"Enter a string:";
cin>>str;
len=strlen(str); // to find the length of the string
fstream file;
file.open("D:\\sample.txt",ios::in|ios::out); // to create a file
for(i=0;i<len;i++)
{
file.put(str[i]); // to write string to a file
}
file.seekg(0);
while(file)
{
file.get(ch); //to read string from the file
cout<<ch;
}
getch();
}

RESULT:

Thus the C++ program for file handling- sequential access concept was created, executed and
output was verified successfully

Prepared by T.Rajasekaran, AP/CSE Page 24


EX.NO: 5.B. FILE HANDLING-RANDOM ACCESS

AIM:
To implement file handling concept using random access

ALGORITHM:
1. Start
2. Get the input file called random.txt and check the file’s presence
3. Seek the input file to a particular(random) location and get the specified output
4. Display the result

SOURCE CODE:
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
clrscr();
fstream fp;
char buf[100];
int pos;
fp.open("D:\\random.txt", ios :: out | ios :: ate); // open a file in write mode with 'ate' flag
cout << "\nWriting to a file ... " << endl;
fp << "This is a line" << endl; // write a line to a file
fp << "This is a another line" << endl; // write another line
pos = fp.tellp();
cout << "Current position of put pointer : " << pos << endl;
fp.seekp(-10, ios :: cur); // move the pointer 10 bytes backward from current position
fp << endl << "Writing at a random location ";
fp.seekp(7, ios :: beg); // move the pointer 7 bytes forward from beginning of the file
fp << " Hello World ";
fp.close(); // file write complete
cout << "Writing Complete ... " << endl;
getch();
fp.open("D:\\random.txt", ios :: in | ios :: ate); // open a file in read mode with 'ate' flag
cout << "\nReading from the file ... " << endl;
fp.seekg(0); // move the get pointer to the beginning of the file
while (!fp.eof()) // read all contents till the end of file
{
fp.getline(buf, 100);
cout << buf << endl;
}
pos = fp.tellg();
cout << "\n Current Position of get pointer : " << pos << endl;
getch();
}
OUTPUT:
Writing to a file
Current position of put pointer : 40 random.txt
Writing Complete This is Hello World is a anot
Writing at a random location
Reading from the file
This is Hello World is a anot
Writing at a random location
Current position of gut pointer : 62

RESULT:
Thus the C++ program for file handling- random access concept was created, executed and
output was verified successfully.

Prepared by T.Rajasekaran, AP/CSE Page 25


Ex.No: 6(A). SIMPLE JAVA PROGRAM

AIM:
To write a java program to find area of Rectangle by using an instance of a class.

ALGORITHM:
1. Declare the class Rectangle.
2. Declare data members height & width and a method area() to calculate area.
3. Declare another class example.
4. Create an object to Rectangle class and access the area() metod.
5. Print the output.
PROGRAM:
import java.util.Scanner;
class Rectangle // class which contains attributes and methods
{
int height,width;
void area() // method to calculate area
{
int a = height*width;
System.out.println("The Area of Rectangle is :" +a);
}
}
public class example // class which contains main()
{
public static void main(String args[])
{
Rectangle r = new Rectangle(); //creating object for Rectangle class
Scanner s = new Scanner(System.in); // Scanner class to receive input from keyboard.
System.out.println("Enter height of the Rectangle:");
r.height = s.nextInt(); // nextInt() method to get integer type value from keyboard.
System.out.println("Enter width of the Rectangle:");
r.width = s.nextInt(); // nextInt() method to get integer type value from keyboard.
r.area(); // invoking area() method of Rectangle class
}
}

OUTPUT:
C:\> cd vec

C:\vec> set PATH=“C:\Program Files\Java\jdk1.7.0_75\bin”;


C:\vec> javac example.java
C:\vec> java example
Enter height of the Rectangle:
10
Enter width of the Rectangle:
5
The Area of Rectangle is: 50

RESULT:
Thus the java program to find the area of rectangle was created, executed and output was
verified successfully.
Prepared by T.Rajasekaran, AP/CSE Page 26
Ex.No: 6(B). HANDLING STRINGS IN JAVA

AIM:
To write a java program to perform various operations using string function.
ALGORITHM:
1. Start
2. Declare the class called stringUse
3. Initialize two strings and using the two strings manipulate string operation
4. Perform the operation like concat(),length(),chatAt(),startsWith(),endsWith(),etc
5. Display the result

PROGRAM:
import java.util.*;
public class stringUse
{
public static void main (String args [])
{
Scanner scanner = new Scanner (System. in); // Scanner class to receive input from keyboard.
System.out.println ("Enter the First Name :");
String fname=scanner.nextLine(); // nextLine () method to get integer type value from keyboard.
System.out.println ("Enter the Last Name :");
String lname=scanner.nextLine(); // nextLine () method to get integer type value from keyboard.
String name= fname+lname; // concatenates two strings
int len = name.length(); // Returns the length of string
System.out.println ("First Name: " + fname);
System.out.println ("Last Name: " + lname);
System.out.println ("Length of Name: " + len);
String cname =name; // copying string to another string
System.out.println ("Copied Name:" + cname);
System.out.println ("Name in Lowercase: "+ name.toLowerCase()); // Converts all the char(s) to lower case
System.out.println ("Name in Uppercase: " + name.toUpperCase()); // Converts all the char(s) to upper case
char c = name. charAt(0); // Returns the character at the specified index
System.out.println ("Character at position 0:" + c);
boolean b=fname.startsWith("v"); // Tests the string starts with the specified character.
System.out.println ("Checks First name starts with character v :"+b);
if(cname == name) // checks ‘name’ and ‘cname’ shares the same location
{
System.out.println ("Same memory location = true");
}
else
System.out.println ("Same memory location = false");
String substr= cname.substring (0, 3); // It returns new String containing the substring of the given
string from specified startIndex to endIndex(exclusive).
System.out.println ("Substring: " + substr);
boolean b1=name.equals(cname); // Compares string by considering case
System.out.println ("Name equality with case checking:" + b1);
boolean b2=name.equalsIgnoreCase(cname); // Compares string by ignoring case
System.out.println ("Name equality without case checking:" + b2);
}
}

Prepared by T.Rajasekaran, AP/CSE Page 27


OUTPUT:

C:\> cd vec

C:\vec> javac stringUse.java

C:\vec> java stringUse

Enter the First Name: sam


Enter the Last Name: daniel
First Name: sam
Last Name: daniel
Length of Name: 9
Copied Name: samdaniel
Name in Lowercase: samdaniel
Name in Uppercase: SAMDANIEL
Character at position 0: s
Checks First name starts with character v: false
Same memory location = true
Substring: sam
Name equality with case checking: true
Name equality without case checking: true

RESULT:

Thus a java program for handling strings was created, executed and output was verified
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 28


Ex. NO: 7(A). SIMPLE PACKAGE CREATION

AIM:
To write a java program to create a package.
ALGORITHM:
1. Start
2. Declare the class called Balance and two methods read(), show() in a file
3. Declare the class called AccountBalance and create an object in another file
4. Import the package and invoke the method show() using the object of class Balance.
5. Display the result

PROGRAM:
Instructions:
Balance.java 1. Create a folder named mypackage
package mypackage; 2. Go to the folder mypackage
public class Balance 3. Create a java program - Balance.java
{
String name; 4. Create a java program - AccountBalance.java and save
int bal; it under the vec folder.
public void read(String n, int b) 5. Open the command prompt
{ StartÆRunÆcmd
name = n;
bal = b; 6. C:\vec> set PATH=”C:\jdk1.7\bin”;
} 7. C:\vec> set CLASSPATH=”C:\jdk1.7\lib”;
public void show() 8. C:\vec\javac mypackage\Balance.java
{ (Balance.class file will be created in mypackage folder)
if(bal>0)
{ 9. C:\vec>javac AccountBalance.java
System.out.println(name +":$"+bal); (AccountBalance.class file will be created)
} 10. C:\vec>java AccountBalance
} 11. Now the output will be displayed.
}
AccountBalance.java
import mypackage.Balance;
class AccountBalance
{
public static void main(String arg[]) throws NoClassDefFoundError
{
Balance obj = new Balance(); // creating object of class A
obj.read("Sachin", 10000); // values are instr
obj.show(); //invoking show() method in the balance class
}
}

OUTPUT:
C:\vec>javac mypackage\Balance.java
C:\vec>javac AccountBalance.java
C:\vec>java AccountBalance
Sachin : $10000

RESULT:
Thus a java program to create a package was created, executed and output was verified
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 29


Ex. NO: 7(B). SIMPLE PACKAGE CREATION

AIM:
To write a java program to find the account balance by array of objects using package.
ALGORITHM:
1. Declare class Balance and pass parameterized constructor.
2. Initialize name and balance as n and b.
3. Use member function to check balance greater than 0 and print the result.
4. Declare another class account import package.
5. Access show() function and print result.
PROGRAM:
Balance.java
package pack;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
name=n;
bal=b;
}
public void show()
{
if(bal>0)
{
System.out.println(name +":$"+bal);
}
}
}
AccountBalance.java
import pack.Balance;
class AccountBalance
{
public static void main(String arg[])
{
Balance current[]=new Balance[3];
current[0]=new Balance("Steve Jobs",123.23);
current[1]=new Balance("Will Smith",157.10);
current[2]=new Balance("Tom Jackson",-12.55);
for(int i=0;i<3;i++)
{
current[i].show();
}
}
}

OUTPUT:
C:\vec>javac pac\Balance.java
C:\vec>javac AccountBalance.java
C:\vec>java AccountBalance
Steve Jobs : $123.33
Will Smith : $157.10

RESULT: Thus java program to find the balance amount using packages was created, executed and
output was verified successfully.

Prepared by T.Rajasekaran, AP/CSE Page 30


Ex.No: 8(A) INTERFACES - DEVELOPING USER DEFINED INTERFACES

AIM:
To write a java program to develop user defined interfaces.

ALGORITHM:
1. Start the program
2. Declare the interface called Area and declare the function called compute in it.
3. Define the class called Rectangle and implement the interface Area.
4. Define the class called Circle and implement the interface Area.
5. Display the result.

PROGRAM:

import java.io.*;
interface Area
{
final static float pi=3.14F;
float compute(float x, float y);
}

class Rectangle implements Area


{
public float compute(float x, float y)
{
return(x*y);
}
}

class Circle implements Area


{
public float compute(float x, float y)
{
return(pi*x*x);
}
}

class MainClass
{
public static void main(String args[])
{
Rectangle rect=new Rectangle(); // Object to class ‘Rectangle’
Circle cir=new Circle(); // Object to class ‘Circle’
System.out.println("Area of Rectangle ="+ rect.compute(10,20));
System.out.println("Area of Circle ="+ cir.compute(10,0));
}
}

OUTPUT:
C:\vec>javac MainClass.java
C:\vec>java MainClass
Area of Rectangle = 200.0
Area of Circle=314.0
RESULT:
Thus java program to implement user defined interface was created, executed and output was
verified successfully.

Prepared by T.Rajasekaran, AP/CSE Page 31


Ex.No: 8(B) INTERFACES – USING PRE-DEFINED INTERFACES
AIM:
To write a java program using pre defined interfaces
ALGORITHM:
1. Create a class called ‘Person’ which implements predefined interface ‘Comparable’
2. Declare data members name and age in a constructor.
3. Define the member function getName() and getAge()
4. compareTo() is the method of ‘Comparable’ interface
5. Display the result.

PROGRAM:
public class Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
public int compareTo(Person per)
{
if(this.age == per.age)
return 0;
else
return this.age > per.age ? 1 : -1;
}
public static void main(String args[])
{
Person e1 = new Person("Adam", 50);
Person e2 = new Person("Steve", 60);
int val = e1.compareTo(e2);
switch(val)
{
case -1:
{
System.out.println("The " + e2.getName() + " is older!");
break;
}
case 1:
{
System.out.println("The " + e1.getName() + " is older!");
break;
}
default:
System.out.println("The two persons are of the same age!");
}
}
}

Prepared by T.Rajasekaran, AP/CSE Page 32


OUTPUT:

C:\vec>javac Person.java
C:\vec>java Person
The Steve is older!

RESULT:
Thus a java program for pre defined interface was created, executed and output was verified
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 33


Ex.No: 9(A) CREATION OF THREADING IN JAVA

AIM:
To implement threading and exception handling using java program.

ALGORITHM:
1. Declare class Th1 that extends from Thread
2. Declare try, catch with data.
3. Declare another two classes Th2 & Th3 and define method run().
4. Declare main class ThreadDemo and create object t1, t2 and t3 for each class and Access it.
5. Display the result.

PROGRAM:

import java.io.*;
class Th1 extends Thread
{
public void run()
{
try
{
Thread.sleep(1000);
System.out.println("Name: Alex");
System.out.println("Age: 20");
}
catch(InterruptedException i) {}
}
}

class Th2 extends Thread


{
public void run()
{
try
{
Thread.sleep(2000);
System.out.println("Class: B.E-CSE");
System.out.println("College: VEC");
}
catch(InterruptedException i) {}
}
}

class Th3 extends Thread


{
public void run()
{
try
{
Thread.sleep(3000);
System.out.println("City: Chennai");
System.out.println("State: Tamilnadu");
}
catch(InterruptedException i) {}
}
}

Prepared by T.Rajasekaran, AP/CSE Page 34


class ThreadDemo
{
public static void main(String args[ ])
{
Th1 t1=new Th1();
t1.start( );
Th2 t2=new Th2();
t2.start( );
Th3 t3=new Th3( );
t3.start( );
}
}

OUTPUT:

C:\javaprg>javac ThreadDemo.java

C:\javaprg>java ThreadDemo

Name : Alex
Age : 20
Class : B.E.-CSE
College : VEC
City : Chennai
State : Tamilnadu

RESULT:

Thus a java program for threading was created, executed and output was verified successfully.

Prepared by T.Rajasekaran, AP/CSE Page 35


Ex.No: 9(B) MULTITHREADING IN JAVA

AIM:
To write a java program on multithreading concept.

ALGORITHM:
1. Start the program
2. Create a main thread called ThreadDemo and starts its execution
3. Invoke the child thread class called newThread
3. newThread() invokes the superclass constructor and starts the child thread execution.
4. Main thread and child thread runs parallelly.
5. Display the result.

PROGRAM:

import java.io.*;
class Newthread extends Thread
{
Newthread()
{
super("DemoThread");
System.out.println("Child Thread:" +this);
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 Thread Interrupted");
}
System.out.println("Exiting Child Thread");
}
}

Prepared by T.Rajasekaran, AP/CSE Page 36


class MultiThreadDemo
{
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("Exiting Main Thread");
}
}

OUTPUT:
C:\javaprg>javac MultiThreadDemo.java

C:\javaprg>java MultiThreadDemo

Child Thread:Thread[DemoThread,5,main]
Main Thread:5
Main Thread:4
Main Thread:3
Main Thread:2
Child Thread:5
Main Thread:1
Child Thread:4
Exiting Main Thread
Child Thread:3
Child Thread:2
Child Thread:1
Exiting Child Thread

RESULT:
Thus a java program for multi threading was created, executed and output was verified
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 37


Ex.No: 10(A) HANDLING PREDEFINED EXCEPTION

AIM:
To implement the pre defined exception concept in java

ALGORITHM:
1. Start the program
2. Create the called error.
3. Declare and Initialize the data members.
4. Use the try and catch block to handle the exception
5. If the exception exists, corresponding catch block will be executed or else control goes out of
the catch block.
6. Display the result.
PROGRAM:
class Exception
{
public static void main(String args[])
{
int a=10, b=5, c=5, result;
try
{
result =a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("Exception occurs: Division by Zero");
}
result =a/(b+c);
System.out.println("Result =" + result);
}
}

OUTPUT:

C:\javaprg> javac Exception.java


C:\javaprg> java Exception

Exception occurs: Division by Zero


Result = 1

RESULT:
 
Thus a java program for pre defined exception was created, executed and output was verified
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 38


Ex.No: 10(B) HANDLING USERDEFINED EXCEPTION

AIM:
To implement the user defined exception concept in java

ALGORITHM:
1. Create a user defined exception class called MyException
2. Throw an exception of user defined type as an argument in main()
3. Exception is handled using try, catch block
4. Display the user defined exception

PROGRAM:

import java.lang.Exception;

class MyException extends Exception


{
int a;
MyException(int b)
{
a=b;
}
public String toString()
{
return ("Exception Number = " +a) ;
}
}

class JavaException
{
public static void main(String args[])
{
try
{
throw new MyException(2); // throw is used to create a new exception and throw it.
}
catch(MyException e)
{
System.out.println(e) ;
}
}
}

OUTPUT
C:\javaprg >javac JavaException.java
C:\javaprg >java JavaException

Exception Number = 2

RESULT:

Thus a java program for user defined exception was created, executed and output was verified
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 39


ADDITIONAL EXERCISES IN JAVA
Ex.No: 11(A) DRAW SMILEY USING JAVA APPLET

Aim: To create a java applet program for drawing smiley face

Algorithm:
Step 1: Create a java program Smiley.java
Step 2: import awt an applet package and create a class that extends Applet
Step 3: Using various methods in awt and applet class draw a face.
Step 4: Create a html file called Smiley.html and write the applet code.
Step 5: Stop

Program:

// Smiley.java
import java.awt.*;
import java.applet.*;
public class Smiley extends Applet
{
public void paint(Graphics g)
{
Font f = new Font("Helvetica", Font.BOLD, 20);
g.setFont(f);
g.drawString("Keep Smiling!!!", 50, 30);
g.drawOval(60, 60, 200, 200);
g.fillOval(90, 120, 50, 20);
g.fillOval(190, 120, 50, 20);
g.drawLine(165, 125, 165, 175);
g.drawArc(110, 130, 95, 95, 0, -180);
}
}

//Smiley.html
</html>
<body>
<applet code="Smiley.class" width=300 height=300></applet>
</body>
</html>

Output:
C:\vec>javac Smiley.java
C:\vec>appletviewer Smiley.html

RESULT:

Thus a java applet program for drawing smiley face was created, executed and output was
verified successfully.

Prepared by T.Rajasekaran, AP/CSE Page 40


Ex.No: 11(B) ADDING TWO NUMBERS USING JAVA APPLET

Aim: To create a java applet program for adding two numbers by getting input from the user

Algorithm:
Step 1: Create a java program Sum.java
Step 2: import awt an applet package and create a Sum that extends Applet
Step 3: Using various methods in awt and applet class draw a face.
Step 4: Create a html file called Sum.html and write the applet code.
Step 5: Stop

Program:

// Sum.java
import java.awt.*;
import java.applet.*;

public class Sum extends Applet


{
TextField T1,T2;
public void init()
{
T1 = new TextField(10);
T2 = new TextField(10);
add(T1);
add(T2);
T1.setText("0");
T2.setText("0");
}
public void paint(Graphics g)
{
int a, b, result;
String str;

g.drawString("Enter Number in TextField to find addition of 2 Numbers ",10,50);


g.setColor(Color.red);
str=T1.getText();
a=Integer.parseInt(str);
str=T2.getText();
b=Integer.parseInt(str);
result=a+b;
g.drawString("THE SUM = " + result,10,80);
showStatus("Addition of 2 Numbers");
}
public boolean action(Event e, Object o)
{
repaint();
return true;
}
}

//Sum.html
<html>
<body>
<applet code="Sum.class" width=350 height=150></applet>
</body>
</html>

Prepared by T.Rajasekaran, AP/CSE Page 41


Output:

C:\vec>javac Sum.java
C:\vec>appletviewer Sum.html

RESULT:

Thus a java applet program for adding two numbers was created, executed and output was
verified successfully.

Prepared by T.Rajasekaran, AP/CSE Page 42


Ex.No: 11(C) DRAW ARCS USING JAVA APPLET

Aim: To create a java applet program for drawing Arcs.

Algorithm:
Step 1: Create a java program Arcs.java
Step 2: import awt an applet package and create a class that extends Applet
Step 3: Using various methods in awt and applet class draw a face.
Step 4: Create a html file called Arcs.html and write the applet code.
Step 5: Stop

Program:

// Arcs.java
import java.awt.*;
import java.applet.*;
public class Arcs extends Applet
{
public void init()
{
setBackground(Color.black);
setForeground(Color.green);
}
public void paint(Graphics g)
{
g.drawArc(10, 40, 70, 70, 0, 75);
g.fillArc(100, 40, 70, 70, 0, 75) ;
g.drawArc(10, 100, 70, 80, 0, 175);
g.fillArc(100, 100, 70, 90, 0, 270);
g.drawArc(200, 80, 80, 80, 0, 180);
}
}

//Arcs.html
<html>
<body>
<applet code="Arcs.class" width=300 height=250></applet>
</body>
</html>

Output:
C:\vec>javac Arcs.java
C:\vec>appletviewer Arcs.html

RESULT:
Thus a java applet program for drawing arcs was created, executed and output was verified
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 43


Ex.No: 11(D) DRAW BUTTONS USING JAVA APPLET

Aim: To create a java applet program for drawing Buttons.

Algorithm:
Step 1: Create a java program ButtonDemo.java
Step 2: import awt an applet package and create a class that extends Applet
Step 3: Using various methods in awt and applet class draw a face.
Step 4: Create a html file called ButtonsDemo.html and write the applet code.
Step 5: Stop

Program:

// ButtonDemo.java
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo extends Frame implements ActionListener
{
Button redBut, greenBut, blueBut, closeBut;
public ButtonDemo()
{
setLayout(new FlowLayout());
redBut = new Button("RED");
greenBut = new Button("GREEN");
blueBut = new Button("BLUE");
closeBut = new Button("CLOSE");
redBut.addActionListener(this);
greenBut.addActionListener(this);
blueBut.addActionListener(this);
closeBut.addActionListener(this);
closeBut.setForeground(Color.red);
add(redBut);
add(greenBut);
add(blueBut);
add(closeBut);
setTitle("Buttons in Action");
setSize(300, 300);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand();

if(str.equals("RED"))
setBackground(Color.red);
else if(str.equals("GREEN"))
setBackground(Color.green);
else if(str.equals("BLUE"))
setBackground(Color.blue);
else if(str.equals("CLOSE"))
System.exit(0);
}
public static void main(String args[])
{
new ButtonDemo();
}
}

Prepared by T.Rajasekaran, AP/CSE Page 44


// ButtonDemo.html
<html>
<body>
<applet code=" ButtonDemo.class" width=300 height=250></applet>
</body>
</html>

Output:

C:\vec>java ButtonDemo.java
C:\vec>appletviewer ButtonDemo.html

RESULT:
Thus a java applet program for creating buttons was created, executed and output was verified
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 45


Ex.No: 11(E) CHAT APPLICATION USING JAVA APPLET

Aim: To create a java applet program for chatting.

Algorithm:

Step 1: Create a java program called Server.java


Step 2: import java.io and java.net package and create a class Server
Step 3: Using various methods in java.io and java.net package initiate chat , send and receive text from
Client program.
Step 4: Create another java program called Client.java
Step 5: import java.io and java.net package and create a class Client
Step 6: Using various methods in java.io and java.net package initiate chat, send and receive text from
Server program.
Step 7: Stop

Program:

// Server.java
import java.io.*;
import java.net.*;
public class Server
{
public static void main(String[] args) throws IOException
{
ServerSocket sersock = new ServerSocket(3000);
System.out.println("Server ready for chatting...");
Socket sock = sersock.accept( );
// reading from keyboard
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

String receiveMessage, sendMessage;


while(true)
{
if((receiveMessage = receiveRead.readLine()) != null)
{
System.out.println(receiveMessage);
}
sendMessage = keyRead.readLine();
pwrite.println(sendMessage);
pwrite.flush();
}
}
}

Prepared by T.Rajasekaran, AP/CSE Page 46


// Client.java
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String[] args) throws IOException
{
Socket sock = new Socket("127.0.0.1", 3000);
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);

// receiving from server ( receiveRead object)


InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Client ready for hatting...");
System.out.println("To initiate Chat, type anything and press Enter key");
String receiveMessage, sendMessage;
while(true)
{
sendMessage = keyRead.readLine(); // keyboard reading
pwrite.println(sendMessage); // sending to server
pwrite.flush(); // flush the data
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
}
}
}
}
Output:
C:\vec>javac Server.java
C:\vec>java Server
C:\vec>javac Client.java
C:\vec>java Client

RESULT:
Thus a java applet program for chat application was created, executed and output was verified
successfully.

Prepared by T.Rajasekaran, AP/CSE Page 47

You might also like