0% found this document useful (0 votes)
79 views52 pages

CS3381 Oop Manual Cse

This document contains the contents and exercises for an Object Oriented Programming laboratory course. The exercises cover topics like sequential, binary, and quadratic sorting algorithms; stack and queue data structures implemented with classes and objects; inheritance for pay slip generation; abstract classes; multiple inheritance with interfaces for stack implementation; exception handling; multithreading; file handling; generic functions; and JavaFX controls, layouts, and menus. It also includes code snippets for implementing sequential search, binary search, insertion sort, selection sort, and stacks using a class with push and pop methods.
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)
79 views52 pages

CS3381 Oop Manual Cse

This document contains the contents and exercises for an Object Oriented Programming laboratory course. The exercises cover topics like sequential, binary, and quadratic sorting algorithms; stack and queue data structures implemented with classes and objects; inheritance for pay slip generation; abstract classes; multiple inheritance with interfaces for stack implementation; exception handling; multithreading; file handling; generic functions; and JavaFX controls, layouts, and menus. It also includes code snippets for implementing sequential search, binary search, insertion sort, selection sort, and stacks using a class with push and pop methods.
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/ 52

CS8383-OBJECT ORIENTED PROGRAMMING LABORATORY

CONTENTS

Ex. Page
No. Name of the Exercise
No.
Sequential Search, Binary Search, And Quadratic Sorting
1 (Insertion and Selection)

stack and queue data structures using classes and


2
objects

3 Pay slip Generation using Inheritance

4 Abstract Class Implementation

Stack ADT Implementation using Multiple Inheritance


5 (Interface)

6 User Defined Exception Handling Implementation

7 Multithreading Implementation

8 File Handling

9 Generic Function Implementation

10 JavaFX controls, layouts and menus.

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

D:\ >java LinearSearchExample

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:

Step 1: Start the program.


Step 2: Selection sort algorithm starts by comparing first two elements of an array
and swapping if necessary.
Step 3: If you want to sort the elements of array in ascending order and if the first
element is greater than second then, you need to swap the elements.
Step4:But, if the first element is smaller than second, leave the elements as it
Step 5: Then, again first element and third element are compared and swapped if
necessary.
Step 6: This process goes on until first and last element of an array is compared.
This completes the first step of selection sort.
Step 7:If there are n elements to be sorted then, the process mentioned above
should be repeated n-1 times to get required result.
Step 8: Stop the program.

PROGRAM:

public class SelectionSortExample {


public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
public static void main(String a[])
{
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();

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:

Is the stack empty? true


Elements in Stack: [78, 113, 90, 120]
Is the stack empty? false
2.B)TO IMPLEMENT QUEUE DATA STRUCTURES USING JAVA PROGRAM

AIM:
To implement queue data structures by using java program.

ALGORITHM:

Step 1: Start the program.


Step 2: For queue insertion operation, check for queue overflow
Step 3: If R>=N then print queue overflow else increment rear pointer and insert
the element.
Step 4: For queue deletion operation, check for underflow of the queue.
Step 5: If F=0 then print queue underflow else delete the element and increment
the front pointer
Step 6: Stop the 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 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("SATFF CLUD FUND"+0.001*BP);


} }
class Associate_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 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:

Employee e1=new Employee();


Programmer p1=new Programmer();
e1.Emp_name="ABC";
e1.Address="y-city";
e1.Mail_id="praw@gmail.com";
e1.Emp_id=567;

e1.Mobile_no=2345678;
p1.BP=15000;
p1.display();
e1.display();
break;
case 2:

Employee e2=new Employee();


Assistant_Professor p2=new Assistant_Professor();
e2.Emp_name="DEF";
e2.Address="A-city";
e2.Mail_id="RAJAN@gmail.com";
e2.Emp_id=123;
e2.Mobile_no=987321;

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

SATFF CLUD FUND15.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:

To design a Java application to implement array implementation of stack using the


concept of Interface.

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

D:\ >javac Teststack.java D:\ >java Teststack ARRAY STACK

1.Push 2.Pop 3.Display 4.Exit Enter your Choice: 1

Enter the value to push: 10 Element pushed: 10

Please enter 0 to quit and 1 to continue 1

ARRAY STACK

1.Push 2.Pop 3.Display 4.Exit Enter your Choice: 1

Enter the value to push: 20 Element pushed: 20

Please enter 0 to quit and 1 to continue 1

ARRAY STACK

1.Push 2.Pop 3.Display 4.Exit Enter your Choice: 1

Enter the value to push: 30 Element pushed: 30

Please enter 0 to quit and 1 to continue 1

ARRAY STACK

1.Push 2.Pop 3.Display 4.Exit Enter your Choice: 3

The elements are:

Element: 10

Element: 20

Element: 30

Please enter 0 to quit and 1 to continue 1

ARRAY STACK

1.Push 2.Pop 3.Display 4.Exit Enter your Choice: 2

Element popped: 30

Please enter 0 to quit and 1 to continue 1

ARRAY STACK

1. Push 2.Pop 3.Display 4.Exit Enter your Choice: 3

The elements are:


element:10 element:20

Please enter 0 to quit and 1 to continue 0

RESULT

Thus the Java application for ADT stack operations has been implemented and executed
successfully.
EX.NO:6 USER DEFINED EXCEPTION HANDLING IMPLEMENTATION

AIM

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

ALGORITHM:

STEP 1. Start

STEP 2. Create a class NegativeAmtException which extends Exception class.

STEP 3. Create a constructor which receives the string as argument.

STEP 4. Get the Amount as input from the user.

STEP 5. If the amount is negative, the exception will be generated.

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

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
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 4. getName() displays the name of the file.

STEP 5. getPath() diplays the path name of the file.

STEP 6. getParent () -This method returns the pathname string of this abstract
pathname’s parent

STEP 7. null if this pathname does not name a parent directory.

STEP 8. exists() – Checks whether the file exists or not.

STEP 9. canRead()-This method is basically a check if the file can be read.

STEP 10. canWrite()-verifies whether the application can write to the file.

STEP 11. isDirectory() – displays whether it is a directory or not.

STEP 12. isFile() – displays whether it is a file or not.

STEP 13. lastmodified() – displays the last modified information.

STEP 14. length()- displays the size of the file.

STEP 15. delete() – deletes the file

STEP 16. Invoke the predefined functions to display the information about the file.

STEP 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
EX.NO:9 GENERIC FUNCTION IMPLEMENTATION

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

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy