0% found this document useful (0 votes)
3 views60 pages

oops final doc

The document outlines the Object Oriented Programming Laboratory course at Arunai Engineering College, detailing various experiments including sequential and binary search algorithms, sorting techniques, and data structures like stacks and queues. Each experiment includes an aim, algorithm, Java program, output, and result, demonstrating the successful execution of the programs. The document serves as a practical guide for students in the Cyber Security branch during their second year of study.
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)
3 views60 pages

oops final doc

The document outlines the Object Oriented Programming Laboratory course at Arunai Engineering College, detailing various experiments including sequential and binary search algorithms, sorting techniques, and data structures like stacks and queues. Each experiment includes an aim, algorithm, Java program, output, and result, demonstrating the successful execution of the programs. The document serves as a practical guide for students in the Cyber Security branch during their second year of study.
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/ 60

5104-ARUNAI

ARUNAI ENGINEERING COLLEGE

TIRUVANNAMALAI

(affiliated to Anna University)

Velu Nagar,Tiruvannamalai
Nagar,Tiruvannamalai-606603

www.arunai.org

Department of Computer Science And Engineering

(Cyber Security)

REGULATION 2021

SECOND YEAR (Third Semester)

CS3381-OBJECT
OBJECT ORIENTED PROGRAMMING LABORATORY

ACADEMIC YEAR:2023
YEAR:2023-2024(ODD SEMESTER)
ARUNAI ENGINEERING COLLLEGE
TIRUVANNAMALAI
TIRUVANNAMALAI-606 603

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

(CYBER SECURITY)
Certified that this is a bonafide record of work done by

Name :

University Reg:No :

Semester :

Branch :

Year :

Staff-in-charge Head of the Department

Submitted for the CS3381--OBJECT ORIENTED PROGRAMMING LABORATORY

Practical Examination held on

Internal Examiner External Examiner


S.NO DATE NAME OF EXPERIMENT PAGE REMARKS
NO
1

EX NO:1a

Solve problems by using sequential search


DATE:

AIM:
To write a java program to develop a Java application to solve sequential search

ALGORITHM:

1. Start.
2. Traverse the array
3. Match the key element with array element
4. If key element is found, return the index position of the array element
5. If key element is not found, return -1
6. End.
2
PROGRAM:

import java.util.Scanner;
public class LinearSearchExample
{
public static int linearSearch(int[] arr, int key)
{
for(int i=0;i<arr.length;i++)
{
if(arr[i] == key)
{
return i;
}
}
return -1;
}
public static void main(String a[])
{
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}
3

OUTPUT:

50 is found at index: 3

RESULT

Thus the java application program to solve searching has been executed successfully.
4

EX NO:1b

Solve problems by using binary search


DATE:

AIM:
To write a java program to develop a Java application to solve binary search.

ALGORITHM:

1. Take four variables => start, end, middle, target.


2. Find the middle element of an array => now your array is divided into two parts
3. left and right.3.If target element > middle element => search in right part.
4. If target element < middle element => search in left part.
5. If middle element == target element => return that element.
6. If start > end => element not found.
5

PROGRAM:

public class BinarySearchExample


{
public static void binarySearch(int arr[], int first, int last, int key)
{
int mid = (first + last)/2;while( first <= last )
{
if ( arr[mid] < key )
{
first = mid + 1;
}
else if ( arr[mid] == key )
{
System.out.println("Element is found at index: " + mid);break;
}
else
{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){ System.out.println("Element is not found!");
}
}
public static void main(String args[]){int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1; binarySearch(arr,0,last,key);
}}
6
OUTPUT:

Element is found at index: 2

RESULT:

Thus the java application program to solve searching has been executed successfully.
7

EX N O : 1 c
Solve problems by using quadratic sorting algorithms( insertion)
DATE:

AIM:
To write a java program to develop a Java application to solve quadratic sorting algorithms.

ALGORITHM:

1. Start.
2. Repeat steps 2 to 4 till the array end is reached.
3. Compare the element at current index i with its predecessor. If it is smaller, repeat step 3.
4. 4.Keep shifting elements from the “sorted” section of the array till the correct location the key
is found
5. Increment loop variable.
6. End.
8
PROGRAM:

public class InsertionSortExample


{
public static void insertionSort(int array[])
{
int n = array.length;
for (int j = 1; j < n; j++) {int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) )
{
array [i+1] = array [i];i--;
}
array[i+1] = key;
}
}
public static void main(String a[]){int[] arr1 = {7,19,3,2,43,11,58,22};
System.out.println("Before Insertion Sort");for(int i:arr1)
{
System.out.print(i+" ");
}
System.out.println();
insertionSort(arr1);//sorting array using insertion sortSystem.out.println("After Insertion Sort");
for(int i:arr1)
{
System.out.print(i+" ");
}
}
}
9
OUTPUT:

Before Insertion Sort


7 19 3 2 43 11 58 22
After Insertion Sort
2 3 7 11 19 22 43 5

RESULT:

Thus the java application program to sorting techniques has been executed successfully.
.
10

EX NO;1d Solve problems by using quadratic sorting


algorithms( selection )
DATE:

AIM:
To write a java program to develop a Java application to solve quadratic sorting algorithms.

ALGORITHM:

1. Start.
2. Run two loops: an inner loop and an outer loop.
3. Repeat steps till the minimum element are found.
4. Mark the element marked by the outer loop variable as a minimum.
5. If the current element in the inner loop is smaller than the marked minimum element, change the value of
the minimum element to the current element.
6. Swap the value of the minimum element with the element marked by the outer loop variable.
7.End.
11
PROGRAM:

public class SelectionSortExample


{
public static void selectionSort(int[] arr)
{
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] < arr[index])
{
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
public static void main(String a[])
{
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");for(int i:arr1)
{ System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);//sorting array using selection sortSystem.out.println("After Selection
Sort");
for(int i:arr1){ System.out.print(i+" ");
}
}
}
12

OUTPUT:

Before Selection Sort


9 14 3 2 43 11 58 22
After Selection Sort
2 3 9 11 14 22 43 5

RESULT:

Thus the java application program to sorting techniques has been executed

successfully.
13
.

EX NO 2A
Develop stack data structures using classes and objects.
DATE

AIM:
To develop a Java application to implement stack and queue data structures using classes and
objects.

ALGORITHM:
Stack :
1. Start the program.
2. Push inserts an item at the top of the stack (i.e., above its current top element).
3. Pop removes the object at the top of the stack and returns that object from the function.
4. The stack size will be decremented by one.
5. isEmpty tests if the stack is empty or not.
6. isFull tests if the stack is full or not.
7. Peek returns the object at the top of the stack without removing it from the stack or modifying the stackin
any way.
8. Size returns the total number of elements present in the stack.
9. Stop the program.
14
PROGRAM:

// Java code for stack implementation


import java.io.*;
import java.util.*;
class Test
{
// Pushing element on the top of the stack
static void stack_push(Stack<Integer> stack)
{
for(int i = 0; i < 5; i++)
{
stack.push(i);
}
}
// Popping element from the top of the stack
static void stack_pop(Stack<Integer> stack)
{
System.out.println("Pop Operation:");
for(int i = 0; i < 5; i++)
{
Integer y = (Integer) stack.pop();
System.out.println(y);
}
}
// Displaying element on the top of the stack
static void stack_peek(Stack<Integer> stack)
{
Integer element = (Integer) stack.peek();
System.out.println("Element on stack top: " + element);
}
// Searching element in the stack
static void stack_search(Stack<Integer> stack, int element)
{
Integer pos = (Integer) stack.search(element);
if(pos == -1)
System.out.println("Element not found");
else
System.out.println("Element is found at position: " + pos);
}
public static void main (String[] args)
{
Stack<Integer> stack = new Stack<Integer>();
15

stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
}
}
16

OUTPUT:

Pop Operation:

2
1

0
Element on stack top: 4

Element is found at position: 3

Element not found

RESULT:

Thus the java application program to sorting techniques has been executed

successfully.
17

EX 2B

Develop queue data structures using classes and objects


DATE:

AIM:

To develop a Java application to implement tqueue data structures using classes and objects.]

ALGORITHM:
Queue:

Enqueue Operation
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.
Dequeue Operation
Step 1 − Check if the queue is empty.
Step 2 − If the queue is empty, produce underflow error and exit.
Step 3 − If the queue is not empty, access the data where front is
pointing

Step 4 − Increment front pointer to point to the next available data

Step 5 − Return success.


18
PROGRAM:
// implementation of queue
// A class to represent a queue
class Queue
{
int front, rear, size;
int capacity;
int array[];
public Queue(int capacity)
{
this.capacity = capacity;
front = this.size = 0;
rear = capacity - 1;
array = new int[this.capacity];
}
// Queue is full when size becomes
// equal to the capacity
boolean isFull(Queue queue)
{
return (queue.size == queue.capacity);
}
// Queue is empty when size is 0
boolean isEmpty(Queue queue)
{
return (queue.size == 0);
}
// Method to add an item to the queue.
// It changes rear and size
void enqueue(int item)
{
this.size = this.size + 1;
19

if (isFull(this))
return;
this.rear = (this.rear + 1)% this.capacity;
this.array[this.rear] = item;

System.out.println(item + " enqueued to queue");


}
// Method to remove an item from queue.
// It changes front and size
int dequeue()
{
if (isEmpty(this))
return Integer.MIN_VALUE;
int item = this.array[this.front];
this.front = (this.front + 1)% this.capacity;
this.size = this.size - 1;
return item;
}
// Method to get front of queue
int front()
{
if (isEmpty(this))
return Integer.MIN_VALUE;
return this.array[this.front];
}
// Method to get rear of queue
int rear()
{
if (isEmpty(this))
return Integer.MIN_VALUE;
return this.array[this.rear];
}
}
// Driver class
public class Test
20
{
public static void main(String[] args)
{
Queue queue = new Queue(1000);
queue.enqueue(10);
queue.enqueue(20);

queue.enqueue(30);
queue.enqueue(40);
System.out.println(queue.dequeue() + " dequeued from queue\n");
System.out.println("Front item is "+ queue.front());
System.out.println("Rear item is " + queue.rear());
}
}
21

OUTPUT:
10 enqueued to queue

20 enqueued to queue

30 enqueued to queue

40 enqueued to queue

10 dequeued from

queueFront item is 20

Rear item is 40

RESULT:

Thus the java application to implement stack and queue data structures using classes and
objects has been done successfully.
22

EX NO 3

Develop a java application with Employee class


DATE:

AIM:
To develop a java application to generate pay slip for different category of employees
using the concept of 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.
Create the objects for the inherited classes and invoke the necessary methods to display the Payslip
23

