0% found this document useful (0 votes)
11 views47 pages

Oops Lab Manual - II Yr

The document outlines the objectives and list of experiments for a laboratory course on object oriented programming in Java. The course aims to build software development skills using Java for real-world applications and cover concepts like classes, packages, interfaces, exception handling and file processing. The list of 11 experiments include implementing data structures, inheritance, exceptions, file handling, generics and GUI applications.

Uploaded by

vikashtamila
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)
11 views47 pages

Oops Lab Manual - II Yr

The document outlines the objectives and list of experiments for a laboratory course on object oriented programming in Java. The course aims to build software development skills using Java for real-world applications and cover concepts like classes, packages, interfaces, exception handling and file processing. The list of 11 experiments include implementing data structures, inheritance, exceptions, file handling, generics and GUI applications.

Uploaded by

vikashtamila
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/ 47

LABORATORY ACTIVITY MANUAL

P.s.r.r college of engineering

CS8383-OBJECT ORIENTED PROGRAMMING LABORATORY

OBJECTIVES:

• To build software development skills using java programming for real-world


applications.
• To understand and apply the concepts of classes, packages, interfaces, arraylist,
exception handling and file processing.
• To develop applications using generic programming and eventhandling.

LIST OF EXPERIMENTS:

1. Solve problems by using sequential search, binary search, and Quadratic sorting
algorithms(Selection, Insertion)
2. Develop Stack and Queue data structures using classes and objects.
3. Develop a java application with 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.

4. Write a Java Program to create an abstract class named Shape that contains two integers
and an empty method named print Area(). Provide three classes named Rectangle, Triangle
and Circle such that each one of the classes extends the class Shape. Each one of the classes
contains only the method print Area () that prints the area of the givenshape.
5. Solve the above problem using an Interface.

6. Implement exception handling and creation of user defined exceptions.

7. Write a java program that implements a multi-threaded application that has three threads. First
thread generates a random integer every 1 second and if the value is even, second thread computes
the square of the number and prints. If the value is odd, the third thread will print the value of cube
of thenumber
8. Write a Java program to perform file operations.
9. Develop applications to demonstrate the features of generics classes.

10. Develop applications using JavaFX controls, Layouts and Menus.


LABORATORY ACTIVITY MANUAL

P.s.r.r college of engineering

11. Develop a mini project for any application using Javaconcepts.

TOTAL: 60 PERIODS

OUTCOMES:
Upon completion of the course, the students will be able to
• Develop and implement Java programs for simple applications that make use of
classes, packages andinterfaces.
• Develop and implement Java programs with arraylist, exception handling and
multithreading.
• Design applications using file processing, generic programming and eventhandling.

CS8383-OBJECT ORIENTED PROGRAMMING LABORATORY


CONTENTS
LABORATORY ACTIVITY MANUAL

P.s.r.r college of engineering

Ex.
No. Name of the Exercise Page No.

1 Electricity Bill Generation using Classes 5–7

Currency converter, Distance converter and Time converter


2 8 – 13
Implementation using Packages

3 Pay slip Generation using Inheritance 14 – 19

Stack ADT Implementation using Multiple Inheritance


4 20 – 28
(Interface)

5 String Operations using Array List 29 – 31

6 Abstract Class Implementation 32 – 34

7 User Defined Exception Handling Implementation 35 – 36

8 File Handling 37 – 39

9 Multithreading Implementation 40 – 41

10 Generic Function Implementation 42 – 43

11 Calculator Design Using Event Driven Programming 33 –56

12 Mini Project 57

Algorithm
Linear search

• Start

• If the size of the array is zero then, return -1, representing that the element is not found. This can
also be treated as the base condition of a recursion call.
LABORATORY ACTIVITY MANUAL

P.s.r.r college of engineering

• Otherwise, check if the element at the current index in the array is equal to the key or not i.e,
arr[size – 1] == key
o If equal, then return the index of the found key.
• End

Binary Search Algorithm:

• Start

