Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
24 views72 pages

Oops Lab Manual (3) - Merged

The document outlines various Java implementations for searching algorithms (sequential and binary search), sorting algorithms (selection and insertion sort), and data structures (stack and queue). Each section includes an aim, algorithm steps, and example code with outputs demonstrating functionality. Additionally, it describes an employee payslip application that calculates gross and net salary based on employee details and basic pay.

Uploaded by

tamilarasi
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)
24 views72 pages

Oops Lab Manual (3) - Merged

The document outlines various Java implementations for searching algorithms (sequential and binary search), sorting algorithms (selection and insertion sort), and data structures (stack and queue). Each section includes an aim, algorithm steps, and example code with outputs demonstrating functionality. Additionally, it describes an employee payslip application that calculates gross and net salary based on employee details and basic pay.

Uploaded by

tamilarasi
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
You are on page 1/ 72

1(a).

IMPLEMENTATION OF SEQUENTIAL SEARCH

AIM:

To develop java application to implement sequential search

ALGORITHM:

Step-0: Start the program

Step-1: Get the length of arrays

Step-2: Get the element to be searched and store it in a variable named value.

Step-3: Compare each element of the array with the variable name

Step-4: In case of a match pair message saying element found is displayed.

Step-5: Else print a message saying element not found is displayed.

Step-6: stop the program

PROGRAM:
(SequentialSearch.java)

import java.util.*;
class SequentialSearch
{
public static int search(int arr[], int x)
{
int n = arr.length;
for (int i = 0; i < n; i++)
{
if (arr[i] == x)
return i;
}
return -1;
}
public static void main(String args[])
{
int arr[] = new int[10];
int i;
Scanner s=new Scanner(System.in)
System.out.println(“Enter the Number of elements”);
int n= s.nextInt();
System.out.println(“Enter the array elements”)
for(i=0;i<n;i++)
{
arr[i] = s.nextInt();
}
System.out.println(“Enter the elements to be searched:”)
int x=s.nextInt();
int result = search(arr, x);
if (result == -1)
System.out.print("Element is not present in array");
else
System.out.print("Element is present at index “+ result);
}
}
OUTPUT:

Enter the Number of elements: 5


Enter the array elements
67
54
4
97
23
Enter the elements to be searched: 4
Element is present at index 2

Enter the elements to be searched: 45


Element is not present in array
1(b).IMPLEMENTATION OF BINARY SEARCH

AIM:

To write a java program for binary search

ALGORITHM:

Step-0: Start the program


Step-1: Get the element to be searched stored it in a variable named value.
Step-2: Get the length of the array
Step-3: Find the mid value and compare into the searching element.
Step-4: In case of a match print the value.
Step-5: Else repeat the process until the element to be searched.
Step-6: stop the program

PROGRAM:

(BinarySearch.java)
import java.util.*;
class BinarySearch
{
public static void binarySearch(int[] arr, int key)
{
int first = 0;
int last = input.length - 1;
int mid = (first + last) / 2;
while (first <= last)
{
if (arr[mid] < key)
{
first = mid + 1;
}
else if (arr[mid] == key)
{
System.out.println(key + " is found at location"+mid);
break;
}
else
{
last = mid - 1;
}
mid = (first + last) / 2;
}
if (first > last)
{
System.out.println(key + " is not present in the list.\n");
}
}
public static void main (String args[])
{
int arr[] = new int[10];
int i;
Scanner s=new Scanner(System.in)
System.out.println(“Enter the Number of elements”);
int n= s.nextInt();
System.out.println(“Enter the array elements”)
for(i=0;i<n;i++)
{
arr[i] = s.nextInt();
}
System.out.println(“Enter the elements to be searched:”)
int x=s.nextInt();
binarysearch(arr, x);
}
OUTPUT:

Enter the Number of elements: 5


Enter the array elements
17
25
45
63
86
Enter the elements to be searched: 45
45 is found at location 2

Enter the elements to be searched: 93


93 is not present in the list.
1 c) Implementation of Selection Sort

AIM:

Write a java program for implementation of selection sort

ALGORITHM:

Step-0: Start the program


Step-1: Set min to location 0
Step-2: Search the minimum element in the list
Step-3: Swap with value at location
Step-4: Increment min to point next element
Step-5: Repeat until the list is sorted.
Step-6: stop the program

Program:

(SelectionSort.java)
import java.util.*;
class SelectionSort
{
public static void main (String args[ ])
{
int a[] = new int[10];
System.out.println(“\n How many elements want to enter in an array?”);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt( );
for (int i=0; i<n; i++)
{
System.out.println(“\n Enter the Elements:”);
a[i] = sc.nextInt( );
}
System.out.println(“Before Sorting…”);
for (int i=0; i<n; i++)
{
System.out.println(a[i]+“ ”);
}
System.out.println(“Sorting process…”);
for(int i=0; i<n-1; i++)
{
int k = i;
for(int j=i+1; j<n; j++)
{
if(a[j]<a[k])
k = j;
}
int temp = a[k];
a[k] = a[i];
a[i] = temp;
}
System.out.println(“After Sorting…”);
for (int i=0; i<n; i++)
{
System.out.println(a[i]+“ ”);
}
}
}
OUTPUT:
How many elements want to enter in an array?
5
Enter the Elements
56
Enter the Elements
3
Enter the Elements
87
Enter the Elements
14
Enter the Elements
2

Before Sorting…
56 3 87 14 2

Sorting process….

After Sorting…
2 3 14 56 87
1 d) Implementation of Insertion Sort

AIM:

Tow write a java program to implementation of insertion sort.

ALGORITHM:

Step-0: Start the program


Step-1: If it is the first element, it is already sorted, return 1.
Step-2: Print next element
Step-3: Compare with all elements in the sorted sub-list
Step-4: Shift all the elements in the sorted sub-list that is greater than the value to be sorted.
Step-5: Insert the value.
Step-6: Repeat until the list is sorted.
Step-7: Stop the program.

PROGRAM:

(InsertionSort.java)
import java.util.*;
public class InsertionSort
{
public static void main(String[] args)
{
int a[] = new int[10];
System.out.println("How many elements want to enter in an array?");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt( );
for (int i=0; i<n; i++)
{
System.out.println("Enter the Elements");
a[i] = sc.nextInt( );
}
System.out.println("Before Sorting…");
for (int i=0; i<n; i++)
{
System.out.println(a[i]+" ");
}
System.out.println("Sorting process ... ");
for(int i=1; i<n; ++i)
{
int key = a[i];
int j = i-1;
while(j >=0 && a[j]>key)
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = key;
}
System.out.println("After Sorting…");
for (int i=0; i<n; i++)
{
System.out.println(a[i]+" ");
}
}

}
OUTPUT:
How many elements want to enter in an array?
6
Enter the Elements
98
Enter the Elements
56
Enter the Elements
24
Enter the Elements
43
Enter the Elements
18
Enter the Elements
3

Before Sorting…
98 56 24 43 18 3

Sorting process....

After Sorting…
3 18 24 43 56 98
2 a) Implementation of Stack ADT

AIM:

To develop a java program for implementation of stack in ADT in java

ALGORITHM:

Step-0: Start the program


Step-1: Create a class for stack
Step-2: After creating the stack check whether it is underflow
Step-3: Store the elements in the stack.
Step-4: Using array insert the element
Step-5: Initialize the array inside the stack variable.
Step-6: Push the element to the top of stack.
Step-7: Create a main method.
Step-6: stop the program

PROGRAM:

(StackDemo.java)
public class StackDemo //Class Creation
{
int size;
int stack[];
int top;
StackDemo(int s) //Constructor with one parameter
{
size = s;
stack = new int[size];
top = -1;
}
public void push(int element) //push operation
{
if(top == size-1)
{
System.out.println("Cannot insert Stack is Full");
}
else
{
top++;
stack[top] = element;
System.out.println("Elements Pused on stack is:"+element);
}
}
public int pop() //pop operation
{
if(top == -1)
{
System.out.println(" Cannot pop Stack is Empty");
return -1;
}
else
{
int item;
item = stack[top];
top --;
System.out.println("Element popped from stack is:"+item);
return item;
}
}
public int peek() //peek operation
{
if(top == -1)
{
System.out.println(" Cannot peek Stack is Empty");
return -1;
}
else
{
return stack[top];
}
}

public static void main (String [] args)


{
StackDemo s = new StackDemo(10); // Object Creation
System.out.println("-----------PUSH OPERATION ----------- ");
s.push(30);
s.push(50);
s.push(80);
s.push(10);
s.push(40);
System.out.println("------------PEEK OPERATION --------- ");
System.out.println("The Top element in the stack is:"+s.peek());
System.out.println("-----------POP OPERATION -----------");
s.pop();
s.pop();
s.pop();
s.pop();
s.pop();
s.pop();
}
}
OUTPUT:

-----------PUSH OPERATION------------
Elements Pused on stack is:30
Elements Pused on stack is:50
Elements Pused on stack is:80
Elements Pused on stack is:10
Elements Pused on stack is:40

------------PEEK OPERATION-----------
The Top element in the stack is:40

-----------POP OPERATION------------
Element popped from stack is:40
Element popped from stack is:10
Element popped from stack is:80
Element popped from stack is:50
Element popped from stack is:30

Cannot pop Stack is Empty


2 b) Implementation of Queue ADT

AIM:

To develop a queue data structure for implementation in java

ALGORITHM:

Step-0: Start the program


Step-1: Check if the queue is full.
Step-2: If the queue is full, produce overflow error and exit.
Step-3: If the queue is not full, increment rear pointer to point the next empty space.
Step-4: Add data element to the queue location, where the rear is pointing.
Step-5: Return success
Step-6: stop the program

PROGRAM:

(QueueDemo.java)
import java.util.*;
public class QueueDemo
{
int capacity;
int que[];
int front,rear,size;
QueueDemo(int n)
{
capacity = n;
que = new int[n];
front = 0;
rear = -1;
size = 0;
}
public void enqueue(int item)
{
if(rear == capacity)
{
System.out.println("Queue is Full");
}
else
{
que[++rear] = item;
size++;
System.out.println("Insertion to queue:" +item);
}
}
public void dequeue()
{
if(front==rear)
{
System.out.println("Queue is empty");
}
else
{
int item=que[front++];
size--;
System.out.println("The deleted item is:"+item);
}
}
public void display()
{
if(front == rear)
{
System.out.println("Queue is empty");
}
else
{
for(int i=front; i<=rear; i++)
{
System.out.println(""+que[i]);
}
}
}

public static void main(String[] args)


{
QueueDemo q = new QueueDemo(5);
System.out.println("Implementation of Queue using Array");
System.out.println("\n1.Enqueue \n2.Dequeue \n3.Display \n4.Exit");
Scanner sc= new Scanner(System.in);
for(;;)
{
System.out.println("\nEnter the Choice:");
int ch = sc.nextInt();
switch(ch)
{
case 1: System.out.println("ENQUEUE OPERATION");
System.out.println("enter the element to be inserted:");
int ele = sc.nextInt();
q.enqueue(ele);
break;
case 2: System.out.println("DEQUEUE OPERATION");
q.dequeue();
break;
case 3: System.out.println("DISPLAY OPERATION");
q.display();
break;
case 4: System.out.println("Queue implementaion completed successfully");
break;

}
}
}
}
OUTPUT:

