0% found this document useful (0 votes)
7 views

Oops Lab

It is ver usefull for the college students

Uploaded by

ramdiva7733
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)
7 views

Oops Lab

It is ver usefull for the college students

Uploaded by

ramdiva7733
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/ 39

SOLVE PROBLEMS BY USING SEQUENTIAL SEARCH, BINARY

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:

 Let the element to be search be x.


 Start from the leftmost element of arr[] and one by one compare x with each element
of arr[].
 If x matches with an element then return that index.
 If x doesn’t match with any of elements then return -1.

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;
}

public static void main(String args[])


{
int array[] = { 2, 4, 0, 1, 9 };
int x = 1;
int result = linearSearch(array, x);
if (result == -1)
System.out.print("Element not found");
else
System.out.print("Element found at index: " + result);
}
}
OUTPUT:

Element found at index 3

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:

 Compare x with the middle element.


 If x matches with middle element, we return the mid index.
 Else If x is greater than the mid element, then x can only lie in the right half subarray
after the mid element. So we recur for right half.
 Else (x is smaller) recur for the left half.

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:

Element found at index 1

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:

 Set the first element as minimum.


 Compare minimum with the second element. If the second element is smaller than
minimum, assign the second element as minimum.
 Compare minimum with the third element. Again, if the third element is smaller, then
assign minimum to the third element otherwise do nothing. The process goes on until
the last element.
 After each iteration, minimum is placed in the front of the unsorted list.
 For each iteration, indexing starts from the first unsorted element. Steps 1 to 3 are
repeated until all the elements are placed at their correct positions.

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:

Sorted Array in Ascending Order:


[2,10,12,15,20]

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:

Sorted Array in Ascending Order:


[1,3,4,5,9]

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

DATE - CLASSES AND OBJECTS

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];
}

static void queueEnqueue(int item)


{
if (capacity == rear) {
System.out.printf("\nQueue is full\n");
return;
}

else
{
queue[rear] = item;
rear++;
}
return;
}

static void queueDequeue()


{
if (front == rear)
{
System.out.printf("\nQueue 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;
}
static void queueDisplay()
{
int i;
if (front == rear)
{
System.out.printf("Queue is Empty\n");
return;
}
for (i = front; i < rear; i++)
{
System.out.printf(" %d = ", queue[i]);
}
return;
}
static 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 Main


{
public static void main(String[] args)
{
Queue q = new Queue(4);
System.out.println("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 two dequeue operations:");
q.queueDisplay();
q.queueFront();
}
}
OUTPUT:

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

D:\Java Programs>javac Shapeclass.java


D:\Java Programs>java Shapeclass
Enter the length and breadth of rectangle:
2
3
Length of rectangle: 2 breadth of rectangle: 3
The area of rectangle is:6
Enter the base and height of triangle:
5
6
Base of triangle: 5 height of triangle: 6
The area of triangle is: 15.0
Enter the radius of circle
4
Radius of circle: 4
The area of circle is:50.24

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:

1. Import the java packages.


2. Create an Interface named Area that contains two integers and an method named
Compute().
3. Create a class Rectangle that implements Area. then compute the area and prints the area
of the Rectangle.
4. Create a class Triangle that implements the class Area. then compute the area and prints
the area of the Triangle.
5. Create a class Circle that implenets the class Area. then compute the area and prints the
area of the Circle.
6. Create object for a class in memory and assign it to the reference variable, then the method
is invoked.

PROGRAM:

public interface Area


{
double Compute(double a, double b);
}
class Rectangle implements Area
{
public double Compute(double l, double b)
{
return (l*b);
}
}
class Triangle implements Area
{
public double Compute(double b, double h)
{
return (b*h/2);
}
}
class Circle implements Area
{
public double Compute(double x,double y)
{
double pi=3.14;
return(pi*x*x);
}
}
public class MainArea
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
double RArea = rect.Compute(10, 20);
System.out.println("The area of the Rectangle is "+RArea);
Triangle tri = new Triangle();
double TArea = tri.Compute(10, 20);
System.out.println("The area of the triangle is "+TArea);
Circle cir = new Circle();
double CArea = cir.Compute(15, 15);
System.out.println("The area of the Circle is "+CArea);
}
}
OUTPUT:

The area of the Rectangle is 200.0


The area of the triangle is 100.0
The area of the Circle is 706.5

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:

D:\>Java Prgs>javac genericdemo.java


D:\>Java Prgs>java genericdemo
Max value in inums: 10
Max value in inums: 1
Max value in chs: v
Max value in chs: a
Max value in chs: 88.3
Max value in chs: 10.4

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.

3. Import menu package from javafx.scene.MenuBar.

4. Create menu and cerate menu items add the menu items to menu bar.

5. Launch the application and display the output.

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;

public class JavaFXApplicationMenu extends Application {

@Override

public void start(Stage stage) {

// Create MenuBar

MenuBar menuBar = new MenuBar();

// Create menus

Menu fileMenu = new Menu("File");

Menu editMenu = new Menu("Edit");

Menu helpMenu = new Menu("Help");


// Create MenuItems

MenuItem newItem = new MenuItem("New");

MenuItem openFileItem = new MenuItem("Open File");

MenuItem exitItem = new MenuItem("Exit");

MenuItem copyItem = new MenuItem("Copy");

MenuItem pasteItem = new MenuItem("Paste");

// Add menuItems to the Menus

fileMenu.getItems().addAll(newItem, openFileItem, exitItem);

editMenu.getItems().addAll(copyItem, pasteItem);

// Add Menus to the MenuBar

menuBar.getMenus().addAll(fileMenu, editMenu, helpMenu);

BorderPane root = new BorderPane();

root.setTop(menuBar);

Scene scene = new Scene(root, 350, 200);

stage.setTitle("JavaFX Menu (o7planning.org)");

stage.setScene(scene);

stage.show();

public static void main(String[] args)

Application.launch(args);

}
OUTPUT:

RESULT:

Thus the implementation for JavaFX control, layout, menu program is executed
successfully.

You might also like