• Begin with the mid element of the whole array as a search key.
• If the value of the search key is equal to the item then return an index of the search key.
• Or if the value of the search key is less than the item in the middle of the interval, narrow the
interval to the lower half.
• Otherwise, narrow it to the upper half.
• Repeatedly check from the second point until the value is found or the interval is empty.
• End

Selection sort:

• Start

• Initialize minimum value(min_idx) to location 0.


• Traverse the array to find the minimum element in the array.
• While traversing if any element smaller than min_idx is found then swap both the values.
• Then, increment min_idx to point to the next element.
• Repeat until the array is sorted.
• End

Insertion Sort Algorithm

• Start

• Iterate from arr[1] to arr[N] over the array.


• Compare the current element (key) to its predecessor.
• If the key element is smaller than its predecessor, compare it to the elements before. Move the
greater elements one position up to make space for the swapped element.
• End

Push Operation
• Start

• Checks if the stack is full.


• If the stack is full, produces an error and exit.
• If the stack is not full, increments top to point next empty space.
LABORATORY ACTIVITY MANUAL

P.s.r.r college of engineering

• Adds data element to the stack location, where top is pointing.


• Returns success.
• End

Pop operation

• Start

• Checks if the stack is empty.


• If the stack is empty, produces an error and exit.
• If the stack is not empty, accesses the data element at which top is pointing.
• Decreases the value of top by 1.
• Returns success.
• End

Enqueue Operation
• Start

• Step 1 − Check if the queue is full.


• Step 2 − If the queue is full, produce overflow error and exit.
• Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
• Step 4 − Add data element to the queue location, where the rear is pointing.
• Step 5 − return success.
• End

Dequeue Operation
• Start

• Step 1 − Check if the queue is empty.


• Step 2 − If the queue is empty, produce underflow error and exit.
• Step 3 − If the queue is not empty, access the data where front is pointing.
• Step 4 − Increment front pointer to point to the next available data element.
• Step 5 − Return success.
• End

Java application for calculate gross and net salary

Algorithm

1)Start
2)Take the input from the user as employee name,id and basic salary
3)Calculate the the above parameters DA,HRA,GS,income tax and net salary
4)Display the output
LABORATORY ACTIVITY MANUAL

P.s.r.r college of engineering


5)Stop
7

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women

EX. NO:1
DATE:

AIM:
ALGORITHM:

Program :

OUTPUT:

RESULT:

VIVA QUESTIONS:
1. Explain how to create instance of a class by giving example
2. What are Access Specifiers
3. Can a top level class be private or protected?
4. Which access Modifiers are used in this program?

EX NO :2
DATE:

AIM:
To develop a java application to implement

ALGORITHM:

1. Start
2. Stop

Program :

RESULT
8

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


Thus the Java application to implement currency converter, distance converter and
time converter was implemented, executed successfully and the output was verified.
VIVA QUESTIONS
1.How to put two public classes in a package
2.What is import feature in java
3.Which mechanism used for naming and visibility control of a class and its content?

EXNO:3 PAYSLIP GENERATIONUSINGINHERITANCE


DATE:

AIM:
To develop a java application to generate pay slip for different category of employees using the concept
of inheritance
.ALGORITM:

1. Start
2. Create the class Employee with name, Empid, address, mailid, mobileno as datamembers.
3. Inherit the classes Programmer, Asstprofessor, Associateprofessor and Professor from
employee class.
4. Add Basic Pay (BP) as the member of all the inheritedclasses.
5. Calculate DA as 97% of BP, HRA as 10% of BP, PF as 12% of BP, Staff club fund as 0.1% ofBP.
6. Calculate gross salary and netsalary.
7. Generate payslip for all categories ofemployees.
8. Create the objects for the inherited classes and invoke the necessary methods to display thePayslip
9. Stop
Program :
import java.util.*;
class Employee
{
int empid;
long mobile;
9

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


String name, address, mailid;
Scanner get = new Scanner(System.in);
getdata()
{
System.out.println("Enter Name of the Employee");
name = get.nextLine();
System.out.println("Enter Mail id");
mailid = get.nextLine();
System.out.println("Enter Address of the Employee:");
address = get.nextLine();
System.out.println("Enter employee id ");
empid = get.nextInt();
System.out.println("Enter Mobile Number");
mobile = get.nextLong();
}
display()
{
System.out.println("Employee Name: "+name);
System.out.println("Employee id : "+empid);
System.out.println("Mail id : "+mailid);
System.out.println("Address: "+address);
System.out.println("Mobile Number: "+mobile);
}
}
class Programmer extends Employee
{
double salary,bp,da,hra,pf,club,net,gross;
getprogrammer()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
calculateprog()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("********************************************");
System.out.println("PAY SLIP FOR PROGRAMMER");
System.out.println("********************************************");
System.out.println("Basic Pay: Rs. "+bp);
System.out.println("DA: Rs. "+da);
10

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


System.out.println("HRA: Rs. "+hra);
System.out.println("PF: Rs. "+pf);
System.out.println("CLUB: Rs. "+club);
System.out.println("GROSS PAY: Rs. "+gross);
System.out.println("NET PAY: Rs. "+net);
}}
class Asstprofessor extends Employee
{
double salary,bp,da,hra,pf,club,net,gross;
getasst()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
calculateasst()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("***********************************");
System.out.println("PAY SLIP FOR ASSISTANT PROFESSOR");
System.out.println("***********************************");
System.out.println("Basic Pay: Rs. "+bp);
System.out.println("DA: Rs. "+da);
System.out.println("HRA: Rs. "+hra);
System.out.println("PF: Rs. "+pf);
System.out.println("CLUB: Rs. "+club);
System.out.println("GROSS PAY: Rs. "+gross);
System.out.println("NET PAY: Rs. "+net);
}}
class Associateprofessor extends Employee
{
double salary,bp,da,hra,pf,club,net,gross;
getassociate()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
calculateassociate()
{
da=(0.97*bp);
hra=(0.10*bp);
11

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("***********************************");
System.out.println("PAY SLIP FOR ASSOCIATE PROFESSOR");
System.out.println("***********************************");
System.out.println("Basic Pay: Rs. "+bp);
System.out.println("DA: Rs. "+da);
System.out.println("HRA: Rs. "+hra);
System.out.println("PF: Rs. "+pf);
System.out.println("CLUB: Rs. "+club);
System.out.println("GROSS PAY: Rs. "+gross);
System.out.println("NET PAY: Rs. "+net);
}}
class Professor extends Employee
{
double salary,bp,da,hra,pf,club,net,gross;
getprofessor()
{
System.out.println("Enter basic pay");
bp = get.nextDouble();
}
calculateprofessor()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
System.out.println("************************");
System.out.println("PAY SLIP FOR PROFESSOR");
System.out.println("************************");
System.out.println("Basic Pay: Rs. "+bp);
System.out.println("DA: Rs. "+da);
System.out.println("HRA: Rs. "+hra);
System.out.println("PF: Rs. "+pf);
System.out.println("CLUB: Rs. "+club);
System.out.println("GROSS PAY: Rs. "+gross);
System.out.println("NET PAY: Rs. "+net);
}}
class Salary
{
public static void main(String args[])
12

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


{
int choice,cont;
do
{
System.out.println("PAYROLL");
System.out.println(" 1.PROGRAMMER \t 2.ASSISTANT PROFESSOR \t 3.ASSOCIATE PROFESSOR
\t 4.PROFESSOR ");
Scanner c = new Scanner(System.in);
System.out.print("Enter Your Choice:");
choice=c.nextInt();
switch(choice)
{
case 1:
{
Programmer p=new Programmer();
p.getdata();
p.getprogrammer();
p.display();
p.calculateprog();
break;
}
case 2:
{
Asstprofessor asst=new Asstprofessor();
asst.getdata();
asst.getasst();
asst.display();
asst.calculateasst();
break;
}
case 3:
{
Associateprofessor asso=new Associateprofessor();
asso.getdata();
asso.getassociate();
asso.display();
asso.calculateassociate();
break;
}
case 4:
{
Professor prof=new Professor();
prof.getdata();
prof.getprofessor();
prof.display();
13

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


prof.calculateprofessor();
break;
}}
System.out.print("Please enter 0 to quit and 1 to continue: ");
cont=c.nextInt();
}while(cont==1);
}}

OUTPUT:

RESULT
Thus the Java application to generate pay slip for different category of employees was
implemented using inheritance and the program was executed successfully.

VIVA QUESTIONS:
1.What is Inheritance?
2.What are the types of Inheritance?
3.How to implement multiple inheritance in java
4.how to access two parent class in a child class?

EXNO:4 STACK IMPLEMENTATION USING CLASS AND OBJECTS


DATE:
AIM
To design a Java application to implement array implementation of stack using the concept of
14

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


Interface and Exception

handling.ALGORITHM

1. Start
2. Create the interface Stackoperation with method declarations for push andpop.
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 underflowcondition.
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 stackoperation.
5. Create the object and invoke the method for push, pop, display based on the input from theuser.
6. Stop.

Program :
import java.io.*;
interface Stackoperation
{
public void push(int i);
public void pop();
}
class Astack implements Stackoperation
{
int stack[]=new int[5];
int top=-1;
int i;
public void push(int item)
{
if(top>=4)
{
System.out.println("Overflow");
}
else
{
top=top+1; stack[top]=item;
System.out.print("Element pushed: "+stack[top]);
}
}
public void pop()
{
if(top<0)
System.out.println("Underflow");
else
{
System.out.print("Element popped: "+stack[top]);
top=top-1;
15

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


}}
public void display()
{
if(top<0)
System.out.println("No Element in stack");
else
{
for(i=0;i<=top;i++) System.out.println("Element:"+stack[i]);
}}}
class Teststack
{
public static void main(String args[]) throws IOException
{
int ch,c; int i;
Astack s=new Astack();
DataInputStream in=new DataInputStream(System.in);
do
{
try
{
System.out.println("ARRAY STACK");
System.out.println("1.Push 2.Pop 3.Display 4.Exit");
System.out.print("Enter your Choice:");
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1:
System.out.print("Enter the value to push:");
i=Integer.parseInt(in.readLine());
s.push(i);
break;
case 2:
s.pop();
break;
case 3:
System.out.println("The elements are: ");
s.display();
break;
default:
break;
}}
catch(IOException e)
{
System.out.println("IO Error");
}
System.out.println("Please enter 0 to quit and 1 to continue ");
16

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


c=Integer.parseInt(in.readLine());
}
while(c==1);
}}