Implementation of Queue using Array

1. Enqueue
2.Dequeue
3.Display
4.Exit

Enter the Choice:


1
ENQUEUE OPERATION
enter the element to be inserted:
45
Insertion to queue:45

Enter the Choice:


1
ENQUEUE OPERATION
enter the element to be inserted:
32
Insertion to queue:32

Enter the Choice:


1
ENQUEUE OPERATION
enter the element to be inserted:
87
Insertion to queue:87

Enter the Choice:


3
DISPLAY OPERATION
45
32
87

Enter the Choice:


2
DEQUEUE OPERATION
The deleted item is:45

Enter the Choice:


3
DISPLAY OPERATION
32
87

Enter the Choice:


2
DEQUEUE OPERATION
The deleted item is:32
Enter the Choice:
2
DEQUEUE OPERATION
Queue is empty

Enter the Choice:


4
Queue implementaion completed successfully
3) Implementation Employee Payslip

AIM:

To develop a java application with employee class and implementation pay slips for the employees
with their gross and net salary.

ALGORITHM:

Step-0: Start the program


Step-1: Create Employee class with Emp_name, Emp_id, Address, Mail_id, Mobile_no as members.
Step-2: Inherit the class,programmer,assistant professor,associate professor and professor from
employee class.
Step-3:Add Basic pay(BP) as the member of all the inherited class with 97% of BP as DA,10% of BP
as HRA,12% of BP as PF,0.1% of BP for Staff club fund.
Step-4: Generating pay slips for the employees with their gross and net salary.
Step-5: stop the program

PROGRAM :

(Employee.java)
import java.util.*;
class Employee
{
String ename,address,mailid;
int eid;
long mobileno;
Scanner sc=new Scanner(System.in);
Employee()
{
System.out.println("enter the employee name");
ename=sc.next();
System.out.println("enter the employee id");
eid=sc.nextInt();
System.out.println("enter the address");
address=sc.next();
System.out.println("enter the mailid");
mailid=sc.next();
System.out.println("enter the mobileno");
mobileno=sc.nextLong();
}
}

(Programmer.java)
class Programmer extends Employee
{
double basic,hra,da,pf,stafffund,grosssalary,netsalary;
Programmer()
{
super();
System.out.println("enter the basic");
basic=sc.nextDouble();
}
void calculate()
{
da=0.97*basic;
hra=0.1*basic;
pf=0.12*basic;
stafffund=0.001*basic;
grosssalary=basic+da+hra;
netsalary=grosssalary-pf-stafffund;

void display()
{
System.out.println(" .................. ");
System.out.println("name "+ename);
System.out.println("id "+eid);

System.out.println("address "+address);
System.out.println("mailid "+mailid);
System.out.println("mobile "+mobileno);
System.out.println("da "+da);
System.out.println("hra "+hra);
System.out.println("pf "+pf);
System.out.println("stafffund "+stafffund);
System.out.println("grosssalary "+grosssalary);
System.out.println("netsalary "+netsalary);
System.out.println(" .................. ");
}
}

(Asstprof.java)
class Asstprof extends Employee
{
double basic,hra,da,pf,stafffund,grosssalary,netsalary;
Asstprof()
{
super();
System.out.println("enter the basic");
basic=sc.nextDouble();
}
void calculate()
{
da=0.97*basic;
hra=0.1*basic;
pf=0.12*basic;
stafffund=0.001*basic;
grosssalary=basic+da+hra;
netsalary=grosssalary-pf-stafffund;
}
void display()
{
System.out.println(" .................. ");
System.out.println("name "+ename);
System.out.println("id "+eid);
System.out.println("address "+address);
System.out.println("mailid "+mailid);
System.out.println("mobile "+mobileno);
System.out.println("da "+da);
System.out.println("hra "+hra);
System.out.println("pf "+pf);
System.out.println("stafffund "+stafffund);
System.out.println("grosssalary "+grosssalary);
System.out.println("netsalary "+netsalary);
System.out.println(" .................. ");
}
}

(Assoprof.java)
class Assoprof extends Employee
{
double basic,hra,da,pf,stafffund,grosssalary,netsalary;

Assoprof()
{
super();
System.out.println("enter the basic");
basic=sc.nextDouble();
}
void calculate()
{
da=0.97*basic;
hra=0.1*basic;
pf=0.12*basic;
stafffund=0.001*basic;
grosssalary=basic+da+hra;
netsalary=grosssalary-pf-stafffund;
}
void display()
{
System.out.println(" .................. ");
System.out.println("name "+ename);
System.out.println("id "+eid);
System.out.println("address "+address);
System.out.println("mailid "+mailid);
System.out.println("mobile "+mobileno);
System.out.println("da "+da);
System.out.println("hra "+hra);
System.out.println("pf "+pf);
System.out.println("stafffund "+stafffund);
System.out.println("grosssalary "+grosssalary);
System.out.println("netsalary "+netsalary);
System.out.println(" .................. ");
}
}

(Professor.java)
class Professor extends Employee
{
double basic,hra,da,pf,stafffund,grosssalary,netsalary;
Professor()
{
super();
System.out.println("enter the basic");
basic=sc.nextDouble();
}
void calculate()
{
da=0.97*basic;
hra=0.1*basic;
pf=0.12*basic;
stafffund=0.001*basic;
grosssalary=basic+da+hra;
netsalary=grosssalary-pf-stafffund;
}

void display()
{
System.out.println(" .................. ");
System.out.println("name "+ename);
System.out.println("id "+eid);
System.out.println("address "+address);
System.out.println("mailid "+mailid);
System.out.println("mobile "+mobileno);
System.out.println("da "+da);
System.out.println("hra "+hra);
System.out.println("pf "+pf);
System.out.println("stafffund "+stafffund);
System.out.println("grosssalary "+grosssalary);
System.out.println("netsalary "+netsalary);
System.out.println(" .................. ");
}
}

(EmployeepaySlipDemo.java)
class EmployeePaySlipDemo
{
public static void main (String m[])
{
Programmer obj=new Programmer();
obj.calculate();
obj.display();

Asstprof obj1=new Asstprof();


obj1.calculate();
obj1.display();

Assoprof obj2=new Assoprof();


obj2.calculate();
obj2.display();

Professor obj3=new Professor();


obj3.calculate();
obj3.display();
}
}
OUTPUT:
Programmer
enter the employee name
sunitha
enter the employee id
21326
enter the address
chennai
enter the mailid
[email protected]
enter the mobileno
97765656
enter the basic
20000
....................
name sunitha
id 21326
address chennai
mailid [email protected]
mobile 97765656
da 19400.0
hra 2000.0
pf 2400.0
stafffund 20.0
grosssalary 41400.0
netsalary 38980.0
....................
---------Assistant Professor--------
enter the employee name
Anand
enter the employee id
234541
enter the address
banglore
enter the mailid
[email protected]
enter the mobileno
7654654392
enter the basic
30000
....................
name Anand
id 234541
address banglore
mailid [email protected]
mobile 7654654392
da 29100.0
hra 3000.0
pf 3600.0
stafffund 30.0
grosssalary 62100.0
netsalary 58470.0
....................
---------Associate Professor--------
enter the employee name
priya
enter the employee id
23435
enter the address
pune
enter the mailid
[email protected]
enter the mobileno
876543678
enter the basic
25000
....................
name priya
id 23435
address pune
mailid [email protected]
mobile 876543678
da 24250.0
hra 2500.0
pf 3000.0
stafffund 25.0
grosssalary 51750.0
netsalary 48725.0
....................
---------Professor--------
enter the employee name
srinithi
enter the employee id
243576
enter the address
chennai
enter the mailid
[email protected]
enter the mobileno
6434567832
enter the basic
40000
....................
name srinithi
id 243576
address chennai
mailid [email protected]
mobile 6434567832
da 38800.0
hra 4000.0
pf 4800.0
stafffund 40.0
grosssalary 82800.0
netsalary 77960.0
4) Implementation of Abstract Class

