Oops Lab
Oops Lab
EX.NO. - 1
SEARCH, AND QUADRATIC SORTING ALGORITHMS
DATE - (SELECTION, INSERTION)
SEQUENTIAL SEARCH
AIM:
To write a Java Program to implement Linear or Sequential Search.
ALGORITHM:
PROGRAM:
class LinearSearch
{
public static int linearSearch(int array[], int x)
{
int n = array.length;
for (int i = 0; i < n; i++)
{
if (array[i] == x)
return i;
}
return -1;
}
RESULT:
Thus the Java program to implement Linear Search has been successfully executed
and the Output is verified.
BINARY SEARCH
AIM:
To write a Java Program to implement Binary Search.
ALGORITHM:
PROGRAM:
class BinarySearch
{
int binarySearch(int array[], int x, int low, int high)
{
while (low <= high)
{
int mid = low + (high - low) / 2;
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
public static void main(String args[])
{
BinarySearch ob = new BinarySearch();
int array[] = { 3, 4, 5, 6, 7, 8, 9 };
int n = array.length;
int x = 4;
int result = ob.binarySearch(array, x, 0, n - 1);
if (result == -1)
System.out.println("Not found");
else
System.out.println("Element found at index " + result);
}
}
OUTPUT:
RESULT:
Thus the Java program to implement Binary Search has been successfully executed
and the Output is verified.
SELECTION SORT
AIM:
To write a Java Program to implement Selection Sort.
ALGORITHM:
PROGRAM:
import java.util.Arrays;
class SelectionSort
{
void selectionSort(int array[])
{
int size = array.length;
for (int step = 0; step < size - 1; step++)
{
int min_idx = step;
for (int i = step + 1; i < size; i++)
{
if (array[i] < array[min_idx])
{
min_idx = i;
}
}
int temp = array[step];
array[step] = array[min_idx];
array[min_idx] = temp;
}
}
public static void main(String args[])
{
int[] data = { 20, 12, 10, 15, 2 };
SelectionSort ss = new SelectionSort();
ss.selectionSort(data);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}
}
OUTPUT:
RESULT:
Thus the Java program to implement Selection Sort has been successfully executed
and the Output is verified.
INSERTION SORT
AIM:
To write a Java Program to implement Insertion Sort.
ALGORITHM:
The first element in the array is assumed to be sorted. Take the second element and
store it separately in key.
Compare key with the first element. If the first element is greater than key, then key is
placed in front of the first element.
Now, the first two elements are sorted.
Take the third element and compare it with the elements on the left of it. Placed it just
behind the element smaller than it. If there is no element smaller than it, then place it
at the beginning of the array.
Similarly, place every unsorted element at its correct position.
PROGRAM:
import java.util.Arrays;
class InsertionSort
{
void insertionSort(int array[])
{
int size = array.length;
for (int step = 1; step < size; step++)
{
int key = array[step];
int j = step - 1;
while (j >= 0 && key < array[j])
{
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
public static void main(String args[])
{
int[] data = { 9, 5, 1, 4, 3 };
InsertionSort is = new InsertionSort();
is.insertionSort(data);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}}
OUTPUT:
RESULT:
Thus the Java program to implement Insertion Sort has been successfully executed
and the Output is verified.
EX.NO. - 2 DEVELOP STACK AND QUEUE DATA STRUCTURES USING
STACK IMPLEMENTATION:
AIM:
To write a Java Program to implement Stack Data Structures.
ALGORITHM:
The class supports one default constructor Stack() which is used to create an empty
stack..
In order to create a stack, we must import java.util.stack package and use the Stack()
constructor of this class. The below example creates an empty Stack.
In order to add an element to the stack, we can use the push() method. This push()
operation place the element at the top of the stack.
To retrieve or fetch the first element of the Stack or the element present at the top of
the Stack, we can use peek() method. The element retrieved does not get deleted or
removed from the Stack.
To pop an element from the stack, we can use the pop() method. The element is
popped from the top of the stack and is removed from the same.
PROGRAM:
class Stack
{
private int arr[];
private int top;
private int capacity;
Stack(int size)
{
arr = new int[size];
capacity = size;
top = -1;
}
public void push(int x)
{
if (isFull())
{
System.out.println("Stack OverFlow");
System.exit(1);
}
System.out.println("Inserting " + x);
arr[++top] = x;
}
public int pop()
{
if (isEmpty())
{
System.out.println("STACK EMPTY");
System.exit(1);
}
return arr[top--];
}
public int getSize()
{
return top + 1;
}
public Boolean isEmpty()
{
return top == -1;
}
public Boolean isFull()
{
return top == capacity - 1;
}
public void printStack()
{
for (int i = 0; i <= top; i++)
{
System.out.print(arr[i] + ", ");
}
}
public static void main(String[] args)
{
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.print("Stack: ");
stack.printStack();
stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();
}
}
OUTPUT:
Inserting 1
Inserting 2
Inserting 3
Stack: 1, 2, 3,
After popping out
1, 2,
RESULT:
Thus the Java program to implement Stack Data Structures has been successfully
executed and the Output is verified.
QUEUE IMPLEMENTATION:
AIM:
To write a Java Program to implement Queue Data Structures.
ALGORITHM:
A Queue class extends Collection interface and it supports the insert and removes
operations using a first-in-first-out (FIFO).
A Stack is a subclass of Vector class and it represents last-in-first-out (LIFO) stack of
objects.
The last element added at the top of the stack (In) can be the first element to be
removed (Out) from the stack.
We can also implement a Queue using Stack in the below program.
PROGRAM:
class Queue {
private static int front, rear, capacity;
private static int queue[];
Queue(int size) {
front = rear = 0;
capacity = size;
queue = new int[capacity];
}
else
{
queue[rear] = item;
rear++;
}
return;
}
else
{
for (int i = 0; i < rear - 1; i++)
{
queue[i] = queue[i + 1];
}
Queue is Empty
Queue after Enqueue Operation:
10 = 30 = 50 = 70 =
Front Element of the queue: 10
Queue is full
10 = 30 = 50 = 70 =
Queue after two dequeue operations: 50 = 70 =
Front Element of the queue: 50
RESULT:
Thus the Java program to implement Queue Data Structures has been successfully
executed and the Output is verified.
EX.NO. - 4
ABSTRACT CLASS IMPLEMENTATION
DATE -
AIM
To write a Java program to calculate the area of rectangle, circle and triangle using the
concept of abstract class.
ALGORITHM:
1. Start
2. Create an abstract class named shape that contains two integers and an empty method
named printarea().
3. Provide three classes named rectangle, triangle and circle such that each one of the
classes
extends the class Shape.
4. Each of the inherited class from shape class should provide the implementation for the
method printarea().
5. Get the input and calculate the area of rectangle, circle and triangle.
6. In the shapeclass, create the objects for the three inherited classes and invoke the
methods and Display the area values of the different shapes.
7. Stop.
PROGRAM
Shapeclass.java
import java.util.*;
abstract class shape
{
int a,b;
abstract public void printarea();
}
class rectangle extends shape
{
public int area_rect;
public void printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the length and breadth of rectangle");
a=s.nextInt();
b=s.nextInt();
area_rect=a*b;
System.out.println("Length of rectangle: "+a +"breadth of rectangle: "+b);
System.out.println("The area of rectangle is:"+area_rect);
}
}
class triangle extends shape
{
double area_tri;
public void printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the base and height of triangle:");
a=s.nextInt();
b=s.nextInt();
System.out.println("Base of triangle: "+a +"height of triangle: "+b);
area_tri=(0.5*a*b);
System.out.println("The area of triangle is:"+area_tri);
}
}
class circle extends shape
{
double area_circle;
public void printarea()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the radius of circle:");
a=s.nextInt();
area_circle=(3.14*a*a);
System.out.println("Radius of circle:"+a);
System.out.println("The area of circle is:"+area_circle);
}
}
public class Shapeclass
{
public static void main(String[] args)
{
rectangle r=new rectangle();
r.printarea();
triangle t=new triangle();
t.printarea();
circle r1=new circle();
r1.printarea();
}
}
OUTPUT
RESULT
Thus the Java program for calculate the area of rectangle, circle and triangle was
implemented and executed successfully.
EX.NO. - 5
CIRCLE, RECTANGLE, TRIANGLE AREA CALCULATION USING
DATE - INTERFACE
AIM:
To develop Java program Shape Area Calculation Using Interface.
ALGORITHM:
PROGRAM:
RESULT:
Thus the Implementation of different shape area calculated using Interface program is
executed successfully.
EX.NO. - 6
IMPLEMENT EXCEPTION HANDLING AND CREATION OF USER
DATE - DEFINED EXCEPTIONS.
AIM:
To write a Java program to implement user defined exception handling.
ALGORITHM:
1. Start
2. Create a class NegativeAmtException which extends Exception class.
3. Create a constructor which receives the string as argument.
4. Get the Amount as input from the user.
5. If the amount is negative, the exception will be generated.
6. Using the exception handling mechanism , the thrown exception is handled by the
catch construct.
7. After the exception is handled , the string “invalid amount “ will be displayed.
8. If the amount is greater than 0, the message “Amount Deposited “ will be displayed
9. Stop.
PROGRAM 1:
userdefined.java
import java.util.*;
class NegativeAmtException extends Exception
{
String msg;
NegativeAmtException(String msg)
{
this.msg=msg;
}
public String toString()
{
return msg;
}
}
public class userdefined
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Amount:");
int a=s.nextInt();
try
{
if(a<0)
{
throw new NegativeAmtException("Invalid Amount");
}
System.out.println("Amount Deposited");
}
catch(NegativeAmtException e)
{
System.out.println(e);
}
}
}
OUTPUT
PROGRAM 2:
example.java
class MyException extends Exception
{
String str1;
MyException(String str2)
{
str1=str2;
}
public String toString()
{
return ("MyException Occurred: "+str1) ;
}
}
class example
{
public static void main(String args[])
{
try
{
System.out.println("Starting of try block");
throw new MyException("This is My error Message");
}
catch(MyException exp)
{
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
OUTPUT
RESULT
Thus the Java program to implement user defined exception handling has been
implemented and executed successfully.
EX.NO. - 7
MULTITHREADING IMPLEMENTATION
DATE -
AIM:
To write a java program that implements a multi-threaded application.
ALGORITHM:
1. Start
2. Create a class even which implements first thread that computes the square of the
number .
3. run() method implements the code to be executed when thread gets executed.
4. Create a class odd which implements second thread that computes the cube of the
number.
5. Create a third thread that generates random number. If the random number is even, it
displays the square of the number. If the random number generated is odd, it displays the
cube of the given number.
6. The Multithreading is performed and the task switched between multiple threads.
7. The sleep () method makes the thread to suspend for the specified time.
8. Stop.
PROGRAM:
multithreadprog.java
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
{
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 multithreadprog
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}
OUTPUT:
RESULT:
Thus the Java program for multi-threaded application has been implemented and
executed Successfully.
EX.NO. - 8
FILE OPERATIONS
DATE -
AIM:
To write a java program that reads a file name from the user, displays information
about whether the file exists, whether the file is readable, or writable, the type of file and the
length of the File in bytes.
ALGORITHM:
1. Start
2. Create a class filedemo. Get the file name from the user.
3. Use the file functions and display the information about the file.
4. getName() displays the name of the file.
5. getPath() diplays the path name of the file.
6. getParent () -This method returns the pathname string of this abstract pathname’s
parent, or
7. null if this pathname does not name a parent directory.
8. exists() – Checks whether the file exists or not.
9. canRead()-This method is basically a check if the file can be read.
10. canWrite()-verifies whether the application can write to the file.
11. isDirectory() – displays whether it is a directory or not.
12. isFile() – displays whether it is a file or not.
13. lastmodified() – displays the last modified information.
14. length()- displays the size of the file.
15. delete() – deletes the file
16. Invoke the predefined functions to display the information about the file.
17. Stop.
PROGRAM:
filedemo.java
import java.io.*;
import java.util.*;
class filedemo
{
public static void main(String args[])
{
String filename;
Scanner s=new Scanner(System.in);
System.out.println("Enter the file name ");
filename=s.nextLine();
File f1=new File(filename);
System.out.println("******************");
System.out.println("FILE INFORMATION");
System.out.println("******************");
System.out.println("NAME OF THE FILE "+f1.getName());
System.out.println("PATH OF THE FILE "+f1.getPath());
System.out.println("PARENT"+f1.getParent());
if(f1.exists())
System.out.println("THE FILE EXISTS ");
else
System.out.println("THE FILE DOES NOT ExISTS ");
if(f1.canRead())
System.out.println("THE FILE CAN BE READ ");
else
System.out.println("THE FILE CANNOT BE READ ");
if(f1.canWrite())
System.out.println("WRITE OPERATION IS PERMITTED");
else
System.out.println("WRITE OPERATION IS NOT PERMITTED");
if(f1.isDirectory())
System.out.println("IT IS A DIRECTORY ");
else
System.out.println("NOT A DIRECTORY");
if(f1.isFile())
System.out.println("IT IS A FILE ");
else
System.out.println("NOT A FILE");
System.out.println("File last modified "+ f1.lastModified());
System.out.println("LENGTH OF THE FILE "+f1.length());
System.out.println("FILE DELETED "+f1.delete());
}
}
OUTPUT
RESULT:
Thus the java program to display file information has been implemented and executed
Successfully.
EX.NO. - 9
GENERIC FUNCTION IMPLEMENTATION
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
2. Create a class Myclass to implement generic class and generic methods.
3. Get the set of the values belonging to specific data type.
4. Create the objects of the class to hold integer, character and double values.
5. Create the method to compare the values and find the maximum value stored in the
array.
6. Invoke the method with integer, character or double values. The output will be
displayed
based on the data type passed to the method.
7. Stop.
PROGRAM:
genericdemo.java
class MyClass<T extends Comparable<T>>
{
T[] vals;
MyClass(T[] o)
{
vals = o;
}
public T min()
{
T v = vals[0];
for(int i=1; i < 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 genericdemo
{
public static void main(String args[]) {
int i;
Integer inums[]={10,2,5,4,6,1};
Character chs[]={'v','p','s','a','n','h'};
Double d[]={20.2,45.4,71.6,88.3,54.6,10.4};
MyClass<Integer> iob = new MyClass<Integer>(inums);
MyClass<Character> cob = new MyClass<Character>(chs);
MyClass<Double>dob = new MyClass<Double>(d);
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 chs: " + dob.max());
System.out.println("Min value in chs: " + dob.min());
}
}
OUTPUT:
RESULT:
Thus the Java program to find the maximum value from the given type of elements
has been Implemented using generics and executed successfully.
EX.NO. - 10
DEVELOP APPLICATIONS USING JAVAFX CONTROLS,
DATE - LAYOUTS AND MENUS
AIM:
To develop Java program for creating controls, layouts and menus using JavaFX.
ALGORITHM:
1. Open new JavaFX New Application and save file name as JavaFXMenuSample
2. Import Supporting packages into program and extends javafx application object
Application.
4. Create menu and cerate menu items add the menu items to menu bar.
PROGRAM:
package javafxapplicationmenu;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
@Override
// Create MenuBar
// Create menus
editMenu.getItems().addAll(copyItem, pasteItem);
root.setTop(menuBar);
stage.setScene(scene);
stage.show();
Application.launch(args);
}
OUTPUT:
RESULT:
Thus the implementation for JavaFX control, layout, menu program is executed
successfully.