CS3381 Oop Manual Cse
CS3381 Oop Manual Cse
CONTENTS
Ex. Page
No. Name of the Exercise
No.
Sequential Search, Binary Search, And Quadratic Sorting
1 (Insertion and Selection)
7 Multithreading Implementation
8 File Handling
11 Mini Project
SEQUENTIAL SEARCH, BINARY SEARCH, AND QUADRATIC
SORTING
EX.NO:1.A) SEQUENTIAL SEARCH
Aim:
To write a java program and execute to solve problems by using sequential search.
Algorithm:
Step 1:Start the program
Step 2: Traverse the array
Step 3: Match the key element with array element
Step 4: If key element is found, return the index position of the array element
Step 5: If key element is not found, return -1
Step 6:Stop the program
Program:
public class LinearSearchExample{
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
System.out.println(key+" is found at index: "+linearSearch(a1, key));
}
}
Output:
D:\ >javac LinearSearchExample.java
50 IS FOUND AT INDEX:3
EX.NO:1.B) BINARY SEARCH
AIM:
To write a java program and execute to solve problems by using binary search.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the upper limit of the array as n
Step 3: Setup for loop from i=1 until i<n increment i
Step 4: Read element to array[]
Step 5: Read element to be searched in the array as search
Step 6: Assign first=0,last=n-1
Step 7: Repeat step 8 to 9 until (first<=last)
Step 8: middle=(first+last)/2
Step 9: if(search<a[middle])
True: n=middle=1
False : if(search>a[middle])
True:first=middle+1
False: found the element in middle+1 position
Step 10: Stop the program.
PROGRAM:
class BinarySearchExample{
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}
OUTPUT:
EX.NO:1.C.i) INSERTION SORT
AIM:
To write a java program and execute to solve quadratic sorting by using insertion.
ALGORITHM:
Step 1: Start the program.
Step 2: The second element of an array is compared with the elements that
appears before it (only first element in this case). If the second element is
smaller than first element, second element is inserted in the position of
first element. After first step, first two elements of an array will be sorted.
Step 3: The third element of an array is compared with the elements that appears
before it (first and second element). If third element is smaller than first
element, it is inserted in the position of first element. If third element is
larger than first element but, smaller than second element, it is inserted in
the position of second element. If third element is larger than both the
elements, it is kept in the position as it is. After second step, first three
elements of an array will be sorted.
Step 3: Similarly, the fourth element of an array is compared with the elements
that appears before it (first, second and third element) and the same
procedure is applied and that element is inserted in the proper position.
After third step, first four elements of an array will be sorted.
Step 4: If there are n elements to be sorted. Then, this procedure is repeated n-
1 times to get sorted list of array
Step 5: Stop the program
PROGRAM:
public class InsertionSortExample {
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}
public static void main(String a[]){
int[] arr1 = {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:
RESULT:
Thus the program is compiled and executed successfully.
EX.NO:1.C.ii) SELECTION SORT
AIM:
To write a java program and execute to solve quadratic sorting by using selection.
ALGORITHM:
PROGRAM:
selectionSort(arr1);
System.out.println("After Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
}
}
Before Selection Sort
9 14 3 2 43 11 58 22
OUTPUT
Sorted array:
11 12 22 25 64Sort
2 3 9 11 14 22 43 5
RESULT:
Thus the program is compiled and executed successfully.
EX.NO:2.A) TO IMPLEMENT STACK DATA STRUCTURES
AIM:
To implement stack data structures by using java program.
ALGORITHM:
Step 1: Start the program.
Step 2: For Push operation, check for stack overflow
Step 3: If Top>=N then print stack overflow else increment Top and insert the
element.
Step 4: For Pop operation, check for underflow of the stack.
Step 5: If Top=0 then print stack underflow else decrement Top and delete the
element
Step 6: Stop the program.
PROGRAM
import java.util.Scanner;
class Stack
{
int top;
int maxsize = 10;
int[] arr = new int[maxsize];
boolean isEmpty()
{
return (top < 0);
}
Stack()
{
top = -1;
}
boolean push (Scanner sc)
{
if(top == maxsize-1)
{
System.out.println("Overflow !!");
return false;
}
else
{
System.out.println("Enter Value");
int val = sc.nextInt();
top++;
arr[top]=val;
System.out.println("Item pushed");
return true;
}
}
boolean pop ()
{
if (top == -1)
{
System.out.println("Underflow !!");
return false;
}
else
{
top --;
System.out.println("Item popped");
return true;
}
}
void display ()
{
System.out.println("Printing stack elements .....");
for(int i = top; i>=0;i--)
{
System.out.println(arr[i]);
}
}
}
public class Stack_Operations {
public static void main(String[] args) {
int choice=0;
Scanner sc = new Scanner(System.in);
Stack s = new Stack();
System.out.println("*********Stack operations using array*********\n");
System.out.println("\n------------------------------------------------\n");
while(choice != 4)
{
System.out.println("\nChose one from the below options...\n");
System.out.println("\n1.Push\n2.Pop\n3.Show\n4.Exit");
System.out.println("\n Enter your choice \n");
choice = sc.nextInt();
switch(choice)
{
case 1:
{
s.push(sc);
break;
}
case 2:
{
s.pop();
break;
}
case 3:
{
s.display();
break;
}
case 4:
{
System.out.println("Exiting....");
System.exit(0);
break;
}
default:
{
System.out.println("Please Enter valid choice ");
}
};
} } }
OUTPUT:
AIM:
To implement queue data structures by using java program.
ALGORITHM:
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 QueueArrayImplementation {
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:
Initial Queue:
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 program is compiled and executed successfully.
EX NO 3: EMPLOYEE DETAILS
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 write a java program to get a employee details and to generate pay slips for the
employees with their gross and net salary.
ALGORITHM:
Step1: start the program.
Step 2: Create a class called Employee withEmp_name, Emp_id, Address, Mail_id,
Mobile_no as membersand compute the payslip
Step 3:.Extends the Employee class for further classes calledProgrammer, Assistant
Professor, AssociateProfessor and Professor
Step 4:Create class called Pay slip and generate Pay slip according to the position of the
Employee.
Step 5: End the program.
PROGRAM:
import java.util.Scanner;
class Employee{
String Emp_name;
int Emp_id;
String Address;
String Mail_id;
int Mobile_no;
void display(){
System.out.println(Emp_name);
//Syetem.out.println(Address);
System.out.println(Emp_id);
System.out.println(Mail_id);
System.out.println(Mobile_no);
} }
class Programmer extends Employee{
int BP;
/*int DA= (int) (0.97*BP);
HRA=(int) (0.10*BP);
PF=(int) (0.12*BP); */
void display(){
System.out.println(BP);
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP);
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD FUND"+0.001*BP);
} }
class Assistant_Professor extends Employee{
int BP;
void display(){
System.out.println(BP);
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP);
System.out.println("PF"+0.12*BP);
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP);
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD FUND"+0.001*BP);
} }
class Professor extends Employee{
int BP;
void display(){
System.out.println(BP);
System.out.println("DA"+0.97*BP);
System.out.println("HRA"+0.10*BP);
System.out.println("PF"+0.12*BP);
System.out.println("SATFF CLUD FUND"+0.001*BP);
}}
class Main{
public static void main(String args[]){
System.out.println("\n
1.Programmer\n2.Assistant_Professor\n3.Associate_Professor\n4.Professor");
Scanner input=new Scanner(System.in);
System.out.print("Enter an integer: ");
int ch=input.nextInt();
switch (ch) {
case 1:
e1.Mobile_no=2345678;
p1.BP=15000;
p1.display();
e1.display();
break;
case 2:
p2.BP=30000;
p2.display();
e2.display();
break;
case 3:
Employee e3=new Employee();
Associate_Professor p3=new Associate_Professor();
e3.Emp_name="GHF";
e3.Address="B-city";
e3.Mail_id="MAIN@gmail.com";
e3.Emp_id=456;
e3.Mobile_no=98710;
p3.BP=30000;
p3.display();
e3.display();
break;
case 4:
Employee e4=new Employee();
Professor p4=new Professor();
e4.Emp_name="KANNAN";
e4.Address="TRICHY";
e4.Mail_id="kanna@gmail.com";
e4.Emp_id=789;
e4.Mobile_no=9810;
p4.BP=30000;
p4.display();
e4.display();
break;
case 5:
//exit(1);
default:
System.out.println("enter correct choice");
} }
}
OUTPUT:
1.Programmer
2.Assistant_Professor
3.Associate_Professor
4.Professor
Enter an integer: 1
15000
DA14550.0
HRA1500.0
PF1800.0
ABC
567
praw@gmail.com
2345678
RESULT:
Thus the program is compiled and executed successfully.
EX.NO:4 ABSTRACT CLASSES
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 classes contain only the method printArea() that prints the
area of the given shape.
AIM:
To write a java program to creagte an abstract class and print the area of given three
shapes.
ALGORITHM:
Step 1:Start the program.
Step 2:Create a abstract class named as shape and get the values for rectangle,circle and
triangle.
Step3: Extends the main class as Abstractddemo for further to calculate the values by
method.
Step: Print the values.
Step: End of the program
PROGRAM
import java.util.*;
abstract class shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
System.out.println("Area of circle is :"+(3.14*x*x));
}
}
class Triangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of triangle is :"+(0.5*x*y));
}
}
public class AbstactDDemo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.area(2,5);
Circle c=new Circle();
c.area(5,5);
Triangle t=new Triangle();
t.area(2,5);
}
}
OUTPUT:
Area of rectangle is :10.0
Area of circle is :78.5
Area of triangle is :5.0
RESULT:
Thus the program is compiled and executed successfully.
EX.NO:5 STACK ADT IMPLEMENTATION USING INHERITANCE
AIM:
ALGORITHM
STEP 1.Start
STEP 2.Create the interface Stackoperation with method declarations for push and pop.
STEP 3.Create the class Astack which implements the interface and provides implementation
for the methods push and pop. Also define the method for displaying the values
stored in the stack. Handle the stack overflow and stack underflow condition.
STEP 4.Create the class teststack. Get the choice from the user for the operation to be
performed and also handle the exception that occur while performing the stack
operation.
STEP 5.Create the object and invoke the method for push, pop, display based on the input
from the user.
STEP 6.Stop.
PROGRAM
import java.io.*;
interface Mystack
{
public void pop();
public void push();
public void display();
}
class Stack_array implements Mystack
{
final static int n=5;
int stack[]=new int[n];
int top=-1;
public void push()
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
if(top==(n-1))
{
System.out.println(" Stack Overflow");
return;
}
else
{
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
stack[++top]=ele;
}
}
catch(IOException e)
{
System.out.println("e");
}
}
public void pop()
{
if(top<0)
{
System.out.println("Stack underflow");
return;
}
else
{
int popper=stack[top];
top--;
System.out.println("Popped element:" +popper);
}
}
public void display()
{
if(top<0)
{
System.out.println("Stack is empty");
return;
}
else
{
String str=" ";
for(int i=0; i<=top; i++)
str=str+" "+stack[i]+" <--";
System.out.println("Elements are:"+str);
}
}
}
class Link
{
public int data;
public Link nextLink;
public Link(int d)
{
data= d;
nextLink=null;
}
public void printLink()
{
System.out.print(" --> "+data);
}
}
class Stack_List implements Mystack
{
private Link first;
public Stack_List()
{
first = null;
}
public boolean isEmpty()
{
return first == null;
}
public void push()
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
Link link = new Link(ele);
link.nextLink = first;
first = link;
}
catch(IOException e)
{
System.err.println(e);
}
}
public Link delete()
{
Link temp = first;
try
{
first = first.nextLink;
}
catch(NullPointerException e)
{
throw e;
}
return temp;
}
public void pop()
{
try
{
Link deletedLink = delete();
System.out.println("Popped: "+deletedLink.data);
}
catch(NullPointerException e)
{
throw e;
}
}
public void display()
{
if(first==null)
System.out.println("Stack is empty");
else
{
Link currentLink = first;
System.out.print("Elements are: ");
while(currentLink != null)
{
currentLink.printLink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
}
}
class StackADT
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Implementation of Stack using Array");
Stack_array stk=new Stack_array();
int ch=0;
do
{
System.out.println("1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
stk.push();
break;
case 2:
stk.pop();
break;
case 3:
stk.display();
break;
case 4:
System.exit(0);
}
}
while(ch<5);
System.out.println("Implementation of Stack using Linked List");
Stack_List stk1=new Stack_List();
ch=0;
do
{
System.out.println("1.Push 2.Pop 3.Display 4.Exit");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
stk1.push();
break;
case 2:
try
{
stk1.pop();
}
catch(NullPointerException e)
{
System.out.println("Stack underflown");
}
break;
case 3:
stk1.display();
break;
default:
System.exit(0);
}
}
while(ch<5);
}
}
OUTPUT
ARRAY STACK
ARRAY STACK
ARRAY STACK
Element: 10
Element: 20
Element: 30
ARRAY STACK
Element popped: 30
ARRAY STACK
RESULT
Thus the Java application for ADT stack operations has been implemented and executed
successfully.
EX.NO:6 USER DEFINED EXCEPTION HANDLING IMPLEMENTATION
AIM
ALGORITHM:
STEP 1. Start
STEP 6. Using the exception handling mechanism , the thrown exception is handled by
the catch construct.
STEP 7. After the exception is handled , the string “invalid amount “ will be displayed.
STEP 8. If the amount is greater than 0, the message “Amount Deposited “ will be
displayed
STEP 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
RESULT
Thus the Java program to implement user defined exception handling has been
implemented and executed successfully.
EX.NO:7 MULTITHREADING IMPLEMENTATION
AIM
To write a java program that implements a multi-threaded application.
ALGORITHM:
STEP 1. Start
STEP 2. Create a class even which implements first thread that computes the square of the
number.
STEP 3. run() method implements the code to be executed when thread gets executed.
STEP 4. Create a class odd which implements second thread that computes the cube of the
number.
STEP 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.
STEP 6. The Multithreading is performed and the task switched between multiple threads.
STEP 7. The sleep () method makes the thread to suspend for the specified time.
STEP 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 HANDLING
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:
STEP 1. Start
STEP 2. Create a class filedemo. Get the file name from the user.
STEP 3. Use the file functions and display the information about the file.
STEP 6. getParent () -This method returns the pathname string of this abstract
pathname’s parent
STEP 10. canWrite()-verifies whether the application can write to the file.
STEP 16. Invoke the predefined functions to display the information about the file.
filedemo.java
AIM
To write a java program to find the maximum value from the given type of elements
using a generic function.
ALGORITHM:
STEP 1. Start
STEP 2. Create a class Myclass to implement generic class and generic methods.
STEP 3. Get the set of the 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 method to compare the values and find the maximum value stored in
the array.
STEP 6. Invoke the method with integer, character or double values. The output will be
displayed based on the data type passed to the method.
STEP 7. Stop.
PROGRAM
genericdemo.java