AIM:

To write a java program to create an abstract class named shape and provide three classes named
rectangle ,triangle and circle such that each of the class extends the class shape.

ALGORITHM:

Step-0: Start the program


Step-1: Define the abstract class shape.
Step-2: Define the class rectangle with print Area() method that extend(make use of) shape.
Step-3: Define the class triangle with print Area() method that extend(make use of) shape.
Step-4: Define the class circle with print Area() method that extend(make use of) shape.
Step-5: Print the area of the rectangle, triangle and circle.
Step-6: stop the program

PROGRAM:

(Shapes.java)
public abstract class Shapes
{
double a,b;
abstract void printArea();
}

(Rectangle.java)
import java.util.*;
public class Rectangle extends Shapes
{
void printArea()
{
System.out.println("\t\t Claculating Area of Rectangle");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Length:");
a = sc.nextDouble();
System.out.println("Enter the Breadth:");
b = sc.nextDouble();
double area = a*b;
System.out.println("Area of Rectangle is:"+area);
}
}

(Triangle.java)

public class Triangle extends Shapes


{
void printArea()
{
System.out.println("\t\t Claculating Area of Triangle");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Height:");
a = sc.nextDouble();
System.out.println("Enter the Breadth:");
b = sc.nextDouble();
double area = 0.5*a*b;
System.out.println("Area of Triangle is:"+area);
}
}

(Circle.java)

public class Circle extends Shapes


{
void printArea()
{
System.out.println("\t\t Claculating Area of Circle");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Radius:");
a = sc.nextDouble(); double
area = 3.14*a*a;
System.out.println("Area of Circle is:"+area);
}
}

(AbstractClassDemo.java)
public class AbstractClassDemo
{
public static void main(String[] args)
{
Shapes obj;
System.out.println(“Implementation of Abstract classes”);
obj = new Rectangle();
obj.printArea();
obj = new Triangle();
obj.printArea();
obj = new Circle();
obj.printArea();
}
}
OUTPUT:

Implementation of Abstract Class


Claculating Area of Rectangle
Enter the Length:
10
Enter the Breadth:
20
Area of Rectangle is:200.0
Claculating Area of Triangle
Enter the Height:
30
Enter the Breadth:
25
Area of Triangle is:375.0
Claculating Area of Circle
Enter the Radius:
10
Area of Circle is:314.0
5) Implementation of Interface

AIM:

To design a java interface for ADT stack using array

ALGORITHM:

Step-0: Start the program


Step-1: Define the interface.
Step-2: Read the elements using array.
Step-3: Initialize stack top pointer as zero.
Step-4: Define and use the method push() to insert the elements into the stack with stack overflow
condition.
Step-5: Define and use the method pop() to remove an element from an array with stack underflow
condition.
Step-6: Display the output.
Step-7: stop the program

PROGRAM:

(myinterface.java)
interface myinterface
{
public void printArea();
}

(Shapes.java)
public abstract class Shapes
{
double a,b;
abstract void printArea();
}

