0% found this document useful (0 votes)
61 views41 pages

Cs 3381 Oop Lab Manual-1

Uploaded by

prawinsk2005
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)
61 views41 pages

Cs 3381 Oop Lab Manual-1

Uploaded by

prawinsk2005
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/ 41

CS3381 OBJECT ORIENTED PROGRAMMING LABORATORY

LIST OF EXPERIMENTS

NAME: REG.NO:

EXP.
DATE NAME OF THE EXPERIMENT MARKS SIGN
NO.

A.Sequential search

B.Binary search
1
C. Sorting algorithms-Selection Sort

D.Quadratic sorting algorithm-Insertion Sort

A. Stack
2
B. Queue

3 Generating pay slips for the employees

4 Finding Area Of Different Shapes Using Abstract Class

5 Finding Area Of Different Shapes Using Interface

6 User defined exception handling.

7 Multi-threaded application

8 File Handling

9 Finding Maximum and Minimum using Generic Classes

10 Applications using JavaFX controls, layouts and menus.

11 Mini project using Java concepts


Ex. No. 1.A SEQUENTIAL SEARCH
ELECTRICITY BILL
Date:

Problem :
Develop a Java application to Solve problems by using Sequential Search.

Aim:
To write a Java program to solve problems by using Sequential Search.

Algorithm:

Step1: start
Step 2: Get the array elements.
Step 3: Traverse the array.
Step 4: Match the key element with array element.
Step 5: If key element is found, return the index position of the array element.
Step 6: If key element is not found, print element not found message.
Step 7: stop

Program:

import java.util.Scanner;
class LinearSearch
{
public static void main(String[] args)
{
int c,n,search,array[];

Scanner in = new Scanner(System.in);


System.out.println("Enter number of elements");
n=in.nextInt();
array=new int[n];

System.out.println("Enter those “ + n + “ elements");

for(c=0;c<n;c++)
array[c]=in.nextInt();

System.out.println("Enter value to find");


search=in.nextInt();

for(c=0;c<n;c++)
{
if(array[c]==search)
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if(c==n)
System.out.println(search + " isn’t present in array.");
}
}
Viva Questions:

1.How will you import the java packages?


2.What is the purpose of Linear Search?
3.How do you perform a Linear Search in array list?
4.How to implement Linear Search algorithm in java?
5.What is the complexity of Linear Search?

Result:

Thus the Java application to solve the problems by using Sequential Search was developed
successfully.
Ex. No.1.B BINARY SEARCH
1.
Date:

Problem :
Develop a Java application to Solve problems by using Binary Search.

Aim:
To write a Java program to solve problems by using Binary Search.

Algorithm:

Step1: Start
Step 2: Get the array elements.
Step 3: Calculate the mid element of the collection.
Step 4: Compare the key items with the mid element.
Step 5: If key item < mid element, then the key is in the upper half of the collection. Hence you
need search in the upper half (mid +1).
Step 6: Else if key item = middle element, then we return the mid index position for the key
found.
Step 7: Else key item > mid element, then the key lies in the lower half of the collection. Thus
repeat binary search on the lower (right) half of the collection.
Step 8: Stop

Program:

import java.util.Scanner;
class BinarySearchExample
{
public static void main(String args[])
{
int counter, num, item, array[], first, last, middle;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();
array = new int[num];
System.out.println("Enter " + num + " integers");
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();

System.out.println("Enter the search value:");


item = input.nextInt();
first = 0;
last = num - 1;
middle = (first + last)/2;

while (first <= last)


{
if (array[middle] < item)
first = middle + 1;
else if(array[middle] == item)
{
System.out.println(item + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(item + " is not found.\n");
}
}

Viva Questions:

1.How will you import the java packages?


2.What is array Binary Search?
3.How does arrays Binary Search work in java?
4.How to implement Binary Search algorithm in java?
5.What is the complexity of Binary Search?

Result:
Thus the Java application to solve the problems by using Binary Search was developed
successfully.
Ex. No.1.C QUADRATIC SORTING ALGORITHM

Date: SELECTION SORT

Problem :
Develop a Java application to Solve problems by using Selection Sort.

Aim:
To write a Java program to solve problems by using Selection Sort.

Algorithm:

Step 1: Start
Step 2: Initialize minimum value (min_index) to location 0.
Step 3: Traverse the array to find the minimum element in the array.
Step 4: While traversing if any element smaller than min_index is found then swap both the
values.
Step 5: Then, increment min_index to point to the next element.
Step 6: Repeat until the array is sorted.
Step 7: Stop

Program:

import java.util.Scanner;
public class selectionsort
{
public static void main(String args[])
{
int size, i, j, temp;
int arr[] = new int[50];
Scanner sc = new Scanner(System.in);
System.out.print("Enter Array Size : ");
size = sc.nextInt();
System.out.print("Enter Array Elements : \n");
for(i=0; i<size; i++)
{
arr[i] = sc.nextInt();
}
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.print("sorted array >>\n");
for(i=0; i<size; i++)
{
System.out.print(arr[i]+ " ");
}
}
}

Viva Questions:

1. What Is Selection Sort?


2. What is the worst case complexity of selection sort?
3. What is the advantage of selection sort over other sorting techniques?
4. What is the best case complexity of selection sort?
5. What are the disadvantages of Selection Sort?

Result:
Thus the java program for selection sort was developed and the output was verified
successfully.
Ex. No.1.D QUADRATIC SORTING ALGORITHM

Date: INSERTION SORT

Problem:
Develop a java application to solve problems by using Insertion Sort.

Aim:
To write a Java program to solve problems by using Insertion Sort.

Algorithm:

Step1: Start
Step 2: Get the elements
Step 3: If the element is the first element, assume that it is already sorted.
Step 4: Pick the next element, and store it separately in a key.
Step 5: Now, compare the element with all elements in the sorted array.
Step 6: If the element in the sorted array is smaller than the current element, then move to the
next element. Else, shift greater elements in the array towards the right.
Step 7: Insert the value.
Step 8: Repeat until the array is sorted.
Step 9: Stop

Program:

import java.util.Scanner;
public class InsertionSort
{
public static void main(String[] args)
{
int n, i, j, element;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the Size of Array: ");
n = scan.nextInt();
int[] arr = new int[n];
System.out.print("Enter " +n+ " Elements: ");
for(i=0; i<n; i++)
arr[i] = scan.nextInt();
for(i=1; i<n; i++)
{
element = arr[i];
for(j=(i-1); j>=0 && arr[j]>element; j--)
arr[j+1] = arr[j];
arr[j+1] = element;
}
System.out.println("\nThe new sorted array is: ");
for(i=0; i<n; i++)
System.out.print(arr[i]+ " ");
}
}

Viva Questions:
1.How will import java package?
2.What is the purpose of Insertion Sort?
3.What is complexity of Insertion Sort?
4.Which sorting is best for large data?
5.How many comparisons does insertion sort have?

Result:
Thus the java program for insertion sort was developed and the output was verified
successfully.
Ex. No.2.A STACK

Date:

Problem:
Develop stack data structure using classes and objects.

Aim:
To write a Java program to develop stack data structure using classes and objects.

Algorithm:

Step 1: start.
Step 2: Enter the size of stack.
Step 3: Enter the choice. Using switch case push and pop operations are performed.
Step 4: If the choice is one, then push operation is performed.
a) Enter the input of the element to be pushed.
b) Check whether the stack is full or not. If the stack is full, then print “stack
overflow. Otherwise the value is pushed to the stack and the current position is
increased.
Step 5: If the choice is two, then pop operation is performed.
a) Check whether the stack is empty or not. If the stack is empty, then print “stack
underflow”.
b) Otherwise the value is popped from the stack.
Step 6: If the choice is three, display the stack elements.
Step 7: If the choice is four, exit the program.
Step 8: Stop.
Program:

import java.util.Scanner;
import java.util.*;
import java.io.*;
class Stack
{
final int max=100;
int s[]=new int[max];
int top=-1;
void push(int ele)
{
if(top>=max-1)
System.out.println("stack overflow");
else
s[++top]=ele;
}
int pop()
{
int z=0;
if(top==-1)
System.out.println("stack underflow");
else
z=s[top--];
return z;
}
void display()
{
if(top==-1)
System.out.println("Stack empty");
else
{
for(int i=top;i>-1;i--)
System.out.println(s[i]+"");
}
}
public static void main(String args[])
{
int q=1;
Stack m = new Stack();
System.out.println("program to perform stack operations");
Scanner sc=new Scanner(System.in);
while(q!=0)
{
System.out.println("enter 1.push 2.pop 3.display 4.exit");
System.out.println("enter your choice");
int ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("enter the element to be pushed");
int ele=sc.nextInt();
m.push(ele);
break;
case 2:
int popele;
popele=m.pop();
System.out.println("the poped element is ");
System.out.println(popele+"");
break;
case 3:
System.out.println("elements in the stack are");
m.display();
break;
case 4:
q=0;
}
}
}
}

Viva Questions:
1. Define stack?
2. Why Are Stacks Useful?
3. List out the basic operations that can be performed on a stack.
4. how to do push operation in a stack?
5. List the application of stacks.

Result:
Thus the Java program for stack data structure using classes and objects was
developed and the output was verified successfully.
Ex. No.2.B QUEUE

Date:

Problem:
Develop Queue data structure using classes and objects.

Aim:
To implement queue data structure using classes and objects.

Algorithm:

1. Start
2. Define an array queue of size max = 5.
3. Initialize front = rear = –1.
4. Display a menu listing queue operations.
5. Accept choice
If choice = 1 then enqueue operation is performed.
If choice = 2 then dequeue operation is performed.
If choice = 3 then display queue elements starting from front to rear.
If choice = 4, exit the program.
7. Stop

Program:

import java.util.Scanner;
import java.util.*;
import java.io.*;
class Queue
{
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;
Queue()
{
front = -1;
rear = -1;
}
boolean isFull()
{
if (front == 0 && rear == SIZE - 1)
{
return true;
}
return false;
}
boolean isEmpty()
{
if (front == -1)
return true;
else
return false;
}
void enQueue(int element)
{
if (isFull())
{
System.out.println("Queue is full \n");
}
else
{
if (front == -1)
front = 0;
rear++;
items[rear] = element;
System.out.println("\n Inserted " + element);
}
}
int deQueue()
{
int element;
if (isEmpty())
{
System.out.println("\n Queue is empty \n");
return (-1);
}
else
{
element = items[front];
if (front >= rear)
{
front = -1;
rear = -1;
} /* Q has only one element, so we reset the queue after deleting it. */
else
{
front++;
}
System.out.println("\n Deleted -> " + element);
return (element);
}
}
void display()
{
/* Function to display elements of Queue */
int i;
if (isEmpty())
{
System.out.println("Empty Queue \n");
}
else
{
System.out.println("\nFront index-> " + front);
System.out.println("Items -> ");
for (i = front; i <= rear; i++)
System.out.print(items[i] + " ");
System.out.println("\nRear index-> " + rear);
}
}
public static void main(String[] args)
{
int e=1;
Queue q = new Queue();
System.out.println("program to perform stack operations \n");
Scanner sc=new Scanner(System.in);
while(e!=0)
{
System.out.println("1.enqueue 2.dequeue 3.display 4.exit");
System.out.println("\n enter your choice :");
int ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("\n enter the element to be pushed");
int ele=sc.nextInt();
q.enQueue(ele);
break;
case 2:
int dequeue;
dequeue=q.deQueue();
System.out.println("\n the deleted element is");
System.out.println(dequeue+"");
break;
case 3:
System.out.println("\n elements in the queue are");
q.display();
break;
case 4:
e=0;
}
}
}
}

Viva Questions:

1. Define a Queue?
2. List the application of queue.
3. What are the key public interfaces provided by queues?
4. What are the types of queue?
5. Define Dequeue?

Result:

Thus the Java program for Queue data structure using classes and objects was
developed and the output was verified successfully.
Ex. No. GENERATING PAY SLIPS FOR THE EMPLOYEES

Date:

Problem:
Develop a java application with Employee class with Emp_name, Emp_id, Address,
Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant Professor, Associate
Professor and Professor from employee class. Add Basic Pay (BP) as the member of all the
inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for
staff club fund. Generate pay slips for the employees with their gross and net salary.