PROGRAM :
import java.util.*;
class employee
{
int empid;
long mobile;
String name, address, mailid;
Scanner get = new Scanner(System.in);
void getdata()
{
System.out.println("Enter Name of the
Employee:");name = get.nextLine();
System.out.println("Enter Mail id:");
mailid = get.nextLine();
System.out.println("Enter Address of the Employee:");
address = get.nextLine();
System.out.println("Enter employee id :");
empid = get.nextInt();
System.out.println("Enter Mobile Number:");
mobile = get.nextLong();

void display()
{
System.out.println("Employee Name: "+name);
System.out.println("Employee id : "+empid);
System.out.println("Mail id : "+mailid);
System.out.println("Address: "+address);
System.out.println("Mobile Number: "+mobile);
}
}
class programmer extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getprogrammer()
{
System.out.println("Enter basic pay:");
bp = get.nextDouble();
}
void calculateprog()
{
da=(0.97*bp);
hra=(0.10*bp);
24
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR PROGRAMMER");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("PF:Rs"+pf);
System.out.println("HRA:Rs"+hra);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class asstprofessor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getasst()
{
System.out.println("Enter basic pay:");
bp = get.nextDouble();
}
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);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR ASSISTANT PROFESSOR");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
25
}
class associateprofessor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getassociate()
{
System.out.println("Enter basic pay:");
bp = get.nextDouble();
}
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);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR ASSOCIATE PROFESSOR");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}

}
class professor extends employee
{
double salary,bp,da,hra,pf,club,net,gross;
void getprofessor()
{
System.out.println("Enter basic pay:");
bp = get.nextDouble();
}
void calculateprofessor()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
26
net=(gross-pf-club);
System.out.println("************************************************");
System.out.println("PAY SLIP FOR PROFESSOR");
System.out.println("************************************************");
System.out.println("Basic Pay:Rs"+bp);
System.out.println("DA:Rs"+da);
System.out.println("HRA:Rs"+hra);
System.out.println("PF:Rs"+pf);
System.out.println("CLUB:Rs"+club);
System.out.println("GROSS PAY:Rs"+gross);
System.out.println("NET PAY:Rs"+net);
}
}
class salary
{
public static void main(String args[])
{
int choice,cont;
do
{
System.out.println("PAYROLL");
System.out.println(" 1.PROGRAMMER \t 2.ASSISTANT PROFESSOR \t 3.ASSOCIATE PROFESSOR
\t 4.PROFESSOR ");
Scanner c = new Scanner(System.in);
System.out.print(“Enter your choice:”);
choice=c.nextInt();
switch(choice)
{
case 1:
{

programmer p=new programmer();


p.getdata();
p.getprogrammer();
p.display();
p.calculateprog();
break;
}

case 2:
{
asstprofessor asst=new asstprofessor();
asst.getdata();
asst.getasst();
27
asst.display();
asst.calculateasst();
break;
}
case 3:
{
associateprofessor asso=new associateprofessor();
asso.getdata();
asso.getassociate();
asso.display();
asso.calculateassociate();
break;
}
case 4:
{
professor prof=new professor();
prof.getdata();
prof.getprofessor();
prof.display();
prof.calculateprofessor();
break;
}
}
System.out.println("Please enter to continue 0 to quit and 1 to continue
");cont=c.nextInt();
}while(cont==1);
}
}
28

OUTPUT:

PAYROLL
1.PROGRAMMER 2.ASSISTANT PROFESSOR 3.ASSOCIATE PROFESSO
4. PROFESSOR
Enter your choice: 2
Enter Name of the Employee: ARUN.k
Enter Mail id: [email protected]
Enter Address of the Employee: 12,Anna
Nagar,chennai-65Enter employee id: 5002
Enter Mobile Number: 9876543210
Enter basic pay: 20000
Employee Name:
ARUN.k
Employee id :
5002
Mail id : [email protected]
Address: 12,Anna Nagar,chennai-65
Mobile Number: 9876543210
******************************************
****** PAY SLIP FOR ASSISTANT
PROFESSOR
************************************************
Basic Pay:Rs20000.0
DA:Rs19400.0
HRA:Rs2000.0
PF:Rs2400.0
CLUB:Rs2000.
0 GROSS
PAY:Rs41400.0
NET
PAY:Rs37000.
0
Please enter to continue 0 to quit and 1 to continue

Result:
Thus the java application to generate pay slip for different category of employees was implementedusing
inheritance and the program was executed successfully
29

EX NO 4

Write a java program to create an abstract class


DATE:

AIM:
To write a java program to create an abstract class named Shape that contains two integers and
an empty method named print Area. Provide three classes named Rectangle, Triangle and Circle such
that each one of the classes extends the class Shape. Each one of the classes contain only the method
print Area() that prints the area of the given shape

ALGORITHM:
1. Start the program
2. Define the abstract class shape.
3. Define the class Rectangle with PrintArea() method that extends(makes use of) Shape.
4. Define the class Triangle with PrintArea() method that extends(makes use of) Shape.
5. Define the class Circle with PrintArea() method that extends(makes use of) Shape.
6. Print the area of the Rectangle,Triangle and Circle .
7. Stop the Program.
30

PROGRAM:
import java.util.*;
abstract class Shapes
{
double a,b;
abstract void printArea();
}
class Rectangle extends Shapes
{
void printArea()
{
System.out.println("\t\t Calculating Area of Rectangle");
Scanner input =new Scanner(System.in);
System.out.println("\n Enter length:");
a=input.nextDouble();

System.out.println("\n Enter breadth:");


b= input.nextDouble();
double area=a*b;
System.out.println("Area of Rectangle is:"+area);
}
}
class Triangle extends Shapes
{
void printArea()
{
System.out.println("\t\t Calculating Area of Triangle");
Scanner input =new Scanner(System.in);
System.out.println("\n Enter height:");
a=input.nextDouble();
System.out.println("\n Enter breadth:");
b= input.nextDouble();
double area=0.5*a*b;
System.out.println("Area of Triangle is:"+area);
31
}
}
class Circle extends Shapes
{
void printArea()
{
System.out.println("\t\t Calculating Area of Circle");
Scanner input =new Scanner(System.in);
System.out.println("\n Enter radius:");
a=input.nextDouble();
double area=3.14*a*a;
System.out.println("Area of Circle is:"+area);
}
}
class AbstractclassDemo
{
public static void main(String[] args)
{
Shapes obj;
obj=new Rectangle();
obj.printArea();
obj=new Triangle();
obj.printArea();
obj=new Circle();
obj.printArea();
}
}
32

OUTPUT:
Calculating Area of Rectangle
Enter length: 10
Enter breadth: 20
Area of Rectangle is:200.0
Calculating Area of Triangle
Enter height: 30
Enter breadth: 25
Area of Triangle is:375.0
Calculating Area of Circle
Enter radius: 10
Area of Circle is:314.0

Result:
Thus the java application program to create an abstract class named shape that contains two integers
hasverified successfully
33

EX NO 5

DATE: Write a java program to create interface

AIM:
To write a java program to calculate the area of rectangle, circle and triangle using the concept of
interface.

ALGORITHM:

1. Create an 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 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.
34

PROGRAM:
import java.util.*;
interface Myinterface //defining interface
{
public void printArea();
}
abstract class Shapes
{
double a,b;
abstract void printArea();
}
class Rectangle extends Shapes implements Myinterface // using interface
{
public void printArea()
{
System.out.println("\t\t Calculating Area of Rectangle");
Scanner input =new Scanner(System.in);
System.out.println("\n Enter length:");
a=input.nextDouble();
System.out.println("\n Enter breadth:");
b= input.nextDouble();
double area=a*b;
System.out.println("Area of Rectangle is:"+area);

}
}
class Triangle extends Shapes implements Myinterface
{
public void printArea()
{
System.out.println("\t\t Calculating Area of Triangle");
Scanner input =new Scanner(System.in);
System.out.println("\n Enter height:");
a=input.nextDouble();
System.out.println("\n Enter breadth:");
b= input.nextDouble();
double area=0.5*a*b;
System.out.println("Area of Triangle is:"+area);
}
}
class Circle extends Shapes implements Myinterface
{
public void printArea()
{
35
System.out.println("\t\t Calculating Area of Circle:");
Scanner input =new Scanner(System.in);
System.out.println("\n Enter radius:");
a=input.nextDouble();
double area=3.14*a*a;
System.out.println("Area of Circle is:"+area);
}
}
class AbstractclassDemo
{
public static void main(String[] args)
{
Shapes obj;
obj=new Rectangle();
obj.printArea();
obj=new Triangle();
obj.printArea();
obj=new Circle();
obj.printArea();
}
36

OUTPUT:
Calculating Area of Rectangle
Enter length: 10
Enter breadth: 20
Area of Rectangle is:200.0
Calculating Area of Triangle
Enter height: 10
Enter breadth: 5
Area of Triangle is:25.0
Calculating Area of Circle:
Enter radius: 10
Area of Circle is:314.0

Result:
Thus the java application program to create an abstract class named shape that contains twointegers
has verified successfully.
37

EX NO 6

DATE: Write a Java program to implement user defined exception


handling

AIM:
To write a Java program to implement user defined exception handling.

ALGORITHM:

1. Start the program


2. Define the exception for getting a number from the user.
3. If the number is positive print the number as such.
4. If the number is negative throw the exception to the user as ‘Number must be positive’.
5. Stop the Program
38

PROGRAM:
import java.io.*;
class MyException extends Exception
{
public MyException(String s)
{
super(s);
}
}
public class Main
{
public static void main(String args[])
{
int no;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.println("Enter a positive number:");
no=Integer.parseInt(b.readLine());
if(no<0)
{
throw new MyException("exception occurred");

}
else
{
System.out.println("Number"+ no);
}
}
catch(MyException ex)
{
System.out.println("Caught");
System.out.println(ex.getMessage());
}
39
catch(Exception e)
{}
}
}
40

OUTPUT:
Enter a positive number:
-10
Caught
exception occurred

Result:
Thus the java application program to implement user defined exception handling has been

executed successfully.
41

EX NO 7

Write a java program that implements a multi –thread


DATE:
application

AIM:
To write a java program that implements a multi –thread application that has three threads .First
thread generates random integer every 1 second and if the value is even ,second thread computes
thesquare f the integer and prints. If the value is odd ,the third threat will print the value of cube of the
number

ALGORITHM:
1. Start the program

2. Design the first thread that generates a random integer for every 1 second .

3. If the first thread value is even, design the second thread as the square of the number and then printit.

4. If the first thread value is odd, then third thread will print the value of cube of the number.

5. Stop the program.


42

PROGRAM:
import java.util.*;
class even implements Runnable
{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN and Square of " + x + " is: " + x * x);
}
}
class odd implements Runnable
{
public int x;

public odd(int x)
{
this.x = x;
}
public void run()
{
System.out.println("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
43
{
for (int i = 0; i < 5; i++)
{
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " +
num);if (num % 2 == 0)
{
Thread t1 = new Thread(new even(num));
t1.start();
} else {
Thread t2 = new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println(" ");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public class threadexample
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}
44

OUTPUT:

Main Thread and Generated Number is 10


New Thread 10 is EVEN and Square of 10 is: 100
--------------------------------------
Main Thread and Generated Number is 14
New Thread 14 is EVEN and Square of 14 is: 196
--------------------------------------
Main Thread and Generated Number is 83
New Thread 83 is ODD and Cube of 83 is: 571787
--------------------------------------
Main Thread and Generated Number is 1
New Thread 1 is ODD and Cube of 1 is: 1
--------------------------------------
Main Thread and Generated Number is 20
New Thread 20 is EVEN and Square of 20 is: 400

Result:

Thus the java application to implement multithread application has been executed successfully
45

EX NO 8

Write a Java program that reads a file


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. Start the program

2. Read the filename from the user.

3. Use getName() Method to display the filename.

4,Use getPath() Method to display the path of the file.


5. Use getParent() Method to display its parent’s information.

6. Use exists() Method to display whether the file exist or not

7. Use isFile() and isDirectory() Methods to display whether the file is file or directory.

8. Use canRead() and canWrite) methods to display whether the file is readable or writable.

9. Use lastModified() Method to display the modified information.

10. Use length() method to display the size of the file.


11. Use isHiddden() Method to display whether the file is hidden or not.
46

PROGRAM:
import java.io.*;
import java.util.Scanner;
class FileDemo
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
String filename;
System.out.println("Enter the file name");
filename=s.next();
File f1=new File(filename);
System.out.println("file name"+f1.getName());
System.out.println("path"+f1.getPath());
System.out.println("parent"+f1.getParent());
System.out.println(f1.exists());
System.out.println(f1.canRead());
System.out.println(f1.canWrite());
System.out.println(f1.isDirectory());
System.out.println(f1.isFile());
System.out.println(f1.lastModified());
System.out.println(f1.length());
System.out.println(f1.isHidden());
}
}
47

OUTPUT:

Enter the file name


FileDemo.java
File name:FileDemo.java
path:FileDemo.java
parent:null
File exists :true
Readable:true
Writable:true
Directory:false
File or not:true
Last Modified:1536136980469
Length:791
Hidden:false

Result:
Thus the java application program for file information has been executed successfully
48

EX NO 9

Write a java program to find the maximum value


DATE:

AIM:
To Write a java program to find the maximum value from the given type of elements using a generic
function.

ALGORITHM:

1. Start the program


2. Define the array with the elements
3. Sets the first value in the array as the current maximum
4. Find the maximum value by comparing each elements of the array
5. Display the maximum value
6. Stop the program
49

PROGRAM :

public class MaximumTest


{
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T maximum(T x, T y, T z)
{
T max = x; // assume x is initially the largest
if(y.compareTo(max) > 0)
{
max = y; // y is the largest so far
}
if(z.compareTo(max) > 0)
{
max = z; // z is the largest now
}
return max; // returns the largest object
}
public static void main(String args[])
{
System.out.printf("Max of %d, %d and %d is %d\n\n", 3, 4, 5, maximum( 3, 4, 5 ));
System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7));
System.out.printf("Max of %s, %s and %s is %s\n","pear","apple", "orange", maximum("pear", "apple",
"orange"));
}
}
50