(Rectangle.java)
import java.util.*;
public class Rectangle extends Shapes implements myinterface
{
void printArea()
{
System.out.println("\t\t Claculating Area of Rectangle");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Length:");
a = sc.nextDouble();
System.out.println("Enter the Breadth:");
b = sc.nextDouble();
double area = a*b;
System.out.println("Area of Rectangle is:"+area);
}
}
(Triangle.java)

public class Triangle extends Shapes implements myinterface


{
void printArea()
{
System.out.println("\t\t Claculating Area of Triangle");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Height:");
a = sc.nextDouble();
System.out.println("Enter the Breadth:");
b = sc.nextDouble();
double area = 0.5*a*b;
System.out.println("Area of Triangle is:"+area);
}
}

(Circle.java)

public class Circle extends Shapes implements myinterface


{
void printArea()
{
System.out.println("\t\t Claculating Area of Circle");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Radius:");
a = sc.nextDouble();
double area = 3.14*a*a;
System.out.println("Area of Circle is:"+area);
}
}

(AbstractClassDemo.java)
public class InterfaceDemo
{
public static void main(String[] args)
{
Shapes obj;
System.out.println(“Implementation of Interface”);
obj = new Rectangle();
obj.printArea();
obj = new Triangle();
obj.printArea();
obj = new Circle();
obj.printArea();
}
}
OUTPUT:
Implementation of Interface
Claculating Area of Rectangle
Enter the Length:
15
Enter the Breadth:
30
Area of Rectangle is:450.0
Claculating Area of Triangle
Enter the Height:
50
Enter the Breadth:
20
Area of Triangle is:500.0
Claculating Area of Circle
Enter the Radius:
48
Area of Circle is:7234.5599999999995
6 a) Implementation of Predefined Exception

AIM:

To write a java program to implement user predefined exception handling

ALGORITHM:

Step-0: Start the program


Step-1: Create an exception under the class predefined exception.
Step-2: Define a function that is main function to display the output message.
Step-3: In main() method class try() and catch() block are used to display the exception in the program.
Step-4: stop the program

PROGRAM:

(Predefinedexception.java)

import java.util.*;
public class PredefinedException
{
public static void main (String[] args)
{
int a,b,c;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value for divident:");
a = sc.nextInt();
System.out.println("Enter the the value for Divisor:");
b = sc.nextInt();
System.out.println("The value of a:"+a);
System.out.println("The value of b:"+b);
try
{
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println("Exception caught:"+e);
}

}
OUTPUT:

Enter the value for divident:


43
Enter the the value for Divisor:
0
The value of a:43
The value of b:0
Exception caught:java.lang.ArithmeticException: / by zero
6 b ) Implementation of User defined exception

AIM:

To write a java program to implement user defined exception handling

ALGORITHM:

Step-0: Start the program


Step-1: Create an exception under the class my exception
Step-2: In exception block, assign S1=S2
Step-3: Define a function string to String() to display the output message.
Step-4: In main() method class, try() and catch() blocks are used to display the exception in the
program.
Step-5: stop the program

Program:

(MyException.java)

class MyException extends Exception


{

int a;
MyException(int x)
{
a=x;
}
public String toString()
{
return "exception caught: The value is greater than 10:"+a;
}
static void compute (int n) throws MyException
{
if(n>10)
throw new MyException(n);
else
System.out.println(" The value is less than 10. Normal exit");
}
public static void main (String args[])
{
try
{
compute(1);
compute(20);
}
catch(MyException e)
{
System.out.println(e);
}
}

}
OUTPUT:

The value is less than 10. Normal exit


exception caught: The value is Greater than 10: 20
7. a) Implementation Displaying Information about a File

AIM:

To develop a java application for implementing a file to display information of file

ALGORITHM:

Step-0: Start the program


Step-1: Import the package java.io.*;
Step-2: Create a class file demo which has a main() method and main() method throws an exception.
Step-3: Inside main() method and name as a data members and get the inputs for frame and using buzz
word reader class.
Step-4: Check whether the file is existing or not using operations f.exist();”exist”:”not exist”.
Step-5: Display whether the file exist or not.
Step-6: check the condition if (f-exist()) then execute the following.
Step-7: Display the length of file bytes using if length()
Step-8: if(f.can write()) then file is writable else file is not writable.
Step-9: stop the program

PROGRAM:
(FileDemoOperation.java)
import java.io.*;
class FileDemoOperation
{
public static void main (String m[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the file name:");
String fname=br.readLine();
File f=new File(fname);
String result =f.exists()?"exist":"not exist";
System.out.println("The file "+result);
if(f.exists())
{
System.out.println("The Length of the file is "+f.length()+"bytes");
if(f.canRead())
System.out.println("The file is Readable");
else
System.out.println("The file is not Readable");
if(f.canWrite())
System.out.println("The file is Writeable");
else
System.out.println("The file is not Writable");
if(fname.endsWith(".txt"))
System.out.println("The file is text file");
if(fname.endsWith(".java"))
System.out.println("The file is java file");
if(fname.endsWith(".jpg"))
System.out.println("The file is image file");
}
}
}
OUTPUT:

Enter the File Name: FileDemoOperation.java


The File is Exist
The Length of the File is 845 Bytes
The file is readable
The file is writable
The File is java file
7 b) Implementation of Copying the content of one file to another file

AIM:

To develop a java program for copy the content of ine file into another file

ALGORITHM:

Step-0: Start the program


Step-1: Import the file as file Demo.java
Step-2: Import the package as java.io.*;
Step-3: Creating the main() class as file demo with main() method and it throws IO exception.
Step-4: To create file input stream as fin=new file Input stream(“input txt”);
Step-5: To create file output stream as fout=new file output stream(“output txt”);
Step-6: To read the value of c by using int c=file.read()
Step-7: Check while condition (cj= -1)
Step-8: To write the output by fout write(char(c)); method by c=read();
Step-9: To close input and output by file.close(), fout.close()
Step-10: stop the program