Aim:
To develop a java application for generating pay slips for the employees with their gross
and net salary.

Algorithm:
Step 1. Start
Step 2. Get the information about the employee – Employee name. Employee id, address, mail id
and mobile number
Step 3:Using function calculate the salary
Grosssalary=(0.97f*bpay)+(0.10f*bpay)+(0.12f*bpay)+(0.001f*bpay)+bpay;
Netsalary=grosssalary-((0.12f*bpay)+(0.001f*bpay)
Step 4:Using switch case, get the choice (Professor, Associate Professor, Assistant
Professor,Programmer) and the required function called.
Step 6:Using function calculate the salary by the input as bpay.
Step 7:Choose the employee and print the details.
Step 8:Stop.

Program:

import java.util.*;
import java.io.*;
class Employee
{
int id;
float grosssalary, netsalary,bpay;
String name, address, mail, mno;
Scanner get = new Scanner(System.in);
Employee()
{
System.out.println("Enter Name of the Employee:");
name = get.next();
System.out.println("Enter id:");
id = get.nextInt();
System.out.println("Enter Address of the Employee:");
address = get.next();
System.out.println("Enter mailid of the Employee:");
mail = get.next();
System.out.println("Enter mobile no. of the Employee:");
mno = get.next();
}
void salary()
{
grosssalary= (0.97f*bpay)+(0.10f*bpay)+(0.12f*bpay) + (0.001f*bpay)+bpay;
netsalary= grosssalary-((0.12f*bpay) + (0.001f*bpay));
}
void display()
{
System.out.println("Employee Name: "+name);
System.out.println("ID : "+id);
System.out.println("Mail Id : "+mail);
System.out.println("Address : "+address);
System.out.println("Mobile No. : "+mno);
System.out.println("Gross Salary : "+grosssalary);
System.out.println("Net Salary : "+netsalary);
}
}
class Programmer extends Employee
{
Programmer()
{
System.out.println("Enter Basic Pay:");
bpay = get.nextFloat();
salary();
}
void display()
{
System.out.println("\n ==============\n Programmer\n ================\n");
super.display();
}
}
class AssistantProfessor extends Employee
{
AssistantProfessor()
{
System.out.println("Enter Basic Pay:");
bpay = get.nextFloat();
salary();
}
void display()
{
System.out.println(" ==============================\n Assistant Professor\n
==============================\n");
super.display();
}
}
class AssociateProfessor extends Employee
{
AssociateProfessor()
{
System.out.println("Enter Basic Pay:");
bpay = get.nextFloat();
salary();
}
void display()
{
System.out.println(" =======================\n Associate Professor\n
=======================\n");
super.display();
}
}
class Professor extends Employee
{
Professor()
{
System.out.println("Enter Basic Pay:");
bpay = get.nextFloat();
salary();
}
void display()
{
System.out.println(" =============\n Professor\n =============\n");
super.display();
}
}
class Employees
{
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(" -------------\n PAY SLIPS \n ------------ \n 1. Professor \n 2. Associate
Professor\n 3. Assistant Professor\n 4. Programmer");
System.out.printf("\n Choose the type of Employee: ");
int choice=Integer.parseInt(br.readLine());
switch(choice)
{
case 1:
System.out.println(" =========================\n Enter Professor Details \n
========================="+"\n");
Professor ob1 = new Professor();
ob1.display();
break;
case 2:
System.out.println(" =================================\n Enter Associate Professor
Details \n ================================="+"\n");
AssociateProfessor ob2 = new AssociateProfessor();
ob2.display();
break;
case 3:
System.out.println(" =================================\n Enter Assistant Professor
Details\n ================================="+"\n");
AssistantProfessor ob3 = new AssistantProfessor();
ob3.display();
break;
case 4:
System.out.println(" ============================\n Enter Programmer Details \n
============================"+"\n");
Programmer ob4 = new Programmer();
ob4.display();
break;
default:
System.out.println("Enter correct choice");
break;
}
}
}

Viva Questions:

1. How to create a package in java?


2. How to Create a class Employee inside a package name employee?
3. How to Create class Programmer?
4. How to initialize the instance variable of Employee class?
5. How to Compile the outside package?

Result:
Thus the java application for generating pay slips for the employees with their gross and net
salary was developed successfully.
Ex. No. FINDING AREA OF DIFFERENT SHAPES USING ABSTRACT CLASS

Date:

Problem:

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 contains only the
method print Area () that prints the area of the given shape.

Aim:
To write a JAVA program for finding area of different shapes using abstract class concept.

Algorithm:

Step 1:Start.
Step 2: Create an abstract class named Shape that contains two integers and an empty method
named print Area()
Step 3:Get the value of length and breadth of rectangle.
Step 4:Calculate the area of rectangle using area=length * breadth
Step 5:Print the area of rectangle.
Step 6:Get the value of length anf height of triangle.
Step 7:Calculate the area of triangle using area = 0.5 * length * height
Step 8:Print the area of circle.
Step 9:Get the value of radius.
Step 10:Calculate the area of circle using area =Math.PI * radius * radius.
Step 11:Print the area of circle.
Step 12:Stop.
Program:

import java.util.*;
abstract class Shape
{
int length = 0;
int height = 0;
public abstract void printArea();
}
class Rectangle extends Shape
{
int area = 0;
public void printArea()
{
System.out.println("\n Rectangle\n ---------- ");
Scanner input = new Scanner(System.in);
System.out.printf("Enter Length of Rectangle : ");
this.length = input.nextInt();
System.out.printf("Enter Breadth of Rectangle : ");
this.height = input.nextInt();
this.area = this.length*this.height;
System.out.println("Area of the Rectangle is : " + this.area);
}
}
class Triangle extends Shape
{
double area = 0.0;
public void printArea()
{
System.out.println("\n Triangle\n --------- ");
Scanner input = new Scanner(System.in);
System.out.printf("Enter Length of Triangle : ");
this.length = input.nextInt();
System.out.printf("Enter Height of Triangle : ");
this.height = input.nextInt();
this.area = 0.5 * this.length * this.height;
System.out.println("Area of the Triangle is : " + this.area);
}
}
class Circle extends Shape
{
double area = 0.0;
public void printArea()
{
System.out.println("\n Circle\n -------- ");
Scanner input = new Scanner(System.in);
System.out.printf("Enter Radius of Circle : ");
this.length = input.nextInt();
this.area = Math.PI * this.length * this.length;
System.out.println("Area of the Circle is : "+this.area);
}
}
class Absclass
{
public static void main(String[] args)
{
System.out.println("\n-------------\nFinding Area\n ------------ ");
Shape rt = new Rectangle();
rt.printArea();
Shape tr = new Triangle();
tr.printArea();
Shape cr = new Circle();
cr.printArea();
}
}

Viva Questions:

1.How will you Import the java packages?


2. How will you Create an abstract class name?
3. How will you Create a class Rectangle, Triangle, Circle?
4. How will you get the input during runtime?
5. How will you Create object for a class in memory?

Result:
Thus the JAVA program for finding area of different shapes using abstract class concept was
written, executed and the output was verified successfully.
Ex. No. 5 FINDING AREA OF DIFFERENT SHAPES USING INTERFACE

Date:

Problem:

Write a Java Program to create an interface named Shape that contains an empty method
named print Area(). Provide three classes named Rectangle, Triangle and Circle such that each one
of the classes implements the class Shape. Each one of the classes contains variables and the
method print Area () that prints the area of the given shape.

Aim:
To write a java program for finding area of different shapes using interface concept.

Algorithm:

Step 1: Start.
Step 2: Create an interface named Shape that contains an empty method named print Area()
Step 3: Get the value of length and breadth of rectangle.
Step 4: Calculate the area of rectangle using area=length * breadth
Step 5: Print the area of rectangle.
Step 6: Get the value of length and height of triangle.
Step 7: Calculate the area of triangle using area = 0.5 * length * height
Step 8: Print the area of circle.
Step 9: Get the value of radius.
Step 10: Calculate the area of circle using area =Math.PI * radius * radius.
Step 11: Print the area of circle.
Step 12: Stop.
Program:

import java.util.*;
interface Shape
{
void printArea();
}
class Rectangle implements Shape

{
int area, length,height;
public void printArea()
{
System.out.println("\n Rectangle\n ---------- ");
Scanner input = new Scanner(System.in);
System.out.printf("Enter Length of Rectangle : ");
this.length = input.nextInt();
System.out.printf("Enter Breadth of Rectangle : ");
this.height = input.nextInt();
this.area = this.length*this.height;
System.out.println("Area of the Rectangle is : " + this.area);
}
}
class Triangle implements Shape
{
double area = 0.0;
int length,height ;
public void printArea()
{
System.out.println("\n Triangle\n --------- ");
Scanner input = new Scanner(System.in);
System.out.printf("Enter Length of Triangle : ");
this.length = input.nextInt();
System.out.printf("Enter Height of Triangle : ");
this.height = input.nextInt();
this.area = 0.5 * this.length * this.height;
System.out.println("Area of the Triangle is : " + this.area);
}
}
class Circle implements Shape
{
double area = 0.0;
int length;
public void printArea()
{
System.out.println("\n Circle\n -------- ");
Scanner input = new Scanner(System.in);
System.out.printf("Enter Radius of Circle : ");
this.length = input.nextInt();
this.area = Math.PI * this.length * this.length;
System.out.println("Area of the Circle is : "+this.area);
}
}
class Main
{
public static void main(String[] args)
{
System.out.println("\n-------------\nFinding Area\n ------------ ");
Shape rt = new Rectangle();
rt.printArea();
Shape tr = new Triangle();
tr.printArea();
Shape cr = new Circle();
cr.printArea();
}
}

Viva Questions:

1.What is an interface in java?


2. Can an interface extends another interface?
3. How will you make classes Rectangle, Triangle, Circle to implement interface?
4. How will you get the input during runtime?
5. What modifiers are allowed for methods in an interface?

Result:
Thus the JAVA program for finding area of different shapes using interface concept was
written, executed and the output was verified successfully.
Ex. No. USER DEFINED EXCEPTION HANDLING

Date:

Problem:
Implement exception handling and creation of user defined exceptions.

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

Algorithm:

Step 1:Start.
Step 2:Create a class MyException that extends Exception class
Step 3:Get an input
Step 4:Check whether the input is greater than or equal to zero.
a) If yes, print the number.
b) Otherwise, handle the exception using try - catch block
Step 5:Stop.

Program:

import java.io.*;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class ExceptMain
{
public static void main(String a[])
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.printf("Enter a positive number : ");
int no=Integer.parseInt(br.readLine());
if(no<0)
{
throw new MyException(" Number must be positive ");
}
System.out.println(" Number:" +no);
}
catch(MyException e)
{
System.out.println("Caught the Exception");
System.out.println(e.getMessage());
System.out.println("Exception Handled ...... !");
}
catch(Exception e)
{
System.out.println("Enter numbers ... Exception Handled!");
}
}
}

Viva Questions:

1. How will you Import the java packages.?


2. How to Create a subclass of Exception named as MyException?
3. When the exception is thrown?
4. How the main ( ) method sets up an exception handler?
5. Define exception handling in java?

Result:
Thus the Java program to implement user defined exception handling was implemented and
the output was verified successfully.
Ex. No. MULTI-THREADED APPLICATION

Date:

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

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

Algorithm:

Step 1:Start.
Step 2:Create three classes. Two classes (even, odd) implements Runnable and one thread extends
Thread Class.
Step 3: First thread generates a random integer every 1 second.
Step 4: The integer value is even, the second thread computes the square of the number and prints.
Step 5: If the value is odd, the third thread will print the value of cube of the number.
Step 6: Stop

Program:

import java.util.*;
class even implements Runnable
{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println(" Thread- 2 : "+ 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("Thread - 3 : "+ 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 = r.nextInt(100);
System.out.println(" Thread-1 : 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 ThreeThreads
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}
Viva Questions:

1. How will you Import the java packages?


2. How to Create a thread?
3. How the thread generates a random integer?
4. How the thread computes the square of the number?
5. How the thread will print the value of cube of the number?

Result:
Thus the java program that implements a multi-threaded application that has three threads
was written and the output was verified successfully.
Ex. No. FILE HANDLING

Date:

Problem:
Write a Java program to perform file operations.

Aim:
To write a Java program to perform file operations.

Algorithm:

Step 1:Start.
Step 2:Get the input as filename.
Step 3:If the filename exists, then
a) Print the details about the file (Is File?, Is Directory?, Is Readable?, Is Writable?, Type,
Length of the file.
b) Otherwise, print “File does not exist”
Step 4:Stop.

Program:

import java.util.Scanner;
import java.io.File;
class FileInfo
{
public static String getFileExtension(File f1)
{
String fileName = f1.getName();
if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
return fileName.substring(fileName.lastIndexOf(".")+1);
else return "Folder";
}
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.print("\nEnter the filename: ");
String s=input.nextLine();
File f1=new File(s);
if(f1.exists())
{
System.out.println("\nDETAILS ABOUT THE FILE");
System.out.println(" --------------------- ");
System.out.println(" File exists in : "+f1.getAbsolutePath());
System.out.println("\n Is file? :"+f1.isFile());
System.out.println(" Is Directory? :"+f1.isDirectory());
System.out.println("\n Is Readable? :"+f1.canRead());
System.out.println(" Is Writable? :"+f1.canWrite());
System.out.println("\n Type :"+getFileExtension(f1));
System.out.println("\n Length of the File :"+f1.length()+" Bytes");

}
else
{
System.out.println("File does not exist");
}

}
}

Viva Questions:

1. How will you Import the java packages.?


2. How to write a java program to implement file information?
3. How to create a File object associated with the file?
4. How the the program uses conditional operator to check different functionalities of the given file.?
5. How will you get the input during runtime?

Result:
Thus the Java program for reading a file name from the user and displaying the information
about the file was written and the output was verified successfully.
Ex. No. 9 FINDING MAXIMUM AND MINIMUM USING GENERIC CLASSES

Date:

Problem:
Develop applications to demonstrate the features of generic classes.

Aim:
To write a java program for finding the maximum and minimum value from the given
type of elements using a generic class.

Algorithm:

Step 1: Start.
Step 2: Create a class Myclass to implement generic class and generic methods.
Step 3: Get the set of values belonging to specific data type.
Step 4: Create the objects of the class to hold integer,character and double values.
Step 5: Create the methods to compare the values and find the maximum value and minimum
value stored in the array.
Step 6: Invoke the methods with integer, character or double values.
Step 7: The maximum and minimum value of Integer ,character and double is displayed based on
the data type passed to the method.
Step 8: Stop.

Program:

class MyClass<T extends Comparable<T>>


{
T[] vals;
MyClass(T[] obj)
{
vals = obj;
}
public T min()
{
T v = vals[0];
for(int i=1; i < vals.length; i++)
if(vals[i].compareTo(v) < 0)
v = vals[i];
return v;
}
public T max()
{
T v = vals[0];
for(int i=1; i < vals.length;i++)
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[]={'j','p','x','a','n','d'};
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);
System.out.println("Max value in inums: " + iob.max());
System.out.println("Min value in inums: " + iob.min());
System.out.println("Max value in chs: " + cob.max());
System.out.println("Min value in chs: " + cob.min());
System.out.println("Max value in d: " + dob.max());
System.out.println("Min value in d: " + dob.min());
}
}

Viva Questions:
1.What is generics in java?
2.What are the advantages of using generics?
3.How do you declare a generic class?
4.What are generic methods?
5.What is type Erasure?

Result:
Thus the java program for finding the maximum and minimum value from the given
type of elements was implemented using a generic class and executed successfully.
Ex. No. 11 JAVAFX CONTROLS, LAYOUTS AND MENUS
Date:

Problem:
Develop applications using JavaFX controls, layouts and menus.

Aim:
To write a java program to develop applications using JavaFX controls, layouts and menus.

Algorithm:
Step 1: Start
Step 2: Create a menu Button named “Technology”.
Step 3: Create necessary menu items and add it add it to the menu.
Step 4: Add the choice box to the scene.
Step 5: Set the stage and launch.
Step 6: Stop

Program:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class MenuButtonExample extends Application
{
public void start(Stage stage)
{
MenuButton menu = new MenuButton("Technology");
menu.setMnemonicParsing(true);
MenuItem item1 = new MenuItem("Java");
MenuItem item2 = new MenuItem("Python");
MenuItem item3 = new MenuItem("C++");
MenuItem item4 = new MenuItem("Big Data");
MenuItem item5 = new MenuItem("Machine Learning");
menu.getItems().addAll(item1, item2, item3, item4, item5);
HBox layout = new HBox(25);
layout.getChildren().addAll(menu);
layout.setPadding(new Insets(15, 50, 50, 150));
layout.setStyle("-fx-background-color: BEIGE");
Scene scene = new Scene(layout, 595, 200);
stage.setTitle("Menu Button");
stage.setScene(scene);
stage.show();
}
public static void main(String args[])
{
launch(args);
}
}
Viva Questios:

1.What is javaFX?
2. What are various features of JavaFX?
3. Which method is used to create JavaFX application?
4. What is a Stage in JavaFX?
5. What is context menu in JavaFX?

Result:
Thus the application using JavaFX controls, layouts and menus was developed and the
output was verified successfully.
Ex. No. 11 MINI PROJECT
Date:

Problem:
Develop a mini project for any application using Java concepts.

Aim:
To develop a Bus Reservation System as a mini project using java concepts

Algorithm:

Step 1: Start
Step 2: Create classes that are needed for Bus Reservation System
Step 3: Get the options for ticket booking and perform the operations.
Step 4: Display the results.
Step 5: Stop

Program:

Booking.java

package busResv;
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Booking {
String passengerName;
int busNo;
Date date;

Booking(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter name of passenger: ");
passengerName = scanner.next();
System.out.println("Enter bus no: ");
busNo = scanner.nextInt();
System.out.println("Enter date dd-mm-yyyy");
String dateInput = scanner.next();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

try {
date = dateFormat.parse(dateInput);
} catch (ParseException e) {

e.printStackTrace();
}

}
public boolean isAvailable(ArrayList<Booking> bookings, ArrayList<Bus> buses) {
int capacity = 0;
for(Bus bus:buses) {
if(bus.getBusNo() == busNo)
capacity = bus.getCapacity();
}

int booked = 0;
for(Booking b:bookings) {
if(b.busNo == busNo && b.date.equals(date)) {
booked++;
}
}

return booked<capacity?true:false;

}
}

Bus.java

package busResv;

public class Bus {


private int busNo;
private boolean ac;
private int capacity;

Bus(int no,boolean ac,int cap){


this.busNo = no;
this.ac = ac;
this.capacity = cap;
}

public int getBusNo(){


return busNo;
}

public boolean isAc(){


return ac;
}
public int getCapacity()
{
return capacity;
}

public void setAc(boolean val) {


ac = val;
}

public void setCapacity(int cap) {


capacity = cap;
}

public void displayBusInfo(){


System.out.println("Bus No:" + busNo + " Ac:" + ac + " Total Capacity: " +
capacity);
}
}

BusDemo.java

package busResv;

import java.util.Scanner;
import java.util.ArrayList;

public class BusDemo {

public static void main(String[] args) {

ArrayList<Bus> buses = new ArrayList<Bus>();


ArrayList<Booking> bookings = new ArrayList<Booking>();

buses.add(new Bus(1,true,2));
buses.add(new Bus(2,false,50));
buses.add(new Bus(3,true,48));

int userOpt = 1;
Scanner scanner = new Scanner(System.in);

for(Bus b:buses) {
b.displayBusInfo();
}

while(userOpt==1) {
System.out.println("Enter 1 to Book and 2 to exit");
userOpt = scanner.nextInt();
if(userOpt == 1) {
Booking booking = new Booking();
if(booking.isAvailable(bookings,buses)) {
bookings.add(booking);
System.out.println("Your booking is confirmed");
}
else
System.out.println("Sorry. Bus is full. Try another bus or
date.");
}
}
}

}
Result:
Thus the mini project for Bus Reservation System using java concepts was done and
executed successfully.

You might also like