OUTPUT:
17

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women

RESULT:
Thus the java application for ADT stack operation has been implemented and executed successfully
18

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


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. Createanabstractclassnamedshapethatcontainstwointegersandanemptymethodnamed
printarea().
3. Provide three classes named rectangle, triangle and circle such that each one of the classes
extends the classShape.
4. Eachoftheinheritedclassfromshapeclassshouldprovidetheimplementationforthemethod
printarea().
5. Get the input and calculate the area of rectangle, circle andtriangle.
6. In the shapeclass, create the objects for the three inherited classes and invoke the methods
and display the area values of the differentshapes.
7. Stop.

Program :

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();
19

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


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:
20

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women

RESULT
Thus the Java program for calculate the area of rectangle, circle and triangle was implemented and
executed successfully.

VIVA QUESTIONS
1.What is difference between abstract class and interface
2.Can a abstract class be defined without any abstract method?
3.Abstract is a specifier or modifier
21

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


EX NO :6 USER DEFINED EXCEPTION HANDLING IMPLEMENTATION
DATE:

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

ALGORITHM:

1. Start
2. Create a class NegativeAmtException which extends Exceptionclass.
3. Create a constructor which receives the string asargument.
4. Get the Amount as input from theuser.
5. If the amount is negative, the exception will begenerated.
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 bedisplayed.
8. If the amount is greater than 0, the message “Amount Deposited “ will bedisplayed
9. Stop.

Program :
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)
{
22

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


System.out.println(e);
}}}

Output

Program 2:
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) ;
}}}
23

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


Output:

RESULT
Thus the Java program to implement user defined exception handling has been implemented and executed
successfully
VIVA QUESTION
1.Define Exception and Error
2.Difference between throw and throws
3.mention some Build in exception
4.how to declare User defined Exception
EX NO:8 FILEHANDLING
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 theuser.
3. Use the file functions and display the information about thefile.
4. getName() displays the name of thefile.
5. getPath() diplays the path name of thefile.
24

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


6. getParent () -This method returns the pathname string of this abstract pathname’s parent,or
7. null if this pathname does not name a parentdirectory.
8. exists() – Checks whether the file exists ornot.
9. canRead()-This method is basically a check if the file can beread.
10. canWrite()-verifies whether the application can write to thefile.
11. isDirectory() – displays whether it is a directory ornot.
12. isFile() – displays whether it is a file ornot.
13. lastmodified() – displays the last modifiedinformation.
14. length()- displays the size of thefile.
15. delete() – deletes thefile
16. Invoke the predefined functions to display the information about thefile.
17. Stop.
Program :
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());
}}
25

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


Output:

Result:
Thus the java program to display file information has been implemented and executed successfully.

VIVA QUESTIONS
1.What is i/o stream
2.Types of file I/O stream
26

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women

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 getsexecuted.
4. Create a class odd which implements second thread that computes the cube of thenumber.
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 givennumber.
6. The Multithreading is performed and the task switched between multiplethreads.
7. The sleep () method makes the thread to suspend for the specifiedtime.
8. Stop.

Program :
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
27

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


{
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(3000);
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:
28

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women

RESULT:

Thus the java program for multithreaded application has been implemented and executed successfully.

VIVA QUESTION
1.What is multithreading and what is the class in which these methods are defined?
29

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women

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 genericmethods.
3. Get the set of the values belonging to specific datatype.
4. Create the objects of the class to hold integer, character and doublevalues.
5. Create the method to compare the values and find the maximum value stored in thearray.
6. Invoke the method with integer, character or double values. The output will be
displayed based on the data type passed to themethod.
7. Stop.
Program :
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);
30

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


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:

VIVA QUESTION
1.How to write parameterized class in java using Generics
2.Can you pass list<string> to a method with accepts List<Object>
3.Can we use generics with Array?
31

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


EX NO:11 CALCULATOR DESIGN USING EVENT DRIVEN PROGRAMMING
DATE:
AIM
To design a calculator using event driven programming paradigm of java with the following
A) Decimal Manipulations
B)Scientific Manipulations
Algorithm:
1. Start
2. Import the swing packages
3. Create the class scientific calculator that implements action listener.
4. Create the container and add controls for digits, scientific calculations and decimal
Manipulations.
5. The different layouts can be used to lay the controls.
6. When the user presses the control, the event is generated and handled.
7. The corresponding decimal, numeric and scientific calculations are performed.
8. Stop
Program :
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class ScientificCalculator extends JFrame implements ActionListener
{
JTextField tfield;
double temp, temp1, result, a; static double m1, m2;
int k = 1, x = 0, y = 0, z = 0;
char ch;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, zero, clr, pow2, pow3, exp, fac, plus, min, div, log, rec, mul, eq,
addSub, dot, mr, mc, mp,
mm, sqrt, sin, cos, tan;
Container cont;
JPanel textPanel, buttonpanel;
ScientificCalculator()
{
cont = getContentPane();
cont.setLayout(new BorderLayout());
JPanel textpanel = new JPanel();
tfield = new JTextField(25);
tfield.setHorizontalAlignment(SwingConstants.RIGHT);
tfield.addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEvent keyevent)
{
char c = keyevent.getKeyChar();
if (c >= '0' && c <= '9')
32

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


{
}
else
{
keyevent.consume();
}
}
});
textpanel.add(tfield);
buttonpanel = new JPanel();
buttonpanel.setLayout(new GridLayout(8, 4, 2, 2));
boolean t = true;
mr = new JButton("MR");
buttonpanel.add(mr);
mr.addActionListener(this);
mc = new JButton("MC");
buttonpanel.add(mc);
mc.addActionListener(this);
mp = new JButton("M+");
buttonpanel.add(mp);
mp.addActionListener(this);
mm = new JButton("M-");
buttonpanel.add(mm);
mm.addActionListener(this);
b1 = new JButton("1");
buttonpanel.add(b1);
b1.addActionListener(this);
b2 = new JButton("2");
buttonpanel.add(b2);
b2.addActionListener(this);
b3 = new JButton("3");
buttonpanel.add(b3);
b3.addActionListener(this);
b4 = new JButton("4");
buttonpanel.add(b4);
b4.addActionListener(this);
b5 = new JButton("5");
buttonpanel.add(b5);
b5.addActionListener(this);
b6 = new JButton("6");
buttonpanel.add(b6);
b6.addActionListener(this);
b7 = new JButton("7");
buttonpanel.add(b7);
b7.addActionListener(this);
b8 = new JButton("8");
33

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


buttonpanel.add(b8);
b8.addActionListener(this);
b9 = new JButton("9");
buttonpanel.add(b9);
b9.addActionListener(this);
zero = new JButton("0");
buttonpanel.add(zero);
zero.addActionListener(this);
plus = new JButton("+");
buttonpanel.add(plus);
plus.addActionListener(this);
min = new JButton("-");
buttonpanel.add(min);
min.addActionListener(this);
mul = new JButton("*");
buttonpanel.add(mul);
mul.addActionListener(this);
div = new JButton("/");
div.addActionListener(this);
buttonpanel.add(div);
addSub = new JButton("+/-");
buttonpanel.add(addSub);

addSub.addActionListener(this);
dot = new JButton(".");
buttonpanel.add(dot);
dot.addActionListener(this);
eq = new JButton("=");
buttonpanel.add(eq);
eq.addActionListener(this);
rec = new JButton("1/x");
buttonpanel.add(rec);
rec.addActionListener(this);
sqrt = new JButton("Sqrt");
buttonpanel.add(sqrt);
sqrt.addActionListener(this);
log = new JButton("log");
buttonpanel.add(log);
log.addActionListener(this);
sin = new JButton("SIN");
buttonpanel.add(sin);
sin.addActionListener(this);
cos = new JButton("COS");
buttonpanel.add(cos);
cos.addActionListener(this);
tan = new JButton("TAN");
34

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