PROGRAM:

import java.io.*;
class FileDemo
{
public static void main (String args[ ])throws IOException
{
FileInputStream fin = new FileInputStream(“input.txt”);
FileOutputStream fout = new FileOutputStream(“output.txt”);
int c= fin.read();
while(c! = -1)
{
fout.write((char)c);
c = fin.read();
System.out.println(c);
}
fin.close( );
fout.close( );
}
}
OUTPUT:

Input File:(input.txt)

India is My Country. I love my country very much.

Output File:(output.txt)

India is My Country. I love my country very much.


8) Implementation of Multithreading

AIM:

To develop java program for implementation of multithreading

ALGORITHM:

Step-0: Start the program


Step-1: Import the package java.util.*;
Step-2: Create class thread one which extends the class thread.
Step-3: In the class thread one create and from random.
Step-4: Declare ’n’ as data members
Step-5: Create the method run() with public keywords
Step-6: In the try() block of method run()creat object for class thread one and thread three +2,+3 are
the objects.
Step-7: In the try() block used to computer (1) and compute (2)
Step-8: stop the program

PROGRAM:
(ThreadOne.java)
import java.util.*;
class ThreadOne extends Thread
{

Random rand=new Random();


int n;
public void run()
{
System.out.println(“First Thread is started….”);
try
{
ThreadTwo t2=new ThreadTwo();
ThreadThree t3=new ThreadThree();
for(int i=0;i<2;i++)
{
n=rand.nextInt(10);
System.out.println(“The Random Number Generated is:”+n);
if(n%2==0)
{
}
else
{

}
t2.setnum(n);
System.out.println(“Second Thread is started….”); t2.start();

System.out.println(“Third Thread is started….”); t3.setnum(n);


t3.start();
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(e);

}
}
}

(ThreadTwo.java)
class ThreadTwo extends Thread
{
int num;
void setnum(int num)
{
this.num=num;
}
public void run()
{
try
{
System.out.println(“The Random Number Generated is even:”+num
+” ” +”Its Square is”+(num*num));

Thread.sleep(100);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}

(ThreadThree.java)
class ThreadThree extends Thread
{
int num;
void setnum(int num)
{
this.num=num;
}
public void run()
{
try
{
System.out.println(“The Random Number Generated is odd:”+num +” “+”Its
Cube is:”+(num*num*num));
Thread.sleep(200);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}

(ThreadDemo.java)
class ThreadDemo
{
public static void main(String m[])
{
System.out.println(“Main Thread is started…”);
ThreadOne t1=new ThreadOne();
t1.start();
}
}
OUTPUT:

Main Thread is started


First Thread is started….
The Random Number Generated is :5
Third Thread is started…
The Random Number Generated is odd:5 Its Cube is:125
The Random Number Generated is even :6
Second Thread is started….
The Random Number Generated is even :6 Its Square is 36
9 a) Implementation of Generic Method

AIM:

To develop a java application for finding maximum value using a generic function.

ALGORITHM:

Step-0: Start the program


Step-1: Create a class generic methods text which has a main() method
Step-2: Get the input list by using a class integer,double and strong and display maximum value.
Step-3: Create method maximum() with closer extends comparable with an arguments and T list[]
and max as a data members of datatype.
Step-4: Inside a method maximum(),check over an entire list by using for loop and calculate as for(int
i=1,i< list.Length,i++)
Step-5: i element =list[i]
Step-6: Return the value of max
Step-7: stop the program

PROGRAM:

(GenericMethodDemo.java)

class GenericMethodDemo
{
public static <T extends Comparable<T>> T maximum(T list[ ])
{
T max;
max=list[0];
for(int i=1;i<list.length;i++)
{
T element=list[i];
if(element.compareTo(max)>0)
max=element;
}
return(max);
}
public static void main(String m[])
{
Integer a[]={10,20,30,54,75,32,98,87};
Double b[]={23.45,67.89,4.2,3.76};
String c[]={"Priya","Nancy"};
System.out.println("Demonstration of Generic Method ... ");
System.out.println("The Maximum of Integer elements is:"+maximum(a));
System.out.println("The Maximum of Floating point elements is:”
+maximum(b));
System.out.println("The Maximum of String elements is:"+maximum(c));
} }
}
OUTPUT:

Demonstration of Generic Method....

The Maximum of Integer elements is: 98


The Maximum of Floating point elements is: 67.89
The Maximum of String elements is: Priya
9 b) Implementation of Generic Class

AIM:

To write a java program that implements generic class

ALGORITHM:

Step-0: Start the program


Step-1: Create a generic type declaration code “public class generic into generic class Arr<T>”
Step-2: Introduce the type variable T that can be used anywhere inside the class.
Step-3: Generic enable types(classes and interfaces) to be parameters when defining classes, interfaces
and methods.
Step-4: stop the program

PROGRAM:

(GenericClassArr.java)

import java.util.*;
public class GenericClassArr<T>
{
public ArrayList <T> obj;
public GenericClassArr(int size)
{
obj = new ArrayList<T>(size);
}
public void insert(int index, T item)
{
obj.add(index,item);
}
public void display()
{
System.out.println(" " +obj);
}
public T del(int index)
{
return obj.remove(index);
}
}
(GenericClassDemo.java)
public class GenericClassDemo
{
public static void main(String[] args)
{
int[] iArray = {3,5,7,8,54};
GenericClassArr <Integer> iobj = new GenericClassArr <Integer>(10);
int i,index;
System.out.println("Array of Integers is .... ");
for(i=0;i<5;i++)
iobj.insert(i,iArray[i]);
iobj.display();
System.out.println("Inserting the Elemetns in Integer Array");
System.out.println("Enter the Element to be inserted:");
Scanner sc= new Scanner(System.in);
int item = sc.nextInt();
System.out.println("Enter the index at which the element to be inserted:");
index = sc.nextInt();
iobj.insert(index,item);
System.out.println(“The integer array after inserting is:”+iobj.display());
System.out.println("Enter the index of the Element to be deleted:");
index = sc.nextInt();
iobj.del(index);
System.out.println(“The integer array after deletion is:”+iobj.display());
double[] dArray = {11.11,22.22,33.33,44.44,55.55};
GenericClassArr<Double> dobj = new GenericClassArr<Double>(10);
System.out.println("Array of Doubles is .... ");
for(i=0;i<5;i++)
dobj.insert(i,dArray[i]);
dobj.display();
System.out.println("Inserting the Elemetns in Double Array");
System.out.println("Enter the Element to be inserted:");
double ditem = sc.nextDouble();
System.out.println("Enter the index at which the element to be inserted:");
index = sc.nextInt();
dobj.insert(index,ditem);
System.out.println(“The double array after inserting is:”+dobj.display());
System.out.println("Enter the index of the Element to be deleted:");
index = sc.nextInt();
dobj.del(index);
System.out.println(“The double array after deletion is:”+dobj.display());
}

}
OUTPUT:

Array of Integers is.....


[3, 5, 7, 8, 54]

Inserting the Elements in Integer Array….

Enter the Element to be inserted:


85
Enter the index at which the element to be inserted:
2

The Integer array after insertion is:


[3, 5, 85, 7, 8, 54]

Enter the index of the Element to be deleted:


4

The Integer array after Deletion is:


[3, 5, 85, 7, 54]

Array of Doubles is.....


[11.11, 22.22, 33.33, 44.44, 55.55]

Inserting the Elemetns in Double Array…….

Enter the Element to be inserted:


66.66
Enter the index at which the element to be inserted:
5

The Double array after insertion is:

[11.11, 22.22, 33.33, 44.44, 55.55, 66.66]

Enter the index of the Element to be deleted:


1

The Double array after deletion is:


[11.11, 33.33, 44.44, 55.55, 66.66]
10 a)Implementation of JavaFX Controls

AIM:

To develop a java program for javaFx Controls

ALGORITHM:

Step-0: Start the program


Step-1: Extend javafx.application and Override start()
Step-2: Create label,textfield,text area,radio button,xhexk box,choice box and button.
Step-3: Create layout and add the controls to it.
Step-4: Create scene and add the scene to stage
Step-5: Using stage object declare SetTitle,SetScsne,SetShow.
Step-6: Declare main class
Step-7: Stop the program.

PROGRAM:

(ControlsDemo.java)
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class ControlsDemo extends Application
{
public void start(Stage ps)
{
Label l1=new Label("Name");
TextField t1= new TextField();
Label l2=new Label("Register number");
TextField t2= new TextField();
Label l3=new Label("Age");
TextField t3= new TextField();
Label l4=new Label("Address");
TextArea t4= new TextArea();
t4.setPrefHeight(100);
t4.setPrefWidth(100);
Label l5=new Label("Gender");
RadioButton rb1= new RadioButton("Male");
RadioButton rb2= new RadioButton("Female");
Label l6=new Label("Hobbies");
CheckBox cb1= new CheckBox("Watching TV");
CheckBox cb2= new CheckBox("Reading Books");
CheckBox cb3= new CheckBox("Palying");
CheckBox cb4= new CheckBox("Lisening Music");
Label l7=new Label("Country");
ChoiceBox chb1= new ChoiceBox();
chb1.getItems().add("America");
chb1.getItems().add("Cannada");
chb1.getItems().add("India");
chb1.getItems().add("Russia");
Button btn = new Button();
btn.setText("Submit");
btn.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
System.out.println("Controls Demo!");
System.out.println("The Name is:"+t1.getText());
System.out.println("The Register Number is:"+t2.getText());
System.out.println("The Age is:"+t3.getText());
System.out.println("The Address is:"+t4.getText());
System.out.println("The Country is:"+chb1.getValue());
}
});
GridPane root= new GridPane();
root.addRow(0,l1,t1);
root.addRow(1,l2,t2);
root.addRow(2,l3,t3);
root.addRow(3,l4,t4);
root.addRow(4,l5,rb1,rb2);
root.addRow(5,l6,cb1,cb2,cb3,cb4);
root.addRow(6,l7,chb1);
root.addRow(7,btn);
Scene scene = new Scene(root, 300, 250);
ps.setTitle("Controls Demo");
ps.setScene(scene);
ps.show();
}
public static void main(String[] args)
{
launch(args);
}
}
OUTPUT:
10 b) Implementation of JavaFX layouts

