0% found this document useful (0 votes)
8 views64 pages

Object-Oriented Programming Lab Manual

The document is a laboratory manual for the Object Oriented Programming Laboratory course at Mangayarkarasi College of Engineering. It outlines the syllabus, list of experiments, and course outcomes, focusing on Java programming concepts such as data structures, algorithms, multithreading, and GUI development. The manual includes detailed instructions for various programming tasks and their expected outcomes.

Uploaded by

mvs122726
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views64 pages

Object-Oriented Programming Lab Manual

The document is a laboratory manual for the Object Oriented Programming Laboratory course at Mangayarkarasi College of Engineering. It outlines the syllabus, list of experiments, and course outcomes, focusing on Java programming concepts such as data structures, algorithms, multithreading, and GUI development. The manual includes detailed instructions for various programming tasks and their expected outcomes.

Uploaded by

mvs122726
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MANGAYARKARASI COLLEGE OF ENGINEERING

(Approved by AICTE, New Delhi & Affiliated to Anna University,


Chennai)
MANGAYARKARASI NAGAR, PARAVAI, MADURAI – 625 402
Website: [Link] E-Mail: : [Link]@[Link]

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LABORATORY MANUAL

[Link] : CS3381

[Link] : OBJECT ORIENTED PROGRAMMING LABORATORY

Regulation 2021

Prepared By, Approved By,

HoD-CSE

1
SYLLABUS

LIST OF EXPERIMENTS:

1. Solve problems by using sequential search, binary search, and quadratic sorting
algorithms (Selection, insertion)
2. Develop stack and queue data structures using classes and objects.
3. Develop a java application with an Employee class with Emp_name, Emp_id, Address,
Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant Professor,
Associate Professor and Professor from employee class. Add Basic Pay (BP) as the
member of all the inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12%
of BP as PF, 0.1% of BP for staff club funds. Generate pay slips for the employees with
their gross and net salary.
4. Write a Java Program to create an abstract class named Shape that contains two integers
and an empty method named printArea(). Provide three classes named Rectangle,
Triangle and Circle such that each one of the classes extends the class Shape. Each one
of the classes contains only the method printArea( ) that prints the area of the given
shape.
5. Solve the above problem using an interface.
6. Implement exception handling and creation of user defined exceptions.
7. Write a java program that implements a multi-threaded application that has three
threads. First thread generates a random integer every 1 second and if the value is even,
the second thread computes the square of the number and prints. If the value is odd, the
third thread will print the value of the cube of the number.
8. Write a program to perform file operations.
9. Develop applications to demonstrate the features of generics classes.
10. Develop applications using JavaFX controls, layouts and menus.
11. Develop a mini project for any application using Java concepts.

COURSE OUTCOMES

On completion of this course, the students will be able to:

CO1: Design and develop java programs using object oriented programming concepts.
CO2: Develop simple applications using object oriented concepts such as package, exceptions.
CO3: Implement multithreading, and generics concepts.
CO4: Create GUIs and event driven programming applications for real world problems.
CO5: Implement and deploy web applications using Java.

2
LIST OF EXPERIMENTS

[Link] Experiment 1 [Link] Marks

1 Solve problems by using sequential search, binary search, and


quadratic sorting algorithms (Selection, insertion)

2 Develop stack and queue data structures using classes and


objects.
Develop a java application with an Employee class with
Emp_name, Emp_id, Address, Mail_id, Mobile_no as
members. Inherit the classes, Programmer, Assistant Professor,
3 Associate Professor and Professor from employee class. Add
Basic Pay (BP) as the member of all the inherited classes with
97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1%
of BP for staff club funds. Generate pay slips for the employees
with their gross and net salary.
Write a Java Program to create an abstract class named Shape
that contains two integers and an empty method named
4 printArea(). Provide three classes named Rectangle, Triangle
and Circle such that each one of the classes extends the class
Shape. Each one of the classes contains only the method
printArea( ) that prints the area of the given shape.
5 Solve the above problem using an interface.

6 Implement exception handling and creation of user defined


exceptions.
Write a java program that implements a multi-threaded
application that has three threads. First thread generates a
7 random integer every 1 second and if the value is even, the
second thread computes the square of the number and prints. If
the value is odd, the third thread will print the value of the cube
of the number.
8 Write a program to perform file operations.

9 Develop applications to demonstrate the features of generics


classes.

10 Develop applications using JavaFX controls, layouts and


menus.

11 Develop a mini project for any application using Java


concepts.

3
EXPERIMENTS TO COURSE OUTCOMES MAPPING

[Link] Experiments/ CO CO1 CO2 CO3 CO4 CO5

Solve problems by using sequential


search, binary search, and quadratic
1
sorting algorithms (Selection, ✓
insertion)

Develop stack and queue data


2
structures using classes and objects. ✓
Develop a java application with an
Employee class with Emp_name,
Emp_id, Address, Mail_id,
Mobile_no as members. Inherit the
classes, Programmer, Assistant
Professor, Associate Professor and
3 Professor from employee class. Add
Basic Pay (BP) as the member of all