buttonpanel.add(tan);
tan.addActionListener(this);
pow2 = new JButton("x^2");
buttonpanel.add(pow2);
pow2.addActionListener(this);
pow3 = new JButton("x^3");
buttonpanel.add(pow3);
pow3.addActionListener(this);
exp = new JButton("Exp");
exp.addActionListener(this);
buttonpanel.add(exp);
fac = new JButton("n!");
fac.addActionListener(this);
buttonpanel.add(fac);
clr = new JButton("AC");
buttonpanel.add(clr);
clr.addActionListener(this);
cont.add("Center", buttonpanel);
cont.add("North", textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("1"))
{
if (z == 0)
{
tfield.setText(tfield.getText() + "1");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "1");
z = 0;
}
}
if (s.equals("2"))
{
if (z == 0)
{
tfield.setText(tfield.getText() + "2");
}
else
{
tfield.setText("");
35

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


tfield.setText(tfield.getText() + "2");
z = 0;
}
}
if (s.equals("3"))
{
if (z == 0)
{
tfield.setText(tfield.getText() + "3");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "3");
z = 0;
}
}
if (s.equals("4"))
{
if (z == 0)
{
tfield.setText(tfield.getText() + "4");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "4");
z = 0;
}
}
if (s.equals("5"))
{
if (z == 0)
{
tfield.setText(tfield.getText() + "5");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "5");
z = 0;
}
}
if (s.equals("6"))
{
if (z == 0)
36

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


{
tfield.setText(tfield.getText() + "6");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "6");
z = 0;
}
}
if (s.equals("7"))
{
if (z == 0)
{
tfield.setText(tfield.getText() + "7");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "7");
z = 0;
}
}
if (s.equals("8"))
{
if (z == 0)
{
tfield.setText(tfield.getText() + "8");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "8");
z = 0;
}
}
if (s.equals("9")) { if (z == 0)
{
tfield.setText(tfield.getText() + "9");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "9");
z = 0;
}
37

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


}
if (s.equals("0"))
{
if (z == 0)
{
tfield.setText(tfield.getText() + "0");
}
else
{
tfield.setText("");
tfield.setText(tfield.getText() + "0");
z = 0;
}
}
if (s.equals("AC"))
{
tfield.setText("");
x = 0;
y = 0;
z = 0;
}
if (s.equals("log"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.log(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("1/x"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = 1 / Double.parseDouble(tfield.getText());
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
38

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


}
if (s.equals("Exp"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.exp(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^2"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.pow(Double.parseDouble(tfield.getText()), 2);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^3"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.pow(Double.parseDouble(tfield.getText()), 3);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("+/-"))
{
if (x == 0)
{
tfield.setText("-" + tfield.getText());
x = 1;
39

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


}
else
{
tfield.setText(tfield.getText());
}
}
if (s.equals("."))
{
if (y == 0)
{
tfield.setText(tfield.getText() + ".");
y = 1;
}
else
{
tfield.setText(tfield.getText());
}
}
if (s.equals("+"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
temp = 0;
ch = '+';
}
else
{
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '+';
y = 0;
x = 0;
}
tfield.requestFocus();
}
if (s.equals("-"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
temp = 0;
ch = '-';
}
else
{
40

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '-';
}
tfield.requestFocus();
}
if (s.equals("/"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
temp = 1;
ch = '/';
}
else
{
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
ch = '/';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("*"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
temp = 1;
ch = '*';
}
else
{
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
ch = '*';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("MC"))
{
41

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


m1 = 0;
tfield.setText("");
}
if (s.equals("MR"))
{
tfield.setText("");
tfield.setText(tfield.getText() + m1);
}
if (s.equals("M+"))
{
if (k == 1)
{
m1 = Double.parseDouble(tfield.getText());
k++;
}
else
{
m1 += Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("M-"))
{
if (k == 1)
{
m1 = Double.parseDouble(tfield.getText());
k++;
}
else
{
m1 -= Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("Sqrt"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.sqrt(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
42

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


}
if (s.equals("SIN"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.sin(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("COS"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.cos(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("TAN"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = Math.tan(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("="))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
43

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


else
{
temp1 = Double.parseDouble(tfield.getText());
switch (ch)
{
case '+':
result = temp + temp1;
break;
case '-':
result = temp - temp1;
break;
case '/':
result = temp / temp1;
break;
case '*':
result = temp * temp1;
break;
}
tfield.setText("");
tfield.setText(tfield.getText() + result);
z = 1;
}
}
if (s.equals("n!"))
{
if (tfield.getText().equals(""))
{
tfield.setText("");
}
else
{
a = fact(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
tfield.requestFocus();
}
double fact(double x)
{
int er = 0;
if (x < 0)
{
er = 20;
return 0;
}
44

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women


double i, s = 1;
for (i = 2; i <= x; i += 1.0)
s *= i;
return s;
}
public static void main(String args[])
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e)
{
}
ScientificCalculator f = new ScientificCalculator();
f.setTitle("ScientificCalculator");
f.pack();
f.setVisible(true);
}
}

OUTPUT:
45

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women

RESULT
Thus the Java programs for scientific calculator has been implemented and executed successfully
VIVA QUESTION
1.Which container use a Border Layout as their default Layout?
2.Which Listener are implemented for JButton?
3.what is awt and Swing?
4.What is Grid Layout

EX NO:11 MINI PROJECT


DATE:
46

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women

1. Airline Reservation System


2. Mark sheet Preparation System
3. NAAC online application Creation
4. Library Management System
5. Converting RGB image to Gray Image
6. Health Care System
7. App Development
8. Income Tax System
9. Vehicle Tracking System
10. E Banking System
47

LABORATORY ACTIVITY MANUAL

P.s.r rengasamy college of engineering for women

You might also like