OUTPUT:
Max of 3, 4 and 5 is 5
Max of 6.6,8.8 and 7.7 is 8.8
Max of pear, apple and orange is pear

Result:
Thus the java application to find maximum value of the given elements has been executed
successfully.
- 51 -

importjava.io.*;

publicclass Max

publicstaticvoidmain(String[]args)

Integer[]list-newInteger[10]; for

(int i=0;i<list.length;i++)

list[i]=i;

System.out.println("Max="+max(list));

publicstatic<EextendsComparable<E>>Emax(E[]list)

Emax=list[0];

for(inti=1;i<list.length;i++)

{E element=list[i];

if(element.compareTo(max)>0)

max-element;

}}

returnmax;

}
52

OUTPUT:
Max=9

RESULT:
Thusthejavaapplicationtofindmaximumvalueofthegivenelementshasbeenexecuted
successfully.
53

EX NO:10

JavaFXcontrol
DATE:

AIM:
To writeajavaprogramtodevelopjavaFXcontrol.

ALGORITHM:
1. Createalabel(Label)andset itsinitialtext.
2. Create abutton(Button)andsetitslabeltext.
3. Attachanactiontothebuttonusing setOnAction.
4. Insidetheactionevent,changethetextofthe labeltoanewvalue.
5. Addthelabel and buttontoalayout container(VBox).
6. Createascene(Scene) withthelayout container.
7. Setthesceneinawindow(Stage)anddisplayit.
8. EndofAlgorithm:
54