the inherited classes with 97% of BP
as DA, 10 % of BP as HRA, 12% of
BP as PF, 0.1% of BP for staff club
funds. Generate pay slips for the
employees with their gross and net
salary.
Write a Java Program to create an
abstract class named Shape that
contains two integers and an empty
method named printArea(). Provide
three classes named Rectangle,
4 Triangle and Circle such that each ✓
one of the classes extends the class
Shape. Each one of the classes
contains only the method
printArea( ) that prints the area of
the given shape.

Solve the above problem using an


5
interface. ✓

6
Implement exception handling and ✓
creation of user defined exceptions.

4
Write a java program that
implements a multi-threaded
application that has three threads. ✓
First thread generates a random
integer every 1 second and if the
7
value is even, the second thread
computes the square of the number
and prints. If the value is odd, the
third thread will print the value of
the cube of the number.

8
Write a program to perform file ✓
operations.

Develop applications to
9 demonstrate the features of ✓
generics classes.

10
Develop applications using JavaFX ✓
controls, layouts and menus.

Develop a mini project for any ✓


11
application using Java concepts.

5
SOLVE PROBLEMS BY USING SEQUENTIAL SEARCH, BINARY
EX NO :1 SEARCH, AND QUADRATIC SORTING ALGORITHMS
(SELECTION, INSERTION)

Aim:
To Solve problems by using sequential search, binary search, and quadratic sorting
algorithms (Selection, insertion).
1. Sequential Search:
Algorithm:
1. Let the element to be search be x.
2. Start from the leftmost element of arr[] and one by one compare x with each
element of arr[].
3. If x matches with an element then return that index.
4. If x doesn’t match with any of elements then return -1.
Program:
class GFG {
public static int search(int arr[], int x)
{
int n = [Link];
for (int i = 0; i < n; i++) {
if (arr[i] == x)
return i;
}
return -1;
}
public static void main(String args[])
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int result = search(arr, x);
if (result == -1)
[Link]("Element is not present in array");
else
[Link]("Element is present" + " at index " + result);

6
}
}
Output:

Element is present at index 3


2. Binary Search:
Algorithm:
1. Compare x with the middle element.
2. If x matches with the middle element, we return the mid index.
3. Else if x is greater than the mid element, then x can only lie in the right half sub
array after the mid element. So we start with same process for the right half.
4. Else (x is smaller) we start with same process for the left half.
Program:
class BinarySearch
{
int binarySearch(int arr[], int x)
{
int l = 0, r = [Link] - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x)
return m;
if (arr[m] < x)
l = m + 1;
else
r = m - 1;
}
return -1;
}
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int arr[] = { 2, 3, 4, 10, 40 };
int n = [Link];
int x = 10;
7
int result = [Link](arr, x);
if (result == -1)
[Link]("Element not present");
else
[Link]("Element found at index " + result);
}
}
Output:

Element is present at index 3

3. Insertion Sort:
Algorithm:
1. Iterate from arr[1] to arr[N] over the array.
2. Compare the current element (key) to its predecessor.
3. If the key element is smaller than its predecessor, compare it to the elements before.
4. Move the greater elements one position up to make space for the swapped element.
Program:
class InsertionSort {
void sort(int arr[])
{
int n = [Link];
for (int i = 1; i < n; ++i)
{
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}

8
}

9
static void printArray(int arr[])
{
int n = [Link];
for (int i = 0; i < n; ++i)
[Link](arr[i] + " ");
[Link]();
}
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6 };
InsertionSort ob = new InsertionSort();
[Link](arr);
printArray(arr);
}
}
Output:

5 6 11 12 13
4. Selection Sort:
Algorithm:
1. Initialize minimum value(min_idx) to location 0
2. Traverse the array to find the minimum element in the array
3. While traversing if any element smaller than min_idx is found then swap both the
values.
4. Then, increment min_idx to point to next element
5. Repeat until array is sorted
Program:
class SelectionSort
{
void sort(int arr[])
{
int n = [Link];
for (int i = 0; i < n-1; i++)

10
{

11
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void printArray(int arr[])
{
int n = [Link];
for (int i=0; i<n; ++i)
[Link](arr[i]+" ");
[Link]();
}
public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int arr[] = {64,25,12,22,11};
[Link](arr);
[Link]("Sorted array");
[Link](arr);
}
}
Output:

Sorted array:
11 12 22 25 64
Result:

Thus the problems by using sequential search, binary search, and quadratic sorting
algorithms (Selection, insertion) have been successfully executed.
Viva Questions:

1. What is searching?
12
2. What is sorting?
3. What is the logic for linear search?
4. What are the types of sorting?
5. List out the types of searching.
6. What is time complexity?
Augmented Experiment:
1. Binary search with recursion
2. Bubble sort
3. Quick sort

13
EX NO :2 DEVELOP STACK AND QUEUE DATA STRUCTURES USING
CLASSES AND OBJECTS.

Aim:
To develop stack and queue data structures using classes and objects.
1. Stack:
Algorithm:
Algorithm Push ():
begin
if stack is full
return
end if
else
increment top
stack[top] assign value
end else
end
Algorithm Pop ():
begin
if stack is empty
return
endif
else
store value of stack[top]
decrement top
return value
end else
end

14
Program:
package ex2;
class stack
{
public int maxSize;
public int stackArray[];
private int top;
public stack(int a)
{
maxSize=a;
stackArray=new int[a];
top=-1;
}
public void push(int item)
{
if(top==maxSize-1)
{
[Link]("stack overflow! cannot insert");
}
else
{
top++;
stackArray[top]=item;
}
}
public void pop()
{
if(top==-1)
{
[Link]("stack is empty");
}
else
{
[Link]("element popped:" +stackArray[top]);
top--;
}
}
public int peek()
{
return stackArray[top];
}
public static void main(String args[])
{
stack stack=new stack(4);
[Link](10);
[Link]("elemented inserted:"+[Link]());
[Link](20);
[Link]("el inserted:"+[Link]());
[Link](30);
[Link]("elemented inserted:"+[Link]());
[Link](40);
15
[Link]("elemented inserted:"+[Link]());
[Link]();
}
}
Output:

10 pushed into stack


20 pushed into stack
30 pushed into stack
The Popped value 30
The Popped value 20
2. Queue:
Algorithm:
Algorithm insertion ():
begin
if rear== MAX_SIZE
Queue is Full
end if
else
queue[rear] assign value
rear++
end else
end
Algorithm deletion ():
begin
if front==rear
Queue is empty
endif
else

16
removed value of queue[front]
decrement front
end else
end

Program:

import [Link].*;
public class Queue
{
int arr[], front, rear, cap, n1;
// Queue constructor
Queue(int n)
{
arr = new int[n];
cap = n;
front = 0;
rear = -1;
n = 0;
}
// dequeue function for removing the front element
public void dequeue()
{
// check for queue underflow
if (isEmpty())
{
[Link]("No items in the queue,cannot delete");
[Link](1);
}

[Link]("Deleting " + arr[front]);

Front = (front + 1) % cap;


n

// enqueue function for adding an item to the rear


public void enqueue(int val)
{
// check for queue overflow
if (isFull())
{
[Link]("OverFlow!!Cannot add more values");
[Link](1);
}

[Link]("Adding " + val);

rear = (rear + 1) % cap;


arr[rear] = val;
17
n1++;
}

// peek function to return front element of the queue


public int peek()
{
if (isEmpty())
{
[Link]("Queue empty!!Cannot delete");
[Link](1);
}
return arr[front];
}

// returns the size of the queue


public int size()
{
return n1;
}
// to check if the queue is empty or not
public Boolean isEmpty()
{
return (size() == 0);
}

// to check if the queue is full or not


public Boolean isFull()
{
return (size() == cap);
}
// Queue implementation in java
public static void main (String[] args)
{
// create a queue of capacity 5
Queue q = new Queue(5);
[Link](10);
[Link](20);
[Link](30);
[Link]("Front element is: " + [Link]());
[Link]();
[Link]("Front element is: " + [Link]());
[Link]("Queue size is " + [Link]());
[Link]();
[Link]();
if ([Link]())
[Link]("Queue Is Empty");
else
[Link]("Queue Is Not Empty");
}
1--;
}
18
}

19
Output:
Case : 1
10 insert to queue
20 insert to queue
30 insert to queue
40 insert to queue
Case: 2
10 delete from queue
Result:

Thus the problems for developing stack and queue data structures using classes and
objects have been successfully executed.
Viva Questions:

1. What is class?
2. What is stack?
3. What is the logic for push and pop function?
4. What are the types of operation in queue?
5. List out the members of class available in java.
Augmented Experiment:
1. Students mark and percentage calculation
2. Employee salary calculation
3. Area of Triangle and Rectangle calculation

20
DEVELOP A JAVA APPLICATION WITH AN EMPLOYEE CLASS
EX NO :3 WITH MEMBERS FOR GENERATE PAY SLIP USING
INHERITANCE

Aim:
To develop a java application with an employee class with members for generate pay
slip using inheritance.
Algorithm:

1. Create the class employee with name, Empid, address, mailid, mobileno as members.
2. Inherit the classes programmer, asstprofessor,associateprofessor and professor from
employee class.
3. Add Basic Pay (BP) as the member of all the inherited classes.
4. Calculate DA as 97% of BP, HRA as 10% of BP, PF as 12% of BP, Staff club fund as
0.1% of BP
5. Calculate gross salary and net salary.
6. Generate payslip for all categories of employees.
7. Create the objects for the inherited classes and invoke the necessary methods to
display the Payslip.
Program:

import [Link].*;
class employee
{
int empid;
long mobile;
String name, address, mailid;
Scanner get = new Scanner([Link]);
void getdata()
{
[Link]("Enter Name of the Employee");
name = [Link]();
[Link]("Enter Mail id");
mailid = [Link]();
[Link]("Enter Address of the Employee:");
address = [Link]();
21
[Link]("Enter employee id ");
empid = [Link]();
[Link]("Enter Mobile Number");
mobile = [Link]();
}
void display()
{
[Link]("Employee Name: "+name);
[Link]("Employee id : "+empid);
[Link]("Mail id : "+mailid);
[Link]("Address: "+address);
[Link]("Mobile Number: "+mobile);
}
}
class programmer extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getprogrammer()
{
[Link]("Enter basic pay");
bp = [Link]();
}
void calculateprog()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
[Link]("************************************************");
[Link]("PAY SLIP FOR PROGRAMMER");
[Link]("************************************************");
[Link]("Basic Pay:Rs"+bp);

22
[Link]("DA:Rs"+da);
[Link]("PF:Rs"+pf);
[Link]("HRA:Rs"+hra);
[Link]("CLUB:Rs"+club);
[Link]("GROSS PAY:Rs"+gross);
[Link]("NET PAY:Rs"+net);
}
}
class asstprofessor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getasst()
{
[Link]("Enter basic pay");
bp = [Link]();
}
void calculateasst()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
[Link]("************************************************");
[Link]("PAY SLIP FOR ASSISTANT PROFESSOR");
[Link]("************************************************");
[Link]("Basic Pay:Rs"+bp);
[Link]("DA:Rs"+da);
[Link]("HRA:Rs"+hra);
[Link]("PF:Rs"+pf);
[Link]("CLUB:Rs"+club);
[Link]("GROSS PAY:Rs"+gross);
[Link]("NET PAY:Rs"+net);

