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

Java Data Structures & Algorithms Lab Report

Uploaded by

Reeta
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 views54 pages

Java Data Structures & Algorithms Lab Report

Uploaded by

Reeta
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

P.T.

R
COLLEGE OF ENGINEERING & TECHNOLOGY
T Thanapandiyan Nagar,AIIMS Road, Satellite Town,
madurai-8.

Reg no:

DEPARTMENT OF
Name Year

Certified that this a Bonafide record of work done by the above student in the

Laboratory during the year

Signature of the lab-In Charge Signature of the head of dept

Submitted for the practical examination held on

Internal Examiner External Examiner


1
CONTENTs

[Link] DATE LIST OF EXERCISES [Link] SIGN

1. Solve problems by using sequential search,


binary search, and quadratic sorting
algorithms

2. Develop stack and queue data structures


using classes and objects

3. Develop a java application with an


employee
Class with members for generate pay slip
using inheritance
4. Write a java program to create an abstract
class
for calculating area of different shape

5. Write a java program to create Interface for


Calculating area of different shape

6. Implement exception handling and creation


of
User defined exception
7. Implement a multi-Threaded application

8. Write a program to perform file operations

9. Develop applications to demonstrate the


features of generics classes

10. Develop application using JavaFX controls,


Layouts and menus

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

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);

3
}
}
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;
4
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;}
}

5
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++)
{

6
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.

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

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

8
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);
9
[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

removed value of queue[front]


decrement front
end else
end

10
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;

11
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--;
}
12
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.

13
EX NO :3 DEVELOP A JAVA APPLICATION WITH AN EMPLOYEE CLASS
WITH MEMBERS FOR GENERATE PAY SLIP USING
DATE: 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]();
14
[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);

15
[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);

16
}
}
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()

17
{
[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] ");

18
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();

19
[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

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

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);
21
[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)
{

22
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.

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

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);
24
[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
{

25
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.

26
EX NO :6
IMPLEMENT EXCEPTION HANDLING AND CREATION OF USER
DATE: 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]);

27
[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.

28
EX NO :7

DATE: 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

29
{
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]();
}

30
[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.

31
EX NO :8
PROGRAM TO PERFORM FILE OPERATIONS
DATE:

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 ");

32
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]());
}
}

33
Output:

Result:

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

34
DEVELOP AN APPLICATION FOR IMPLEMENTING GENERIC
EX NO :9
CLASS
DATE:

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++)
35
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.

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

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;
37
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);

38
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("-");

39
[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);

40
[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;

41
}
}
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;
}

42
}
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;
}
}

43
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;
}
}

44
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

45
{
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

46
{
[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]("-"))
{

47
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]("*")) {

48
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
{

49
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]("");

50
}
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]("="))
{

51
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

52
{
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]();

53
[Link](true);
}
}

Output:

Result:

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

54

Common questions

Powered by AI

Both the abstract class and the interface approach require the classes (rectangle, triangle, circle) to define the 'printarea()' method, ensuring these shapes provide a unique calculation of their area. The key similarity is that they both support polymorphism and enforce structural consistency. The primary difference is in how they achieve this: abstract classes allow inheritance of state (variables) and implementation (methods), whereas interfaces provide no state or implementation, only method signatures, which enforces a contract with greater flexibility across different class hierarchies .

Using a generic class for computing maximum and minimum values is highly effective as it facilitates code reusability and type safety. By defining the class to operate on objects of a specified type T, it ensures that the algorithms for finding maximum and minimum are applicable to any data type that implements Comparable. This approach reduces redundancy and increases flexibility, as seen with Integer, Character, and Double types in the examples, all of which can use the same class methods without modification while avoiding the pitfalls of typecast and class-specific code .

The Java program implements event-driven programming by using the ActionListener interface, which listens for actions such as button presses. Each button in the calculator interface corresponds to a specific calculation or input operation. When a button is pressed, the 'actionPerformed' method is triggered, and the program determines which operation to execute based on the event source. This design allows the calculator to respond dynamically to user inputs and perform operations such as addition, subtraction, or scientific functions in real-time, thus making it interactive and responsive .

To generate a pay slip for the "programmer" subclass, the program first prompts for the basic pay input. It calculates DA as 97% of BP, HRA as 10% of BP, PF as 12% of BP, and staff club fund as 0.1% of BP. The gross salary is calculated by adding BP, DA, and HRA. The net salary is obtained by subtracting PF and club contributions from the gross salary. The computed values are then printed as part of the pay slip for the programmer .

The Java program handles user-defined exceptions by creating a class 'NegativeAmtException' that extends the Exception class. It captures an error message that can be accessed when the exception is triggered. If the input amount is negative, an instance of this exception is thrown, allowing the program to catch and manage this specific error using try-catch blocks. This mechanism prevents unexpected behavior or crashes in response to invalid input, allowing the program to output 'Invalid Amount' gracefully and demonstrating robust error handling .

Java Swing is a part of Java's standard library that facilitates building graphical user interfaces. In the described program, Swing components like JFrame, JPanel, and JButton are used to construct the calculator's interface. Swing is suitable for this application because it provides a rich set of widgets and layout managers that are necessary for creating a complex GUI application. Additionally, Swing is platform-independent, allowing consistent behavior across different operating systems, which is crucial for portable Java applications .

The event handling mechanism ensures input integrity and operational correctness by listening for and responding to user actions in real-time through the ActionListener interface. Each button press is mapped to specific logic in the 'actionPerformed' method, enabling the calculator to execute operations only when valid inputs are provided. The use of method calls corresponding to each arithmetical or scientific calculation prevents user error by ensuring that only defined procedures are accessible, and inappropriate user actions like invalid numeric input are automatically managed by the GUI's design, resulting in accurate and reliable interactions .

The Java Employee class serves as the base class with common attributes such as name, Empid, address, mailid, and mobileno that are inherited by subclasses for different positions. These subclasses include programmer, assistant professor, associate professor, and professor, each adding specific functionality to handle payroll details. The pay slip generation leverages inheritance by allowing each subclass to calculate various financial metrics like DA, HRA, PF, and net salary using overridden methods. By using a common base class for inheritance, code reusability is maximized, and logical separation of roles is maintained while generating pay slips for each employee type .

Java interfaces provide more flexibility than abstract classes as a class can implement multiple interfaces, allowing different types of functionalities to be added without the limitations of single inheritance. In the context of the area calculations, using an interface like 'shape' allows the program to enforce a contract (the method 'printarea()') that must be implemented by all geometrical shape classes. This not only ensures a uniform method signature but also allows other unrelated classes to adopt this interface alongside their primary inheritance hierarchy, enabling a more versatile design compared to abstract classes which do not allow multiple inheritance .

The abstract class named 'shape' declares an empty method 'printarea()' which must be implemented by all subclasses. This design enforces a structure for subclasses such as rectangle, triangle, and circle to provide specific implementations of area calculation. Each subclass implements the method 'printarea()' to calculate its respective area using relevant formulas (e.g., a rectangle's area is length multiplied by breadth), thus ensuring consistent API across different shape types and promoting code reuse and polymorphism .

You might also like