PROGRAM:
//Javaprogramtocreateamenubarandaddmenuto

//itandalsoaddmenuitemstomenuandalsoadd

//aneventlistenertohandletheeventsimport

javafx.application.Application;

importjavafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.*;

import javafx.event.ActionEvent;

importjavafx.event.EventHandler,

import javafx.scene.control.*;

import javafx.stage.Stage;

import javafx.scene.control.Alert Alert Type;

import java time. LocalDate;

publicclassMenuBar_2extendsApplication

//launchtheapplicationpublicvoidstart(Stages)

//settitleforthestages.setTitle("creatingMenuBar");

//createamenuMenum=newMenu("Menu");

//createmenuitems

Menultemml=newMenultem("menuitem1");

Menultemm2=newMenultem("menuitem2");Menultemm3=newMenultem("menuitem3");// add
menu items to menu

m.getitems().add(ml);m.getItems().add(m2);m.getItems().add(m3);

//labeltodisplayevents

Label1=newLabel("\t\t\t\t"+"nomenuitemselected"),

//createeventsformenuitems

//actionevent

EventHandler ActionEvent event = new EventHandler<ActionEvent>()

public void handle(ActionEvent e)

L.setText("\t\t"+((Menultem)e.getSource()).getText()+"selected");

//addeventml.setOnAction(event);m2setOnAction(event);m3.setOnAction(event);
55

//createamenubarMenuBarmbnewMenuBar();

//addmenutomenubarmb.getMenus().add(m),

//createaVBoxVBoxvbnewVBox(mb, 1).

//createasceneScenesc=newScene(vb,500,300);

//set thescenes.setScene(sc),s.show(); public

static void main(String args[])

//launchtheapplicationlaunch(args);})
56

OUTPUT:

RESULT:

Thus the Java FX control program is executed successfully.

You might also like