23
}
}
class associateprofessor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getassociate()
{
[Link]("Enter basic pay");
bp = [Link]();
}
void calculateassociate()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
[Link]("************************************************");
[Link]("PAY SLIP FOR ASSOCIATE PROFESSOR");
[Link]("************************************************");
[Link]("Basic Pay:Rs"+bp);
[Link]("DA:Rs"+da);
[Link]("HRA:Rs"+hra);
[Link]("PF:Rs"+pf);
[Link]("CLUB:Rs"+club);
[Link]("GROSS PAY:Rs"+gross);
[Link]("NET PAY:Rs"+net);
}
}
class professor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getprofessor()

24
{
[Link]("Enter basic pay");
bp = [Link]();
}
void calculateprofessor()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
[Link]("************************************************");
[Link]("PAY SLIP FOR PROFESSOR");
[Link]("************************************************");
[Link]("Basic Pay:Rs"+bp);
[Link]("DA:Rs"+da);
[Link]("HRA:Rs"+hra);
[Link]("PF:Rs"+pf);
[Link]("CLUB:Rs"+club);
[Link]("GROSS PAY:Rs"+gross);
[Link]("NET PAY:Rs"+net);
}
}
class salary
{
public static void main(String args[])
{
int choice,cont;
do
{
[Link]("PAYROLL");
[Link](" [Link] \t [Link] PROFESSOR \t
[Link] PROFESSOR \t [Link] ");

25
Scanner c = new Scanner([Link]);
choice=[Link]();
switch(choice)
{
case 1:
{
programmer p=new programmer();
[Link]();
[Link]();
[Link]();
[Link]();
break;
}
case 2:
{
asstprofessor asst=new asstprofessor();
[Link]();
[Link]();
[Link]();
[Link]();
break;
}
case 3:
{
associateprofessor asso=new associateprofessor();
[Link]();
[Link]();
[Link]();
[Link]();
break;
}
case 4:
{
professor prof=new professor();

26
[Link]();
[Link]();
[Link]();
[Link]();
break;
}
}
[Link]("Do u want to continue 0 to quit and 1 to continue ");
cont=[Link]();
}while(cont==1);
}
}
Output:

Result:

Thus the Java application has been created with employee class and pay slips are
generated for the employees with their gross and net salary using inheritance concepts
and implemented successfully.
Viva Questions:

1. What is inheritance?
2. What is base class and derived class?
27
3. What is the syntax for inherit one class to another class?
4. What are the types of inheritance?
5. List out the rules for access specifier available in java.
Augmented Experiment:
1. EB bill preparation
2. Income tax calculation

28
WRITE A JAVA PROGRAM TO CREATE AN ABSTRACT CLASS
EX NO :4
FOR CALCULATING AREA OF DIFFERENT SHAPE

Aim:
To write a java program to create abstract class for calculating area of different shape.
Algorithm:
1. Create an abstract class named shape that contains two integers and an empty method
named printarea().
2. Provide three classes named rectangle, triangle and circle such that each one of the
classes extends the class Shape.
3. Each of the inherited class from shape class should provide the implementation for the
method printarea().
4. Get the input and calculate the area of rectangle, circle and triangle.
5. In the shape class, create the objects for the three inherited classes and invoke the
methods and display the area values of the different shapes.

Program:

import [Link].*;
abstract class shape
{
int a,b;
abstract public void printarea();
}
class rectangle extends shape
{
public int area_rect;
public void printarea()
{
Scanner s=new Scanner([Link]);
[Link]("enter the length and breadth of rectangle");
a=[Link]();
b=[Link]();
area_rect=a*b;
[Link]("Length of rectangle "+a +"breadth of rectangle "+b);
29
[Link]("The area ofrectangle is:"+area_rect);
}
}
class triangle extends shape
{
double area_tri;
public void printarea()
{
Scanner s=new Scanner([Link]);
[Link]("enter the base and height of triangle");
a=[Link]();
b=[Link]();
[Link]("Base of triangle "+a +"height of triangle "+b);
area_tri=(0.5*a*b);
[Link]("The area of triangle is:"+area_tri);
}
}
class circle extends shape
{
double area_circle;
public void printarea()
{
Scanner s=new Scanner([Link]);
[Link]("enter the radius of circle");
a=[Link]();
area_circle=(3.14*a*a);
[Link]("Radius of circle"+a);
[Link]("The area of circle is:"+area_circle);
}
}
public class shapeclass
{
public static void main(String[] args)
{

30
rectangle r=new rectangle();
[Link]();
triangle t=new triangle();
[Link]();
circle r1=new circle();
[Link]();
}
}
Output:

Result:

Thus the Java program has been created with shape class and generated printarea() for
the class using abstract concepts and successfully implemented.
Viva Questions:

1. What is abstract class?


2. What is concrete statement and non-concrete statement?
3. What is the syntax for creating abstract class?
4. What is overriding concept in java?
Augmented Experiment:
3. Calculate Interest in different Bank
4. Calculate Income Tax in different country.

31
WRITE A JAVA PROGRAM TO CREATE INTERFACE FOR
EX NO :5
CALCULATING AREA OF DIFFERENT SHAPE

Aim:
To write a java program to create interface for calculating area of different shape.
Algorithm:
1. Create interface named shape that contains two integers and an empty method named
printarea().
2. Provide three classes named rectangle, triangle and circle such that each one of the
classes implements the interface Shape.
3. Each of the implemented class from shape interface should provide the implementation
for the method printarea().
4. Get the input and calculate the area of rectangle, circle and triangle.
5. In the shape interface, create the objects for the three inherited classes and invoke the
methods and display the area values of the different shapes.

Program:

import [Link].*;
interface shape
{
abstract public void printarea();
}
class rectangle implements shape
{
public int area_rect,a,b;
public void printarea()
{
Scanner s=new Scanner([Link]);
[Link]("enter the length and breadth of rectangle");
a=[Link]();
b=[Link]();
area_rect=a*b;
[Link]("Length of rectangle "+a +"breadth of rectangle "+b);
32
[Link]("The area ofrectangle is:"+area_rect);
}
}
class triangle implements shape
{
double area_tri;
public int a,b;
public void printarea()
{
Scanner s=new Scanner([Link]);
[Link]("enter the base and height of triangle");
a=[Link]();
b=[Link]();
[Link]("Base of triangle "+a +"height of triangle "+b);
area_tri=(0.5*a*b);
[Link]("The area of triangle is:"+area_tri);
}
}
class circle implements shape
{
double area_circle;
public int a;
public void printarea()
{
Scanner s=new Scanner([Link]);
[Link]("enter the radius of circle");
a=[Link]();
area_circle=(3.14*a*a);
[Link]("Radius of circle"+a);
[Link]("The area of circle is:"+area_circle);
}
}
public class shapeclass
{

33
public static void main(String[] args)
{
rectangle r=new rectangle();
[Link]();
triangle t=new triangle();
[Link]();
circle r1=new circle();
[Link]();
}
}
Output:

Result:

Thus the Java program has been created with shape interface and generated printarea()
for the interface using interface concepts and successfully implemented.
Viva Questions:

1. What is interface?
2. What is concrete statement and non-concrete statement?
3. What is the syntax for creating interface?
4. How to implement abstract methods in interface?
Augmented Experiment:
1. Calculate Interest in different Bank
2. Calculate Income Tax in different country.

34
EX NO :6 IMPLEMENT EXCEPTION HANDLING AND CREATION OF USER
DEFINED EXCEPTIONS

Aim:
To write a java program for implementing user defined exceptions handling.
Algorithm:
1. Create a class which extends Exception class.
2. Create a constructor which receives the string as argument.
3. Get the amount as input from the user.
4. If the amount is negative, the exception will be generated.
5. Using the exception handling mechanism, the thrown exception is handled by the catch
construct.
6. After the exception is handled, the string “invalid amount “will be displayed.
7. If the amount is greater than 0 , the message “Amount Deposited “ will be displayed
Program:

import [Link];
class NegativeAmtException extends Exception
{
String msg;
NegativeAmtException(String msg)
{
[Link]=msg;
}
public String toString()
{
return msg;
}
}
public class userdefined
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
35
[Link]("Enter Amount:");
int a=[Link]();
try
{
if(a<0)
{
throw new NegativeAmtException("Invalid Amount");
}
[Link]("Amount Deposited");
}
catch(NegativeAmtException e)
{
[Link](e);
}
}
}
Output:

Result:

Thus the Java program has been created for the user defined exception handling and
successfully implemented.
Viva Questions:

1. What is exception?
2. What are the block of structure in exception?
3. What the syntax is for try and catch block?
4. What is finally in exception?
Augmented Experiment:
1. Array out of bounds exception.

36
EX NO :7
IMPLEMENT A MULTI THREADED APPLICATION

Aim:
To write a java program for implementing multi-threaded application.
Algorithm:
1. Create a class even which implements first thread that computes .the square of the
number.
2. run() method implements the code to be executed when thread gets executed.
3. Create a class odd which implements second thread that computes the cube of the
number.
4. Create a third thread that generates random number. If the random number is even, it
displays the square of the number. If the random number generated is odd, it displays
the cube of the given number.
5. The Multithreading is performed and the task switched between multiple threads.
6. The sleep () method makes the thread to suspend for the specified time.

Program:

import [Link].*;
class even implements Runnable
{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
[Link]("New Thread "+ x +" is EVEN and Square of " + x + " is: " + x *
x);
}
}
class odd implements Runnable

37
{
public int x;
public odd(int x)
{
this.x = x;
}
public void run()
{
[Link]("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x * x *
x);
}
}
class A extends Thread
{
public void run()
{
int num = 0;
Random r = new Random();
try
{
for (int i = 0; i < 5; i++)
{
num = [Link](100);
[Link]("Main Thread and Generated Number is " + num);
if (num % 2 == 0)
{
Thread t1 = new Thread(new even(num));
[Link]();
}
else
{
Thread t2 = new Thread(new odd(num));
[Link]();
}

38
[Link](1000);
[Link](" ");
}
}
catch (Exception ex)
{
[Link]([Link]());
}
}
}
public class multithreadprog
{
public static void main(String[] args)
{
A a = new A();
[Link]();
}
}
Output:

Result:

Thus the Java program has been created for the multi-threaded application and
successfully implemented.
Viva Questions:

1. What is thread?
2. What are the methods are used for thread?

39
3. What the syntax is thread formation?
4. What is run method in thread?
Augmented Experiment:
1. Thread create with runnable interface.
2. Thread create with thread class.
3. Thread create with both.

40
EX NO :8
PROGRAM TO PERFORM FILE OPERATIONS

Aim:
To write a java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length
of the file in bytes.
Algorithm:
1. Create a class filedemo. Get the file name from the user.
2. Use the file functions and display the information about the file.
3. getName() displays the name of the file.
4. getPath() diplays the path name of the file.
5. getParent () -This method returns the pathname string of this abstract pathname’s
parent, or null if this pathname does not name a parent directory.
6. exists() – Checks whether the file exists or not.
7. canRead()-This method is basically a check if the file can be read.
8. canWrite()-verifies whether the application can write to the file.
9. isDirectory() – displays whether it is a directory or not.
10. isFile() – displays whether it is a file or not.
11. lastmodified() – displays the last modified information.
12. length()- displays the size of the file.
13. delete() – deletes the file
14. Invoke the predefined functions abd display the information about the file.
Program:

import [Link].*;
import [Link].*;
class filedemo
{
public static void main(String args[])
{
String filename;
Scanner s=new Scanner([Link]);
[Link]("Enter the file name ");

41
filename=[Link]();
File f1=new File(filename);
[Link]("*****************");
[Link]("FILE INFORMATION");
[Link]("*****************");
[Link]("NAME OF THE FILE "+[Link]());
[Link]("PATH OF THE FILE "+[Link]());
[Link]("PARENT"+[Link]());
if([Link]())
[Link]("THE FILE EXISTS ");
else
[Link]("THE FILE DOES NOT ExISTS ");
if([Link]())
[Link]("THE FILE CAN BE READ ");
else
[Link]("THE FILE CANNOT BE READ ");
if([Link]())
[Link]("WRITE OPERATION IS PERMITTED");
else
[Link]("WRITE OPERATION IS NOT PERMITTED");
if([Link]())
[Link]("IT IS A DIRECTORY ");
else
[Link]("NOT A DIRECTORY");
if([Link]())
[Link]("IT IS A FILE ");
else
[Link]("NOT A FILE");
[Link]("File last modified "+ [Link]());
[Link]("LENGTH OF THE FILE "+[Link]());
[Link]("FILE DELETED "+[Link]());
}
}

42
Output:

Result:

Thus the Java program has been created for the file operations and successfully
implemented.
Viva Questions:

1. What is file in JAVA?


2. What are the method used in File?
3. How to implement write or read mode in file?

Augmented Experiment:
1. Using append to include in file.
2. File with character data.
3. File with mixed data.

43
DEVELOP AN APPLICATION FOR IMPLEMENTING GENERIC
EX NO :9
CLASS

Aim:
To write a java program for implementing generic class.
Algorithm:
1. Create a class Myclass to implement generic class and generic methods.
2. Get the set of the values belonging to specific data type.
3. Create the objects of the class to hold integer, character and double values.
4. Create the method to compare the values and find the maximum value stored in the
array.
5. Invoke the method with integer, character or double values. The output will be
displayed based on the data type passed to the method.

Program:

class MyClass<T extends Comparable<T>>


{
T[] vals;
MyClass(T[] o)
{
vals = o;
}
public T min()
{
T v = vals[0];
for(int i=1; i < [Link]; i++)
if(vals[i].compareTo(v) < 0)
v = vals[i];
return v;
}
public T max()
{
T v = vals[0];
for(int i=1; i < [Link];i++)
44
if(vals[i].compareTo(v) > 0)
v = vals[i];
return v;
}
}
class gendemo
{
public static void main(String args[])
{
int i;
Integer inums[]={10,2,5,4,6,1};
Character chs[]={'v','p','s','a','n','h'};
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};
MyClass<Integer> iob = new MyClass<Integer>(inums);
MyClass<Character> cob = new MyClass<Character>(chs);
MyClass<Double>dob = new MyClass<Double>(d);
[Link]("Max value in inums: " + [Link]());
[Link]("Min value in inums: " + [Link]());
[Link]("Max value in chs: " + [Link]());
[Link]("Min value in chs: " + [Link]());
[Link]("Max value in chs: " + [Link]());
[Link]("Min value in chs: " + [Link]());
}
}
Output:

Result:

Thus the Java program has been created for the generic class and successfully
implemented.

45
Viva Questions:

1. What is generic class?


2. What is generic method?
3. What the syntax is followed in generic class and method?
Augmented Experiment:
4. Bubble sort
5. Linear search
6. Insertion sort

46
DEVELOP APPLICATIONS (CALCULATOR) USING JAVAFX
EX NO :10
CONTROLS, LAYOUTS AND MENUS (MINI PROJECT)

Aim:
To design a calculator as a mini project using event driven programming paradigm of
java with the following options
a) Decimal Manipulations
b) Scientific Manipulations
Algorithm:
1. import the swing packages and awt packages.
2. Create the class scientific calculator that implements action listener.
3. Create the container and add controls for digits , scientific calculations and decimal
Manipulations.
4. The different layouts can be used to lay the controls.
5. When the user presses the control, the event is generated and handled.
6. The corresponding decimal, numeric and scientific calculations are performed.

Program:

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class ScientificCalculator extends JFrame implements ActionListener
{
JTextField tfield;
double temp, temp1, result, a;
static double m1, m2;
int k = 1, x = 0, y = 0, z = 0;
char ch;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, zero, clr, pow2, pow3, exp,
fac, plus, min, div, log, rec, mul, eq, addSub, dot, mr, mc, mp,
mm, sqrt, sin, cos, tan;
Container cont;
JPanel textPanel, buttonpanel;
47
ScientificCalculator()
{
cont = getContentPane();
[Link](new BorderLayout());
JPanel textpanel = new JPanel();
tfield = new JTextField(25);
[Link]([Link]);
[Link](new KeyAdapter() {
public void keyTyped(KeyEvent keyevent) {
char c = [Link]();
if (c >= '0' && c <= '9') {
}
else
{
[Link]();
}
}
});
[Link](tfield);
buttonpanel = new JPanel();
[Link](new GridLayout(8, 4, 2, 2));
boolean t = true;
mr = new JButton("MR");
[Link](mr);
[Link](this);
mc = new JButton("MC");
[Link](mc);
[Link](this);
mp = new JButton("M+");
[Link](mp);
[Link](this);
mm = new JButton("M-");
[Link](mm);
[Link](this);

48
b1 = new JButton("1");
[Link](b1);
[Link](this);
b2 = new JButton("2");
[Link](b2);
[Link](this);
b3 = new JButton("3");
[Link](b3);
[Link](this);
b4 = new JButton("4");
[Link](b4);
[Link](this);
b5 = new JButton("5");
[Link](b5);
[Link](this);
b6 = new JButton("6");
[Link](b6);
[Link](this);
b7 = new JButton("7");
[Link](b7);
[Link](this);
b8 = new JButton("8");
[Link](b8);
[Link](this);
b9 = new JButton("9");
[Link](b9);
[Link](this);
zero = new JButton("0");
[Link](zero);
[Link](this);
plus = new JButton("+");
[Link](plus);
[Link](this);
min = new JButton("-");

49
[Link](min);
[Link](this);
mul = new JButton("*");
[Link](mul);
[Link](this);
div = new JButton("/");
[Link](this);
[Link](div);
addSub = new JButton("+/-");
[Link](addSub);
[Link](this);
dot = new JButton(".");
[Link](dot);
[Link](this);
eq = new JButton("=");
[Link](eq);
[Link](this);
rec = new JButton("1/x");
[Link](rec);
[Link](this);
sqrt = new JButton("Sqrt");
[Link](sqrt);
[Link](this);
log = new JButton("log");
[Link](log);
[Link](this);
sin = new JButton("SIN");
[Link](sin);
[Link](this);
cos = new JButton("COS");
[Link](cos);
[Link](this);
tan = new JButton("TAN");
[Link](tan);

50
[Link](this);
pow2 = new JButton("x^2");
[Link](pow2);
[Link](this);
pow3 = new JButton("x^3");
[Link](pow3);
[Link](this);
exp = new JButton("Exp");
[Link](this);
[Link](exp);
fac = new JButton("n!");
[Link](this);
[Link](fac);
clr = new JButton("AC");
[Link](clr);
[Link](this);
[Link]("Center", buttonpanel);
[Link]("North", textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
String s = [Link]();
if ([Link]("1"))
{
if (z == 0)
{
[Link]([Link]() + "1");
}
else
{
[Link]("");
[Link]([Link]() + "1");
z = 0;

51
}
}
if ([Link]("2")) {
if (z == 0) {
[Link]([Link]() + "2");
}
else
{
[Link]("");
[Link]([Link]() + "2");
z = 0;
}
}
if ([Link]("3")) {
if (z == 0) {
[Link]([Link]() + "3");
}
else
{
[Link]("");
[Link]([Link]() + "3");
z = 0;
}
}
if ([Link]("4")) {
if (z == 0) {
[Link]([Link]() + "4");
}
else
{
[Link]("");
[Link]([Link]() + "4");
z = 0;
}

52
}
if ([Link]("5")) {
if (z == 0) {
[Link]([Link]() + "5");
}
else
{
[Link]("");
[Link]([Link]() + "5");
z = 0;
}
}
if ([Link]("6")) {
if (z == 0) {
[Link]([Link]() + "6");
}
else
{
[Link]("");
[Link]([Link]() + "6");
z = 0;
}
}
if ([Link]("7")) {
if (z == 0) {
[Link]([Link]() + "7");
}
else
{
[Link]("");
[Link]([Link]() + "7");
z = 0;
}
}

53
if ([Link]("8")) {
if (z == 0) {
[Link]([Link]() + "8");
}
else
{
[Link]("");
[Link]([Link]() + "8");
z = 0;
}
}
if ([Link]("9")) {
if (z == 0) {
[Link]([Link]() + "9");
}
else
{
[Link]("");
[Link]([Link]() + "9");
z = 0;
}
}
if ([Link]("0"))
{
if (z == 0) {
[Link]([Link]() + "0");
}
else
{
[Link]("");
[Link]([Link]() + "0");
z = 0;
}
}

54
if ([Link]("AC")) {
[Link]("");
x = 0;
y = 0;
z = 0;
}
if ([Link]("log"))
{
if ([Link]().equals("")) {
[Link]("");
}
Else
{
a = [Link]([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("1/x")) {
if ([Link]().equals("")) {
[Link]("");
}
else
{
a = 1 / [Link]([Link]());
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("Exp")) {
if ([Link]().equals("")) {
[Link]("");
}
else

55
{
a = [Link]([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("x^2")) {
if ([Link]().equals("")) {
[Link]("");
}
else
{
a = [Link]([Link]([Link]()), 2);
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("x^3")) {
if ([Link]().equals("")) {
[Link]("");
}
else
{
a = [Link]([Link]([Link]()), 3);
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("+/-")) {
if (x == 0) {
[Link]("-" + [Link]());
x = 1;
}
else

56
{
[Link]([Link]());
}
}
if ([Link](".")) {
if (y == 0) {
[Link]([Link]() + ".");
y = 1;
}
else
{
[Link]([Link]());
}
}
if ([Link]("+"))
{
if ([Link]().equals(""))
{
[Link]("");
temp = 0;
ch = '+';
}
else
{
temp = [Link]([Link]());
[Link]("");
ch = '+';
y = 0;
x = 0;
}
[Link]();
}
if ([Link]("-"))
{

57
if ([Link]().equals(""))
{
[Link]("");
temp = 0;
ch = '-';
}
else
{
x = 0;
y = 0;
temp = [Link]([Link]());
[Link]("");
ch = '-';
}
[Link]();
}
if ([Link]("/")) {
if ([Link]().equals(""))
{
[Link]("");
temp = 1;
ch = '/';
}
else
{
x = 0;
y = 0;
temp = [Link]([Link]());
ch = '/';
[Link]("");
}
[Link]();
}
if ([Link]("*")) {

58
if ([Link]().equals(""))
{
[Link]("");
temp = 1;
ch = '*';
}
else
{
x = 0;
y = 0;
temp = [Link]([Link]());
ch = '*';
[Link]("");
}
[Link]();
}
if ([Link]("MC"))
{
m1 = 0;
[Link]("");
}
if ([Link]("MR"))
{
[Link]("");
[Link]([Link]() + m1);
}
if ([Link]("M+"))
{
if (k == 1) {
m1 = [Link]([Link]());
k++;
}
else
{

59
m1 += [Link]([Link]());
[Link]("" + m1);
}
}
if ([Link]("M-"))
{
if (k == 1) {
m1 = [Link]([Link]());
k++;
}
else
{
m1 -= [Link]([Link]());
[Link]("" + m1);
}
}
if ([Link]("Sqrt"))
{
if ([Link]().equals(""))
{
[Link]("");
}
else
{
a = [Link]([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("SIN"))
{
if ([Link]().equals(""))
{
[Link]("");

60
}
else
{
a = [Link]([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("COS"))
{
if ([Link]().equals(""))
{
[Link]("");
}
else
{
a = [Link]([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("TAN")) {
if ([Link]().equals("")) {
[Link]("");
}
else
{
a = [Link]([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
if ([Link]("="))
{

61
if ([Link]().equals(""))
{
[Link]("");
}
else
{
temp1 = [Link]([Link]());
switch (ch)
{
case '+':
result = temp + temp1;
break;
case '-':
result = temp - temp1;
break;
case '/':
result = temp / temp1;
break;
case '*':
result = temp * temp1;
break;
}
[Link]("");
[Link]([Link]() + result);
z = 1;
}
}
if ([Link]("n!"))
{
if ([Link]().equals(""))
{
[Link]("");
}
else

62
{
a = fact([Link]([Link]()));
[Link]("");
[Link]([Link]() + a);
}
}
[Link]();
}
double fact(double x)
{
int er = 0;
if (x < 0)
{
er = 20;
return 0;
}
double i, s = 1;
for (i = 2; i <= x; i += 1.0)
s *= i;
return s;
}
public static void main(String args[])
{
try
{
[Link]("[Link]
eel");
}
catch (Exception e)
{
}
ScientificCalculator f = new ScientificCalculator();
[Link]("ScientificCalculator");
[Link]();

63
[Link](true);
}
}

Output:

Result:

Thus the Java program has been created for the mini project using JavaFX and
successfully implemented.
Viva Questions:

1. What is awt?
2. What is frame in java?
3. What the syntax is followed in JavaFx tool box?
Augmented Experiment:
1. Attendance calculation
2. Time table preparation

64

You might also like