AIM:

To develop a java application for JavaFx Layouts


ALGORITHM:

Step-0: Start the program


Step-1: Extend java.fx.application.Application and Override Start()
Streat-2: Create a Layout flowpane
Step-3: Creates a Button
Step-4: Add the button to the flowpane Object
Step-5: Create the scene
Step-6: Using the stage object set PS.SetTitle(),PS.SetSum(),PS.SetShow()
Step-7: Declare the main() class
Step-8: stop the program

PROGRAM:
(FlowPaneLayoutDemo.java)
mport javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*
public class FlowPaneLayoutDemo extends Application
{
public void start(Stage ps)
{
FlowPane root = new FlowPane();
Button b1 = new Button("ONE");
Button b2 = new Button("TWO");
Button b3 = new Button("THREE");
Button b4 = new Button("FOUR");
Button b5 = new Button("FIVE");
Button b6 = new Button("SIX");
root.getChildren().addAll(b1,b2,b3,b4,b5,b6);
Scene scene = new Scene(root, 300, 250);
ps.setTitle("LayoutDEmo");
ps.setScene(scene);
ps.show();
}
public static void main(String[] args)
{
launch(args);
}
}
OUTPUT:
10 c) Implementation of Menus

AIM:

To develop the java application to implement the menus

ALGORITHM:

Step-0: Start the program


Step-1: Extend javafx.application .Application
Step-2: Create menubar
Step-3: Create menus and create menu item for menus
Step-4: Add menubar to border layout
Step-5: Create Scene and using stage object and set title, scene and show.
Step-6: Declare the main() class
Step-7: Stop the program

PROGRAM:
(MenusDemo.java)
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class MenusDemo extends Application
{
public void start(Stage primaryStage)
{
// creating Menu Bar
MenuBar mbar = new MenuBar();
// Creating Three Menus
Menu fmenu = new Menu("File");
Menu emenu = new Menu("Edit");
Menu hmenu = new Menu("Help");
//Creating Menu Items for File menu
MenuItem newItem = new MenuItem("New");
MenuItem openItem = new MenuItem("Open File");
MenuItem saveItem = new MenuItem("Save");
MenuItem exitItem = new MenuItem("Exit");
// Creating Menu Items for Edit menu
MenuItem cutItem = new MenuItem("Cut");
MenuItem copyItem = new MenuItem("Copy");
MenuItem pasteItem = new MenuItem("Paste");
// Adding MenuItems to the Menus
fmenu.getItems().addAll(newItem,openItem,saveItem,exitItem);
emenu.getItems().addAll(cutItem,copyItem,pasteItem);
// Adding Menus to the Menu bar
mbar.getMenus().addAll(fmenu,emenu,hmenu);
BorderPane root = new BorderPane();
//Adding Menu Bar to the Border Layout
root.setTop(mbar);
Scene scene = new Scene(root, 400, 300);
primaryStage.setTitle("JavaFX Menus Demo");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
OUTPUT:
MINI PROJECT - OPAC SYSTEM

AIM:

To develop a mini project OPAC system for library using Java concepts.

ALGORITHM:

1. Import the awt,swing packages.


2. Extend the JFrame which implements actionlistener to the class datas.
3. Create the textfield for id, name and button for next, address and the panel.
4. Create object for the getcontentpane().
5. Assign the length and breadth value for the layout using gridlayout.
6. Add the new labels for ISBN and book name.
7. Add the new button for the nextbook
8. Create the bookname under the driver jdbc odbc driver in the try block.
9. Create the object for exception as e and use it for catching the error.
10. Show all the records using showrecord.

PROGRAM:

//File Name should be Data.java

import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Data extends JFrame implements ActionListener
{
JTextField id;
JTextField name;
JButton next;
JButton addnew;
JPanel p;
static ResultSet res;
static Connection conn;
static Statement stat;
public Data()
{
super("My Application");
Container c = getContentPane();
c.setLayout(new GridLayout(5,1));

id = new JTextField(20);
name = new JTextField(20);
next = new JButton("Next BOOK");
p = new JPanel();

c.add(new JLabel("ISBN Number",JLabel.CENTER));


c.add(id);
c.add(new JLabel("Book Name",JLabel.CENTER));
c.add(name);
c.add(p);

p.add(next);
next.addActionListener(this);
pack();
setVisible(true);
addWindowListener(new WIN());
}

public static void main(String args[])


{
Data d = new Data();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:stu");
// cust is the DSN Name
stat = conn.createStatement();
res = stat.executeQuery("Select * from stu"); // stu is the table name
res.next();
}
catch(Exception e)
{
System.out.println("Error" +e);
}
d.showRecord(res);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == next)
{
try
{
res.next();
}
catch(Exception e)
{
}
showRecord(res);
}
}
public void showRecord(ResultSet res)
{
try
{
id.setText(res.getString(2));
name.setText(res.getString(3));
}
catch(Exception e)
{
}
}//end of the main

//Inner class WIN implemented


class WIN extends WindowAdapter
{
public void windowClosing(WindowEvent w)
{
JOptionPane jop = new JOptionPane();
jop.showMessageDialog(null,"Thank you","My
Application",JOptionPane.QUESTION_MESSAGE);
}
}
}

NOTE:
Create a new Database
1. Create a new Database file in MS ACCESS (our backend) named “books.mdb”.
2. Then create a table named “stu” in it.
3. The table stu contains the following fields and data types
i. ISBN - Text
ii. BookName - Text
4. Enter various records as you wish.
5. Save the database file.

Next step is to add our “books.mdb” to the System DSN. To do that follows the procedure
given below,
i. Go to Start-> Control Panel -> Administrative tools.
ii. In that double click “Data Sources (ODBC)”.
iii. ODBC Data Source Administrator dialog appears.
iv. In that select “System DSN” tab and click the Add Button.
v. Select “Microsoft Access Driver(*.mdb)” and click Finish.
vi. ODBC Microsoft Access Setup appears. In the “Data Source name” type “stu”.
vii. Click on the “Select” button and choose your database file. Then click ok.

Now your database file gets added to the System DSN.


Table: Design View

Table Name: stu


Administrative Tools.

ODBC Data Source Administrator


Creating Microsoft Access Driver(*.mdb)

ODBC Microsoft Access Setup


OUTPUT:

To Compile:
javac Data.java
To Run:
java Data
RESULT:

Thus the program to develop the simple OPAC for the libraries is executed
successfully.

You might also like