CS3381 OOP Lab Student Copy
CS3381 OOP Lab Student Copy
0 0 3 1.5
COURSE OBJECTIVES
➢ To build software development skills using java programming for real-world applications.
➢ To understand and apply the concepts of classes, packages, interfaces, inheritance, exception
handling and file processing.
➢ To develop applications using generic programming and event handling.
LIST OF EXPERIMENTS
1. Solve problems by using sequential search, binary search, and quadratic sorting algorithms
(selection, insertion)
2. Develop stack and queue data structures using classes and objects.
3. Develop a java application with an Employee class with Emp_name, Emp_id, Address, Mail_id,
Mobile_no as members. Inherit the classes, Programmer, Assistant Professor, Associate Professor
and Professor from employee class. Add Basic Pay (BP) as the member of all the inherited classes
with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club funds.
Generate pay slips for the employees with their gross and net salary.
4. Write a Java Program to create an abstract class named Shape that contains two integers and
an empty method named printArea(). Provide three classes named Rectangle, Triangle and Circle
such that each one of the classes extends the class Shape. Each one of the classes contains only
the method printArea( ) that prints the area of the given shape.
5. Solve the above problem using an interface.
6. Implement exception handling and creation of user defined exceptions.
7. Write a java program that implements a multi-threaded application that has three threads. First
thread generates a random integer every 1 second and if the value is even, the second thread
computes the square of the number and prints. If the value is odd, the third thread will print the
value of the cube of the number.
8. Write a program to perform file operations.
9. Develop applications to demonstrate the features of generics classes.
10. Develop applications using JavaFX controls, layouts and menus.
11. Develop a mini project for any application using Java concepts.
AIM:
To develop a Java program by using sequential search algorithm.
ALGORITHM:
Step 1: Start the program.
Step 2: Start from the leftmost element of arr[] and one by one compare x with each
element of arr[ ].
Step 3: Let the element to be search be x.
Step 4: If x matches with an element, then return that index.
Step 5: If x doesn’t match with any of elements, then return -1.
Step 6: Stop the program.
PROGRAM:
// LinearSearch.java
package search;
public class LinearSearch
{
public static void main (String[ ] args)
{
int[ ] arr= {92, 25, 66, 47, 84, 75, 34, 10, 11};
int target = 10;
sequentialSearch(arr, target);
}
public static void sequentialSearch(int[] arr, int t)
{
int index = -1;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == t)
{
index = i;
break;
}
}
if (index == -1)
{
System.out.println("Your target integer "+t+" does not exist in the array");
}
else
{
System.out.println("Your target integer "+t+" is in index " + (index+1) + " of the array");
}
}
}
OUTPUT:
APPLICATIONS:
➢ Search for an element in an unsorted data sequence.
➢ Sorting elements in an array or list.
➢ Finding the minimum and maximum values in an array or list.
RESULT:
Thus, the java program for implementing a linear search was successfully developed and
executed.
EX: NO: 1 (B)
BINARY SEARCH ALGORITHM
DATE:
AIM:
To develop a Java program for implementing binary search algorithm.
ALGORITHM:
Step 1: Start the program.
Step 2: For Binary Search to be performed on any array, the array must be already sorted
in any format, that is, either ascending or descending.
Step 3: Find the middle index of the array/list.
Step 4: If the middle element is equal to the search element, Stop Searching.
Step 5: If the element that is to be searched is less than the middle element then consider
the first half as a separate list.
Step 6: Else-If the element that is to be searched is larger than the middle element then
consider the second half as a separate list.
Step 7: Repeat Step 2-3-4-5 Until desired result is found.
Step 8: Stop the program.
PROGRAM:
// BinarySearch.java
package search;
class BinarySearch
{
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 "+key+" is found at position: " + (mid+1));
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);
}
}
OUTPUT:
APPLICATIONS:
➢ Insertion, Deletion and Searching in Sorted Arrays.
➢ File Systems.
➢ Game Development.
➢ Data Compression.
➢ Network Routing.
➢ Online Shopping and E-Commerce.
RESULT:
Thus, the java program for implementing binary search was successfully developed and
executed.
EX: NO: 1 (C)
SELECTION SORT
DATE:
AIM:
To develop a Java program for implementing selection sort algorithm.
ALGORITHM:
Step 1: Start the program.
Step 2: Set Min_Index to 0.
Step 3: Search for the smallest element in the array.
Step 4: Swap with value with the element at the Min_Index.
Step 5: Increment Min_Index to point to next element.
Step 6: Repeat until the complete array is sorted.
Step 7: Stop the program.
PROGRAM:
// SelectionSort.java
package sort;
class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
{
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
}
public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int arr[] = {64,25,12,22,11};
ob.sort(arr);
System.out.println("Sorted Array");
ob.printArray(arr);
}
}
OUTPUT:
APPLICATIONS:
The selection sort is used when,
➢ A small list is to be sorted.
➢ Cost of swapping not considered in applications.
➢ Checking of all the elements is compulsory.
➢ Cost of writing to memory matters like in flash memory.
RESULT:
Thus, the java program for implementing selection sort was successfully developed and
executed.
EX: NO: 1 (D)
INSERTION SORT
DATE:
AIM:
To develop a Java program for implementing insertion sort algorithm.
ALGORITHM:
Step 1: Start the program.
Step 2: If the element is the first element, assume that it is already sorted, return 1.
Step 3: Pick the next element, and store it separately in a key.
Step 4: Now, compare the key with all elements in the sorted array.
Step 5: 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 6: Insert the value.
Step 7: Repeat above steps, until array is sorted.
Step 8: Stop the program.
PROGRAM:
// InsertionSort.java
package sort;
class InsertionSort
{
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 = {9,14,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);
System.out.println("After Insertion Sort");
for(int i:arr1)
{
System.out.print(i+" ");
}
}
}
OUTPUT:
APPLICATIONS:
➢ Small Arrays.
➢ Online Algorithms.
➢ Nearly sorted data.
➢ Debugging.
➢ Adaptive sorting.
➢ Online card games.
RESULT:
Thus, the java program for implementing insertion sort was successfully developed and
executed.
EX: NO: 2 (A)
STACK ADT USING ARRAY
DATE:
AIM:
To develop a Java program for implementing stack operations like push, pop, peek, size
etc., using Array.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a class StackUsingArray with the following instance variables:
- int[] stackArray: An array to store the stack elements.
- int maxSize: The maximum size of the stack.
- int top: An integer to keep track of the top element's index in the stack.
Step 3: Initialize the stackArray with the specified maxSize in the constructor.
- Initialize top to -1 to represent an empty stack.
Step 4: Implement the push operation:
- Check if the stack is full (top == maxSize - 1).
- If it's full, print an error message or handle the overflow.
- If it's not full, increment top by 1 and set stackArray[top] to the value being pushed.
Step 5: Implement the pop operation:
- Check if the stack is empty (top == -1).
- If it's empty, print an error message or handle underflow.
- If it's not empty, return the element at stackArray[top], then decrement top by 1.
Step 6: Implement the peek operation:
- Check if the stack is empty (top == -1).
- If it's empty, print an error message or handle the empty stack case.
- If it's not empty, return the element at stackArray[top] without removing it.
Step 7: Implement the size operation:
- Return top + 1 to get the current number of elements in the stack.
Step 8: Optionally, implement an isEmpty method:
- Return true if top is -1; otherwise, return false.
Step 9: Optionally, implement an isFull method:
- Return true if top is equal to (maxSize - 1); otherwise, return false.
Step 10: In the main method or elsewhere, create an instance of the StackUsingArray class
and perform stack operations like push, pop, peek, and size as needed.
Step 11: Stop the program.
PROGRAM:
// StackDS.java
package adt;
APPLICATIONS:
➢ Expression Evaluation.
➢ Function call stack.
➢ Undo/Redo Functionality.
➢ Backtracking Algorithms.
➢ Browser History.
➢ Parsing & Syntax Checking.
RESULT:
Thus, the java program for implementing stack manipulations using array was
successfully developed and executed.
EX: NO: 2 (B)
QUEUE ADT USING ARRAY
DATE:
AIM:
To develop a Java program for implementing queue operations like enqueue, dequeue,
display elements, full/empty conditions etc., using Array.
ALGORITHM:
Step 1: Start the program.
Step 2: Define a class named 'sample' to represent the queue.
- Declare private static integer variables 'front', 'rear', and 'capacity'.
- Declare a private static integer array 'queue'.
- Create a constructor that initializes 'front', 'rear', 'capacity', and 'queue'.
Step 3: Implement the 'queueEnqueue' method to add an item to the queue:
- Check if the 'capacity' is equal to 'rear'. If it is, print "Queue is Full" and return.
- Otherwise, add the 'item' to 'queue[rear]' and increment 'rear' by 1.
Step 4: Implement the 'queueDequeue' method to remove an item from the queue:
- Check if 'front' is equal to 'rear'. If it is, print "Queue is Empty" and return.
- Iterate from 'i' = 0 to 'rear - 1':
- Move each element 'queue[i + 1]' to 'queue[i]'.
- If 'rear' is less than 'capacity', set 'queue[rear]' to 0 and decrement 'rear' by 1.
Step 5: Implement the 'queueDisplay' method to display the elements of the queue:
- Check if 'front' is equal to 'rear'. If it is, print "Queue is Empty" and return.
- Iterate from 'i' = 'front' to 'rear - 1':
- Print 'queue[i]' on a new line.
Step 6: Implement the 'queueFront' method to display the front element of the queue:
- Check if 'front' is equal to 'rear'. If it is, print "Queue is Empty" and return.
- Print the front element 'queue[front]' on a new line.
Step 7: Define a public class 'QueueEx' for the main program.
- In the 'main' method:
- Create an instance 'q' of the 'sample' class with a capacity of 5.
- Call 'q.queueEnqueue' to enqueue elements.
- Call 'q.queueDisplay' to display the queue.
- Call 'q.queueFront' to display the front element.
- Call 'q.queueDequeue' to dequeue elements.
Step 8: Run the 'main' method to execute the program where the 'sample' class represents a basic
queue data structure with enqueue, dequeue, and display operations, while the 'QueueEx' class
demonstrates how to use the queue operations.
Step 9: Stop the program.
PROGRAM:
// QueueEx.java
package sample;
class sample
{
private static int front, rear, capacity;
private static int queue[];
sample(int size)
{
front = rear = 0;
capacity = size;
queue = new int[capacity];
}
void queueEnqueue(int item)
{
if (capacity == rear)
{
System.out.printf("Queue is Full.\n");
return;
}
else
{
queue[rear] = item;
rear++;
}
return;
}
void queueDequeue()
{
if (front == rear)
{
System.out.printf("Queue is Empty\n");
return;
}
else
{
for (int i = 0; i < rear - 1; i++)
{
queue[i] = queue[i + 1];
}
if (rear < capacity)
queue[rear] = 0;
rear--;
}
return;
}
void queueDisplay()
{
int i;
if (front == rear)
{
System.out.printf("Queue is Empty\n");
return;
}
System.out.println("\n Queue Elements are:");
for (i = front; i < rear; i++)
{
System.out.println("\n"+queue[i]);
}
return;
}
void queueFront()
{
if (front == rear)
{
System.out.printf("Queue is Empty\n");
return;
}
System.out.printf("\nFront Element of the Queue: %d", queue[front]);
return;
}
}
public class QueueEx
{
public static void main(String[] args)
{
sample q = new sample(5);
System.out.print("Initial Queue:");
q.queueDisplay();
q.queueEnqueue(10);
q.queueEnqueue(30);
q.queueEnqueue(50);
q.queueEnqueue(70);
System.out.println("Queue after Enqueue Operation:");
q.queueDisplay();
q.queueFront();
q.queueEnqueue(90);
q.queueDisplay();
q.queueDequeue();
q.queueDequeue();
System.out.printf("\nQueue after 2 Dequeue operation:");
q.queueDisplay();
q.queueFront();
}}
OUTPUT:
APPLICATIONS:
➢ Job scheduling.
➢ Task Management.
➢ Buffer Management.
➢ Order processing in E-Commerce.
➢ GPS Navigation.
➢ Request handling in web servers.
RESULT:
Thus, the java program for implementing stack manipulations using array was
successfully developed and executed.
EX: NO: 3
EMPLOYEE – PAY SLIP APPLICATION
DATE:
AIM:
To Develop a java application for generating pay slips for various categories of employees.
Application Information: Create an Employee class with Emp_name, Emp_id, Address, Mail_id,
Mobile_no as members. Inherit the classes, Programmer, Assistant Professor, Associate Professor
and Professor from employee class. Add Basic Pay (BP) as the member of all the inherited classes
with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club funds.
Generate pay slips for the employees with their gross and net salary.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a class called Employee with emp_name , emp_id , address , mail_id , mobile_no
as members and compute the payslip.
Step 3: Extend the employee class further for inheriting the classes called programmer,
assistant professor, associate professor and professor.
Step 4: Create class called pay slip and generate pay slip according to the position of the
employee.
Step 5: Stop the program.
PROGRAM:
// EmployeeSalary.java
package employee;
import java.io.DataInputStream;
class Employee
{
String emp_name,mail_id, address, mobile,designation;
int id,basic_pay;
void input() throws Exception
{
DataInputStream d=new DataInputStream(System.in);
System.out.print("Enter the id :");
id=Integer.parseInt(d.readLine());
System.out.print("Enter the Name :");
emp_name=d.readLine();
System.out.print("Enter the Address :");
address=d.readLine();
System.out.print("Enter Mobile number :");
mobile=d.readLine();
System.out.print("Enter the Mail id :");
mail_id=d.readLine();
}
void display(String designation,int basic_pay)
{
float da=0.97f *basic_pay ;
float hra= 0.1f*basic_pay;
float pf= 0.12f*basic_pay;
float sfclub = 0.001f*basic_pay;
float gross_pay = basic_pay + da + hra ;
float net_pay = gross_pay - pf - sfclub;
System.out.println("--------------------------------------------------------------------");
System.out.println("| EMPLOYEE DETAILS MAINTENANCE |");
System.out.println("--------------------------------------------------------------------");
System.out.println("Employee Id :"+id);
System.out.println("Employee Name :"+emp_name);
System.out.println("Employee Address :"+address);
System.out.println("Employee Mobile Number :"+mobile);
System.out.println("Employee Mail ID :"+mail_id);
System.out.println("Designation of an employee :"+designation);
System.out.println("Basic pay of an Employee :"+basic_pay);
System.out.println("DA :"+da);
System.out.println("HRA :"+hra);
System.out.println("Gross Salary :"+gross_pay);
System.out.println("PF :"+pf);
System.out.println("Staff club amount :"+sfclub);
System.out.println("Net pay :"+net_pay);
System.out.println("--------------------------------------------------------------------");
}
}
class Lecturer extends Employee
{
void cal() throws Exception
{
DataInputStream d=new DataInputStream(System.in);
designation = "Lecturer";
System.out.print("Enter the basic pay of an employee :");
basic_pay = Integer.parseInt(d.readLine());
display(designation,basic_pay);
}
}
class AP extends Employee
{
void cal() throws Exception
{
DataInputStream d=new DataInputStream(System.in);
designation = "Assistant Professor";
System.out.print("Enter the basic pay of an employee :");
basic_pay = Integer.parseInt(d.readLine());
display(designation,basic_pay);
}
}
class Associate extends Employee
{
void cal() throws Exception
{
DataInputStream d=new DataInputStream(System.in);
designation = "Associate Professor";
System.out.print("Enter the basic pay of an employee :");
basic_pay = Integer.parseInt(d.readLine());
display(designation,basic_pay);
}
}
class Professor extends Employee
{
void cal() throws Exception
{
DataInputStream d=new DataInputStream(System.in);
designation = "Professor";
System.out.print("Enter the basic pay of an employee :");
basic_pay = Integer.parseInt(d.readLine());
display(designation,basic_pay);
}
}
class EmployeeSalary
{
public static void main(String a[]) throws Exception
{
DataInputStream d=new DataInputStream(System.in);
System.out.print("1.Lecturer\n2.Assistant Professor\n3.Associate Professor \n 4.Professor \n
Enter the choice:");
int ch=Integer.parseInt(d.readLine());
switch(ch)
{
case 1: Lecturer e=new Lecturer();
e.input();
e.cal();
break;
case 2: AP e1=new AP();
e1.input();
e1.cal();
break;
case 3: Associate e2=new Associate();
e2.input();
e2.cal();
break;
case 4: Professor e3=new Professor();
e3.input();
e3.cal();
break;
}}}
OUTPUT:
FEATURES / APPLICATIONS:
➢ Any General-purpose application.
➢ Application that needs reusability.
➢ Organized form of information.
➢ Achieve run-time polymorphism.
RESULT:
Thus, the java program for developing payslip application for employees was successfully
developed and executed.
EX: NO: 4
ABSTRACT CLASS IMPLEMENTATION
DATE:
AIM:
To develop a Java program for implementing abstract class in order to calculate the area
of different shapes.
Application Information: Write a Java Program to create an abstract class named Shape that
contains two integers and an empty method named printArea(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class Shape. Each one
of the classes contains only the method printArea( ) that prints the area of the given shape.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare three different classes for rectangle, square and circle
Step 3: Declare two methods of the same name but with a different number of arguments or
with different data types.
Step 4: Call the methods defined in Step 3 using objects.
Step 5: Call the corresponding methods as per the number of arguments or their datatypes.
Step 6: Display the result.
Step 7: Stop the program.
PROGRAM:
// AbstractDemo.java
package sample;
import java.io.*;
abstract class shape
{
float a,b;
abstract void area() throws Exception;
}
class Rectangle extends shape
{
void area() throws Exception
{
DataInputStream d= new DataInputStream(System.in);
System.out.print("Enter the Length of Rectangle:");
a=Float.parseFloat(d.readLine());
System.out.print("Enter the Breadth of Rectangle:");
b=Float.parseFloat(d.readLine());
float ar = a*b;
System.out.println("Area of rectangle = "+ar);
}
}
class Triangle extends shape
{
void area() throws Exception
{
DataInputStream d= new DataInputStream(System.in);
System.out.print("Enter the Breadth of Triangle:");
a=Float.parseFloat(d.readLine());
System.out.print("Enter the Height of Triangle:");
b=Float.parseFloat(d.readLine());
float ar = 0.5f*a*b;
System.out.println("Area of Triangle = "+ar);
}}
class Circle extends shape
{
void area() throws Exception
{
DataInputStream d= new DataInputStream(System.in);
System.out.print("Enter the radius of a Circle:");
a=Float.parseFloat(d.readLine());
float ar = 3.14f*a*a;
System.out.println("Area of Circle = "+ar);
}
}
class AbstractDemo
{
public static void main(String a[]) throws Exception
{
DataInputStream d= new DataInputStream(System.in);
System.out.println("\nArea of Different shapes:\n 1. Rectangle \n 2. Triangle \n 3. Circle\n
Enter Your Choice :");
int ch=Integer.parseInt(d.readLine());
switch(ch)
{
case 1: Rectangle r=new Rectangle();
r.area();
break;
case 2: Triangle t=new Triangle();
t.area();
break;
case 3: Circle c = new Circle();
c.area();
break;
}}}
OUTPUT:
APPLICATIONS:
➢ Large scale programming.
➢ Common interface definition.
➢ Code reusability.
➢ Template method pattern.
➢ Enforcing design constraints.
RESULT:
Thus, the java program for implementing abstract class was successfully developed and
executed.
EX: NO: 5
INTERFACE – IMPLEMENTATION
DATE:
AIM:
To develop a Java program for implementing interface in order to calculate the area of
different shapes.
Application Information: Write a Java Program to create an interface named Shape that contains
two integers and an empty method named printArea(). Provide three classes named Rectangle,
Triangle and Circle such that each one of the classes implements the interface Shape. Each one of
the classes contains only the method area( ) that prints the area of the given shape.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare three different classes for rectangle, triangle and circle.
Step 3: Declare two methods of the same name but with a different number of arguments or
with different data types.
Step 4: Call these methods using objects.
Step 5: Call the corresponding methods as per the number of arguments or their datatypes.
Step 6: Declare an interface by using interface keyword.
Step 7: Display the result.
Step 8: Stop the program.
PROGRAM:
// InterfaceEx.java
import java.io.*;
import java.util.*;
interface shape
{
float a=10, b=20;
void area( );
}
class Rectangle implements shape
{
public void area( )
{
float ar = a*b;
System.out.println("Area of rectangle = "+ar);
}
}
class Triangle implements shape
{
public void area( )
{
float ar = 0.5f*a*b;
System.out.println("Area of Triangle = "+ar);
}
}
class Circle implements shape
{
public void area( )
{
float ar = 3.14f*a*a;
System.out.println("Area of Circle = "+ar);
}
}
class InterfaceEx
{
public static void main(String a[ ])
{
Rectangle r=new Rectangle();
r.area();
Triangle t=new Triangle();
t.area();
Circle c = new Circle();
c.area();
}
}
OUTPUT:
FEATURES / APPLICATIONS:
➢ GUI Framework.
➢ Database Connectivity.
➢ Sorting.
➢ File I/O.
➢ Web Services.
➢ Game Development.
➢ Networking.
RESULT:
Thus, the java program for implementing interface for various shapes and its area
manipulation was successfully developed and executed.
EX: NO: 6
EXCEPTION HANDLING
DATE:
AIM:
To develop a Java program for creating user defined exception and handle it for checking
the eligibility for blood donation.
ALGORITHM:
Step 1: Start the program.
Step 2: Create user-defined exception by extending Exception class.
Step 3: Define a default constructor in your own exception class.
Step 4: Define a parameterized constructor with string as a parameter call superclass constructor.
Step 5: Create an object of user-defined exception class and throw it using throw clause.
Step 6: Display the result.
Step 7: Stop the program.
PROGRAM:
// UserException.java
package sample;
import java.io.DataInputStream;
OUTPUT:
APPLICATIONS:
➢ Error Reporting and Logging.
➢ Input Validation.
➢ File and Database Operations.
➢ Web Development.
➢ Security.
➢ Network Communication.
RESULT:
Thus, the java program for implementing user defined exception was successfully
developed and executed.
EX: NO: 7
MULTITHREADING – IMPLEMENTATION
DATE:
AIM:
To develop a Java program for implementing multiple threads in order to generate
random numbers based on even/odd numbers and calculate square and cube of the
number generated.
ALGORITHM:
Step 1: Start the program.
Step 2: Use built-in Random class for generating the random number.
Step 3: Declare methods for calculating the square and cube of a number upon
satisfying the condition of even or odd number.
Step 4: display the random number along with its square and cube value as output.
Step 5: Stop the program.
PROGRAM:
// MultiThread.java
package sample;
import java.util.*;
class SquareThread extends Thread
{
public int n;
public SquareThread(int no)
{
this.n = no;
System.out.println("Square Thread Started");
start();
}
public void run()
{
System.out.println("The Square of the Random Number " + n + " is "+(n*n));
}
}
class CubeThread extends Thread
{
public int n;
public CubeThread(int no)
{
this.n = no;
System.out.println("Cube Thread Started");
start();
}
public void run()
{ System.out.println("The Cube of the Random Number " + n + " is "+(n*n*n));
}}
class RandThread extends Thread
{public RandThread()
{start();}
public void run()
{
int v = 0;
Random r = new Random();
try
{ for (int i = 1; i<=10; i++) {
v = r.nextInt(100);
System.out.println("Generated Random Number is " + v);
if (v % 2 == 0)
new SquareThread(v);
else
new CubeThread(v);
Thread.sleep(1000); }}
catch (InterruptedException e)
{ System.out.println("Randon Number Thread Interrupted");
}}}
public class MultiThread
{public static void main(String[] args)
{
RandThread r = new RandThread();}}
OUTPUT:
FEATURES / APPLICATIONS:
➢ Responsive User interface.
➢ Server Applications.
➢ Parallel Processing.
➢ I/O Operations.
➢ Gaming.
➢ Resource Management.
RESULT:
Thus, the java program for implementing the concept of mutithreading was
successfully developed and executed.
EX: NO: 8
FILE OPERATIONS
DATE:
AIM:
To develop a Java program for performing various file operations.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a new text file with some information saved in it. Identify the file path to
specify in the code.
Step 3: Until EOF, write the contents to the file created.
Step 4: Display the file information like length, absolute path, contents, read and write
mode status etc and close all the object references created.
Step 5: Stop the program.
PROGRAM:
// FileManip.java
package sample;
import java.io.*;
import java.util.*;
class FileManip
{
public static void main(String[] args)
{
try
{
FileWriter fwrite = new FileWriter("D:/sample.txt");
fwrite.write("This is a Sample File.");
fwrite.close();
System.out.println("Content is successfully written to the File.");
File f1 = new File("D:/sample.txt");
Scanner dataReader = new Scanner(f1);
System.out.println("Read the File contents are:");
while (dataReader.hasNextLine())
{
String fileData = dataReader.nextLine();
System.out.println(fileData);
}
System.out.println("The absolute path of a file:"+f1.getAbsolutePath());
System.out.println("The File Length :"+f1.length());
System.out.println("The File Access Read Mode :"+f1.canRead());
System.out.println("The File Access Write Mode :"+f1.canWrite());
dataReader.close();
}
catch (IOException e)
{
System.out.println("Unexpected error occurred");
e.printStackTrace();
}
}
}
OUTPUT:
FEATURES / APPLICATIONS:
➢ Configuration Management.
➢ Logging.
➢ File uploads and downloads.
➢ Batch Processing.
➢ Report Generation.
➢ E-Commerce.
➢ Caching.
RESULT:
Thus, the java program for implementing the concept of various file operations
was successfully developed and executed.
EX: NO: 9
GENERIC PROGRAMMING
DATE:
AIM:
To develop a Java program for an application development using the concept of
Generic Classes and Generic Methods.
ALGORITHM:
Step 1: Start the program.
Step 2: Define a method of Generic Type for sorting that accepts any data type.
Using built-in Arrays class, sort the values and display the maximum element.
Step 3: Invoke the method defined in the previous step with different type of array
elements.
Step 4: Stop the program.
PROGRAM:
(i) Generic Method
// GenericDemo.java
package sample;
import java.util.*;
class GenericDemo
{
public static < E > void findMax(E[] elements)
{
Arrays.sort(elements);
System.out.println("The Maximum Element is " + elements[elements.length-1]);
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A', 'P','R','O','G','R','A', 'M' };
Double[] doubleArray={1.5,2.5,3.9,22.5,9.0};
findMax( intArray );
findMax( charArray );
findMax(doubleArray);
}}
OUTPUT:
(ii) Generic Class
ALGORITHM:
Step 1: Start the program.
Step 2: Define a class of Generic Type for displaying a value of integer and string.
Step 3: Invoke the constructor of the class with parameter of different types.
Display the values passed through constructor.
Step 4: Stop the program.
// GenericType.java
class GenericType {
public static void main(String[] args) {
// initialize generic class with Integer data
GenericsClass<Integer> intObj = new GenericsClass<>(5);
System.out.println("Generic Class returns: " + intObj.getData());
OUTPUT:
FEATURES / APPLICATIONS:
➢ Code Reusability.
➢ Custom Data Structures.
➢ Design Patterns.
➢ Concurrency Utilities.
➢ JavaFX GUI Programming.
RESULT:
Thus, the java program for implementing the concept of generic class and methods
was successfully developed and executed.
EX: NO: 10
JAVAFX APPLICATION
DATE:
AIM:
To develop a simple menu bar application with New, Open and Save options using
JavaFX controls.
ALGORITHM:
Step 1: Import JavaFX packages and controls needed to develop menu bar
components.
Step 2: Define a class named Main that extends Application.
Step 3: Override the start method, which is the entry point for JavaFX applications.
a. Set the stage title to "Creating MenuBar."
b. Create a Menu named "Menu."
c. Create three menu items: "New," "Open," and "Save."
d. Add the menu items to the menu.
e. Create a label with the initial text "No Menu Item Selected."
f. Define an event handler (event) to handle menu item selections and
update the label text accordingly.
g. Set the event handler for each menu item.
h. Create a MenuBar and add the menu to it.
i. Create a VBox containing the MenuBar and the label.
j. Create a scene with the VBox and set the stage with this scene.
k. Show the stage.
Step 4: Define the main method to launch the JavaFX application.
PROGRAM: //Main.java
package application;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.stage.Stage;
import javafx.*;
import java.time.LocalDate;
public class Main extends Application
{
public void start(Stage s)
{
s.setTitle("Creating MenuBar");
Menu m = new Menu("Menu");
MenuItem m1 = new MenuItem("New");
MenuItem m2 = new MenuItem("Open");
MenuItem m3 = new MenuItem("Save");
m.getItems().add(m1);
m.getItems().add(m2);
m.getItems().add(m3);
Label l = new Label("\t\t\t\t" + "No Menu Item Selected");
EventHandler<ActionEvent> event = new EventHandler<ActionEvent>()
{
public void handle(ActionEvent e)
{
l.setText("\t\t\t\t" + ((MenuItem)e.getSource()).getText() + " Menu Selected");
}
};
m1.setOnAction(event);
m2.setOnAction(event);
m3.setOnAction(event);
MenuBar mb = new MenuBar();
mb.getMenus().add(m);
VBox vb = new VBox(mb, l);
Scene sc = new Scene(vb, 500, 300);
s.setScene(sc);
s.show();
}
public static void main(String args[])
{
launch(args);
}
}
PROCEDURE:
During installation, accept user agreement. “Restart Eclipse now” will be prompted once
installation is completed.
Now goto File → New → choose “Other” option.
Enter Project name and uncheck “Create module-info.java” file and click “Finish”.
To proceed further, download JavaFX SDK from URL: gluonhq.com/products/javafx/
based on the OS compatibility and extract to a location in the system.
JavaFX SDK extraction done to C:\JavaFX.
Eclipse IDE: Select option “Preferences” from “Window” menu.
Now select all the JAR files available within folder “lib” from JavaFX SDK folder extracted
to a location in the previous step.
Selected JAR files will be listed under the user library once the previous step is done.
Select Project folder → Right click → Build Path → Configure Build Path option to be
chosen.
Add Java/JDK/bin path in the Native library location(Edit option) available in the
“Source” tab.
Goto “Arguments” tab and enter vm arguments as “--module-path "C:\Program
Files\openjfx-17.0.9_windows-x64_bin-sdk\javafx-sdk-17.0.9\lib" --add-modules
javafx.controls, javafx.fxml, javafx.graphics”
Goto “Dependencies” tab and select “Modulepath Entries”.
Click on “Finish”.
Select “Run” to start JavaFX application.
RESULT:
Thus, a simple menu bar application using JavaFX controls was successfully
developed and executed.