Oops Manual 2021
Oops Manual 2021
Semester III
Lab Manual
Regulation 2017
TABLE OF CONTENTS
1
S. Page
Particulars
No. No.
3 Lab syllabus 5
2. System calls. 11
4. Shell Programming. 20
6. Semaphores 39
6 Advance Experiments
2
1. Simulation environment for deadlock situation
can be created.
VISION
To develop students with intellectual curiosity and technical
expertise to meet the global needs.
MISSION
3
NPR College of Engineering & Technology, Natham.
VISION
To produce globally competent technical professionals for digitized
society.
MISSION
To establish conducive academic environment by imparting quality
education and value added training.
To encourage students to develop innovative projects to optimally
resolve the challenging social problems.
4
CS8383 OBJECT ORIENTED PROGRAMMING LABORATORY L T P C
0042
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 event handlin
TOTAL: 60 PERIODS
OUTCOMES:
At the end of the course, the student should be able to
Compare the performance of various CPU Scheduling Algorithms
Implement Deadlock avoidance and Detection Algorithms
Implement Semaphores
Create processes and implement IPC
Analyze the performance of the various Page Replacement Algorithms
Implement File Organization and File Allocation Strategies
5
Course Outcomes
After completion of the course, Students are able to learn the listed Course
Outcomes.
Course Knowledg
COs Course Outcomes
Code e Level
Develop and implement Java programs for simple
CO1 C207.1 K3
applications that make use of classes
Develop and implement Java programs with array
CO2 C207.2 K3
list
CO3 C207.3 Design applications using file processing K3
Build software development skills using java
CO4 C207.4 K3
programming for real-world applications
Apply the concepts of classes, packages,
CO5 C207.5 K3
interfaces, exception handling
Develop applications using generic programming
CO6 C207.6 K3
and event handling
List of Experiments with COs, POs and PSOs
Exp.
Name of the Experiment COs POs PSOs
No.
C05
6
CO5
CO6
Additional Experiments
CO5
Program Outcomes
7
Program Outcomes
Aim:
8
To develop a Java application to generate Electricity bill and create a class with
the following members: Consumer no., consumer name, previous month reading,
current month reading, type of EB connection (i.e domestic or commercial).
Algorithm:
1) Start the program
2) Create a class Lab1
3) Get the variables cno, pr,cr,type as integer type and name as string
4) Use Scanner to read the input
5) If the type of EB connection is domestic, the following should be calculated
using if statement
First 100 units - Rs. 1 per unit
101-200 units - Rs. 2.50 per unit
201 -500 units - Rs. 4 per unit
> 501 units - Rs. 6 per unit
6) If the type of the EB connection is commercial, the following should be
calculated:
First 100 units - Rs. 2 per unit
101-200 units - Rs. 4.50 per unit
201 -500 units - Rs. 6 per unit
> 501 units - Rs. 7 per unit
7) End the program and display the output.
Program:
import java.util.*;
import java.lang.*;
class Lab1
{
public static void main(String arg[])
{
int cno,pr,cr,type;
String name;
Scanner sc=new Scanner(System.in);
9
}
else
{
if(unit>501)
System.out.println("EB Bill Amount:"+unit*7.0);
else if(unit>201)
System.out.println("EB Bill Amount:"+unit*6.0);
else if(unit>101)
System.out.println("EB Bill Amount:"+unit*4.50);
else
System.out.println("EB Bill Amount:"+unit*2.0);
}
}
}
Output:
Result:
Thus the java application for electricity bill calculation was implemented
successfully
Aim:
10
Todevelop a java application to implement currency converter (Dollar to INR),
distance converter (meter to KM) , time converter (hours to minutes) using packages.
Algorithm:
1) Start the program
2) Create a folder named as mypack in anyone directory, that is a package
creation.
3) Within the package create the classes Time, Distance and Currency
4) Time class uses the hour to minutes and minutes to hour conversion
5) Distance class used to convert kilometer to meter and meter to kilometer.
6) Currency class uses dollar to INR and INR to dollar conversion.
7) Set a main class and call all three classes using the object.
8) Compile Time, Distance , Currency and the main class
9) Run the main class alone to display the output.
10) Stop the program.
Program:
Package mypack;
Currency.java
public class currency {
Scanner input=new Scanner(System.in);
public void convertEUROtoINR()
{
System.out.println("EURO TO INR\n");
double money;
System.out.println("Enter in EURO");
money=input.nextDouble();
System.out.println(money+"EURO = "+money*80+" INR");
}
public void convertDOLLARtoINR()
{
System.out.println("\nDOLLAR TO INR\n");
double money;
System.out.println("Enter in DOLLAR");
money=input.nextDouble();
System.out.println(money+"DOLLAR = "+money*66.89+" INR");
}
public void convertYENtoINR()
{
System.out.println("\nYEN TO INR\n");
double money;
System.out.println("Enter in YEN");
money=input.nextDouble();
System.out.println(money+"YEN = "+money*0.61+" INR");
}
public void convertINRtoEURO()
{
System.out.println("\nINR TO EURO\n");
double money;
System.out.println("Enter in INR");
money=input.nextDouble();
System.out.println(money+"INR = "+money*0.013+" EURO");
}
11
public void convertINRtoDOLLAR()
{
System.out.println("\nINR TO DOLLAR\n");
double money;
System.out.println("Enter in INR");
money=input.nextDouble();
System.out.println(money+"INR = "+money*0.015+" DOLLAR");
}
public void convertINRtoYEN()
{
System.out.println("\nINR TO YEN\n");
double money;
System.out.println("Enter in INR");
money=input.nextDouble();
System.out.println(money+"INR = "+money*1.63+" YEN");
}
}
public class Classmain {
public static void main(String[] args) {
currency c=new currency();
c.convertDOLLARtoINR();
c.convertEUROtoINR();
c.convertYENtoINR();
c.convertINRtoDOLLAR();
c.convertINRtoEURO();
c.convertINRtoYEN();
}
}
Output:
DOLLAR TO INR
Enter in DOLLAR
6
6.0DOLLAR = 401.34000000000003 INR
EURO TO INR
Enter in EURO
2
2.0EURO = 160.0 INR
YEN TO INR
Enter in YEN
4
4.0YEN = 2.44 INR
INR TO DOLLAR
Enter in INR
5
5.0INR = 0.075 DOLLAR
INR TO EURO
Enter in INR
3
3.0INR = 0.039 EURO
INR TO YEN
Enter in INR
8
8.0INR = 13.04 YEN
12
Distance.java
Package mypack;
public class distance {
Scanner input=new Scanner(System.in);
double distance;
void convertmetertokilometer()
{
System.out.println("\nMeter to kilometer");
System.out.println("Enter in meters : ");
distance=input.nextDouble();
System.out.println(distance+"Meters ="+distance/1000+"Kilometer");
}
void convertmilestokilometer()
{
System.out.println("\nMiles to kilometer\n");
System.out.println("Enter in miles : ");
distance=input.nextDouble();
System.out.println(distance+"Miles ="+distance*1.60934+"Kilometer");
}
void convertkilometertometer()
{
System.out.println("\nKilometer to meter\n");
System.out.println("Enter in Kilometer : ");
distance=input.nextDouble();
System.out.println(distance+"Kilometer ="+distance*1000+"Meter");
}
void convertkilometertomiles()
{
System.out.println("\nkilometer to Miles\n");
System.out.println("Enter in Kilometer : ");
distance=input.nextDouble();
System.out.println(distance+"Kilometer ="+distance/1.60934+"Miles");
}}
public class Mainclass {
public static void main(String[] args) {
distance d=new distance();
d.convertkilometertometer();
d.convertkilometertomiles();
d.convertmetertokilometer();
d.convertmilestokilometer();
}
}
Output
Kilometer to meter
Enter in Kilometer :
5
5.0Kilometer =5000.0Meter
kilometer to Miles
Enter in Kilometer :
4
4.0Kilometer =2.4854Miles
Meter to kilometer
Enter in meters :
2
13
2.0Meters =0.002Kilometer
Miles to kilometer
Enter in miles :
5
5.0Miles =8.0467Kilometer
Time.java
Package mypack;
public class time {
double time;
Scanner input=new Scanner(System.in);
void converthourstominutes()
{
System.out.println("\nHours to minutes\n");
System.out.println("Enter in hours : ");
time=input.nextDouble();
System.out.println(time+"Hours="+time*60+"Minutes");
}
public void converthourstoseconds()
{
System.out.println("\nHours to Seconds");
System.out.println("Enter in hours : ");
time=input.nextDouble();
System.out.println(time+"Hours="+time*60*60+"Seconds");
}
public void convertminutestohours()
{
System.out.println("\nMinutes to Hours\n");
System.out.println("Enter in minutes : ");
time=input.nextDouble();
System.out.println(time+"Minutes="+time/60+"Hours");
}
public void convertsecondstohours()
{
System.out.println("\nSeconds to Hours\n");
System.out.println("Enter in Seconds : ");
time=input.nextDouble();
System.out.println(time+"Seconds="+time/60/60+"Hours");
}
}
import mypack;
public class Time {
public static void main(String[] args) {
times t=new time();
t.converthourstominutes();
t.converthourstoseconds();
t.convertminutestohours();
t.convertsecondstohours();
}
}
14
Output:
Hours to minutes
Enter in hours :
2
2.0Hours=120.0Minutes
Hours to Seconds
Enter in hours :
3
3.0Hours=10800.0Seconds
Minutes to Hours
Enter in minutes :
2
2.0Minutes=0.0333Hours
Seconds to Hours
Enter in Seconds :
3
3.0Seconds=8.33334Hours
Result:
Thus the java application for implementing currency, distance and time
converter was implemented successfully.
Ex.No:3 Generate pay slips for the employees with their gross and net
Date: salary using Inheritance concept.
15
Aim:
To generate pay slips for the employees with their gross and net salary using
Inheritance concept.
Algorithm:
1) Start the program
2) Create a class Employee and inherit the classes, Programmer,
AssistantProfessor, AssociateProfessor and Professor from Employee class.
3) Get the members name, address, id,mailid,mobileno as string then gs(gross
salary) and ns(net salary) as float in Employee class .
4) Get bpay(BasicPay),gs and ns as double in other classes.
5) Create the cal() method to calculate the gross salary and net salary( 97% of BP
as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club fund).
6) Super keyword is used to call a method defined in the super class(Employee)
7) Create a main class Lab3 and call the inherited classes using the object.
8) End the program and display the output.
Program:
import java.util.Scanner;
public class employee {
String empname,address,mailid;
long mobileno;
int empid;
}
class professor extends employee
{
double bp,da,hra,pf,netsalary,grosssalary;
void read()
{
Scanner s=new Scanner(System.in);
System.out.println("PROFESSOR DETAILS\n\n");
System.out.println("Enter employee NAME : ");
empname=s.next();
System.out.println("Enter employee ID : ");
empid=s.nextInt();
System.out.println("Enter employee ADDRESS : ");
address=s.next();
System.out.println("Enter employee EMAIL ID : ");
mailid=s.next();
System.out.println("Enter employee MOBILE NO : ");
mobileno=s.nextLong();
System.out.println("Enter employee BP : ");
bp=s.nextDouble();
}
void calculate()
{
da=bp*0.97;
hra=bp*0.10;
pf=bp*0.01;
grosssalary=bp+da+hra;
netsalary=grosssalary-pf;
}
void show()
{
16
System.out.println("\nPROFESSOR EXTEND DETAILS");
System.out.println("NAME = "+empname);
System.out.println("ADDRESS = "+address);
System.out.println("EMP ID = "+empid);
System.out.println("EMAIL ID = "+mailid);
System.out.println("MOBILE NO = "+mobileno);
System.out.println("\nEMPLOYEE PAY SLIP");
System.out.println("THE HRA IS = "+hra);
System.out.println("THE DA IS = "+da);
System.out.println("THE PF IS = "+pf);
System.out.println("THE GROSS SALARY IS = "+grosssalary);
System.out.println("THE NET SALARY IS = "+netsalary);
}
}
class assprofessor extends employee
{
double bp,da,hra,pf,netsalary,grosssalary;
void read()
{
Scanner s=new Scanner(System.in);
System.out.println("\n\n\nASSISSTANT PROFESSOR DETAILS\n\n");
System.out.println("Enter employee NAME : ");
empname=s.next();
System.out.println("Enter employee ID : ");
empid=s.nextInt();
System.out.println("Enter employee ADDRESS : ");
address=s.next();
System.out.println("Enter employee EMAIL ID : ");
mailid=s.next();
System.out.println("Enter employee MOBILE NO : ");
mobileno=s.nextLong();
System.out.println("Enter employee BP : ");
bp=s.nextDouble();
}
void calculate()
{
da=bp*0.97;
hra=bp*0.10;
pf=bp*0.01;
grosssalary=bp+da+hra;
netsalary=grosssalary-pf;
}
void show()
{
System.out.println("\nASSISSTANT PROFESSOR EXTEND DETAILS");
System.out.println("NAME = "+empname);
System.out.println("ADDRESS = "+address);
System.out.println("EMP ID = "+empid);
System.out.println("EMAIL ID = "+mailid);
System.out.println("MOBILE NO = "+mobileno);
System.out.println("\nEMPLOYEE PAY SLIP");
System.out.println("THE HRA IS = "+hra);
System.out.println("THE DA IS = "+da);
17
System.out.println("THE PF IS = "+pf);
System.out.println("THE GROSS SALARY IS = "+grosssalary);
System.out.println("THE NET SALARY IS = "+netsalary);
}
}
class associativeprofessor extends employee
{
double bp,da,hra,pf,netsalary,grosssalary;
void read()
{
Scanner s=new Scanner(System.in);
System.out.println("\n\n\nASSOCIATIVE PROFESSOR DETAILS\n\n");
System.out.println("Enter employee NAME : ");
empname=s.next();
System.out.println("Enter employee ID : ");
empid=s.nextInt();
System.out.println("Enter employee ADDRESS : ");
address=s.next();
System.out.println("Enter employee EMAIL ID : ");
mailid=s.next();
System.out.println("Enter employee MOBILE NO : ");
mobileno=s.nextLong();
System.out.println("Enter employee BP : ");
bp=s.nextDouble();
}
void calculate()
{
da=bp*0.97;
hra=bp*0.10;
pf=bp*0.01;
grosssalary=bp+da+hra;
netsalary=grosssalary-pf;
}
void show()
{
System.out.println("\nASSOCIATIVE PROFESSOR EXTEND DETAILS");
System.out.println("NAME = "+empname);
System.out.println("ADDRESS a= "+address);
System.out.println("EMP ID = "+empid);
System.out.println("EMAIL ID = "+mailid);
System.out.println("MOBILE NO = "+mobileno);
System.out.println("\nEMPLOYEE PAY SLIP");
System.out.println("THE HRA IS = "+hra);
System.out.println("THE DA IS = "+da);
System.out.println("THE PF IS = "+pf);
System.out.println("THE GROSS SALARY IS = "+grosssalary);
System.out.println("THE NET SALARY IS = "+netsalary);
}
}
18
p.read();
p.calculate();
p.show();
assprofessor p1=new assprofessor();
p1.read();
p1.calculate();
p1.show();
associativeprofessor p2=new associativeprofessor();
p2.read();
p2.calculate();
p2.show();
Output:
19
Result:
Thus the java application for employee pay slip generation using inheritance
concept has been implemented successfully.
20
Aim:
To design a Java interface for ADT Stack and Implement this interface using
array.
Algorithm:
1) Start the program
2) Create an interface with the name stackoperation, and declare the push() and
pop() method .
3) Create a class , Astack and implement the stackoperation.
4) Set the maximum value that to be pushed as the top
5) The condition is checked, if it is a push option the item should be pushed into
the stack and if it is a pop then the item is removed from the top of the stack.
6) If the size exceeds, it displays the “overflow” message and if the size is lower
than the fixed top value, displays the “underflow” message.
7) Display option is used to view the items stored in the Array stack.
8) End the program and display the result.
Program:
import java.util.*;
import java.io.*;
interface stackoperation
{
public void push();
public void pop();
}
class Astack implements stackoperation
{
int stack[];
int top;
Astack()
{
stack=new int[10];
top=0;
}
public void push()
{
if(top>=5)
System.out.println("overflow");
else
{
Scanner in=new Scanner(System.in);
System.out.println("enter the value to push:");
stack[++top]=in.nextInt();
System.out.println("item pushed");
}
}
public void pop()
{
if(top<1)
System.out.println("underflow");
else
{
System.out.println("item popped :"+stack[top--]);
}
}
21
public void display()
{
System.out.println("The Stack elements are: "+top);
for(int i=top;i>=1;i--)
System.out.println("element:"+stack[i]);
}
}
class sample
{
public static void main(String args[])throws IOException
{
int ch;
Scanner in=new Scanner(System.in);
Astack s=new Astack();
System.out.println("ARRAY STACK");
do
{
System.out.println("1.push 2.pop 3.display 4.exit");
System.out.println("enter ur choice:");
ch=in.nextInt();
switch(ch)
{
case 1:
s.push();
break;
case 2:
s.pop();
break;
case 3:
System.out.println("the elements are:");
s.display();
break;
case 4:System.exit(0);
}
}while(ch!=4);
}
}
Output:
ARRAY STACK
1.push 2.pop 3.display 4.exit
enter ur choice:
1
enter the value to push:
22
item pushed
1.push 2.pop 3.display 4.exit
22
enter ur choice:
1
enter the value to push:
21
item pushed
1.push 2.pop 3.display 4.exit
enter ur choice:
3
the elements are:
The Stack elements are: 2
element:21
element:22
1.push 2.pop 3.display 4.exit
enter ur choice:
2
item popped :21
1.push 2.pop 3.display 4.exit
enter ur choice:
3
the elements are:
The Stack elements are: 1
element:22
1.push 2.pop 3.display 4.exit
enter ur choice:
4
23
Result:
Thus the design and implementation of ADT Stack using array has successfully
executed.
24
Aim:
To write a java program to perform string operations using ArrayList .
Algorithm:
1) Start the program.
2) Create the class and store the string elements in the array list
3) Append is to add the elements at the end of the array list
4) Insert the elements into the array list
5) Search the string element in the list
6) Display the string that starts with given letter.
7) End the program and display the output.
Program:
import java.util.*;
public class Lab5 {
public static void main(String args[]) {
/*Creation of ArrayList: I'm going to add String
*elements so I made it of string type */
ArrayList<String> obj = new ArrayList<String>();
Output:
25
Append - add at end : [First, Second, Third, Fourth]
Insert - add at particular index : [First, Fifth, Second, Third, Fourth]
Searching the string-Third in the Array List : true
Searching the string-Nine in the Array List : false
The elements starts with F :
First
Fifth
Fourth
26
Result:
Thus the implementation of string operations using array list has been
successfully executed.
27
Aim:
To write a Java Program using an abstract class.
Algorithm:
1) Start the program
2) Create a class with the name Shape.
3) Create the Rectangle,Triangle,Circle extends Shape.
4) Create the objects to the individual classes.
5) Call the PrintArea() on individual object.
Program:
import java.util.*;
import java.io.*;
import java.lang.*;
abstract class shape
{
public int x,y;
public abstract void printArea();
}
class Rectangle extends shape {
public void printArea()
{
float area;
area= x * y;
System.out.println("Area of Rectangle is " +area);
}
}
class Triangle extends shape {
public void printArea()
{
float area;
area= (x * y) / 2;
System.out.println("Area of Triangle is " +area);
}
}
class Circle extends shape {
public void printArea()
{
float area;
area=(22 * x * x) / 7;
System.out.println("Area of Circle is " + area);
}
}
public class Shapes {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter values : ");
int x1=sc.nextInt();
int y1=sc.nextInt();
Rectangle r = new Rectangle();
r.x = x1;
r.y = y1;
r.printArea();
28
Triangle t = new Triangle();
t.x = x1;
t.y = y1;
t.printArea();
Circle c = new Circle();
c.x = x1;
c.printArea();
}
}
Output:
Enter values :
5
6
Area of Rectangle is 30.0
Area of Triangle is 15.0
Area of Circle is 78.0
Result:
Thus the design and implementation of Abstract class has been implemented
successfully.
29
Aim:
To write a Java program for implementing user defined exception handling
Algorithm:
1) Start the program
2) Create user defined exception otherwise called own exception class
3) try represents the block of statements in which there are chances of occurring
some exceptions.
4) Exception is detected & it is thrown using throw keyword.
5) catch block is defined after the try block and it catches the exception thrown by
the try block.
6) End the program and display the result.
Program:.
import java.lang.*;
import java.io.*;
class JavaException1{
public static void main(String args[])
{
try{
throw new MyException("Userdefiend Exception");
}
catch(MyException e)
{
System.out.println(e) ;
}
}
}
class MyException extends Exception{
MyException(String msg) {
super(msg);
}
}
Output:
Result:
Thus the java program foruser defined exception has been implemented
successfully .
30
Implement a Java program for file handling using various file
Ex.No:8
Date: methods
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 the program
2) Create a class named as Lab8
3) Java File class represents the files and directory pathnames in an abstract
manner.
4) Checks whether the file can read, write and exist .
5) Files can also checks the last modified and length of the file using the methods
6) Stop the program and run the output.
Program:
import java.io.*;
class Lab8
{
public static void main(String args[])
{
File f1=new File("/Lab","Test.java");
System.out.println("file name:"+f1.getName());
System.out.println("path:"+f1.getPath());
System.out.println("parent:"+f1.getParent());
System.out.println(f1.exists());
System.out.println(f1.canRead());
System.out.println(f1.canWrite());
System.out.println(f1.isDirectory());
System.out.println(f1.isFile());
System.out.println(f1.lastModified());
System.out.println(f1.length());
System.out.println(f1.delete());
}
}
Output:
file name:Test.java
path:\Lab\Test.java
parent:\Lab
false
false
false
false
false
0
0
False
31
Result:
Thus the information of the file has been displayed successfully using various
file methods.
32
Ex.No:9 Implement a java program that implements a multi-threaded
Date: application.
Aim:
To 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 the number.
Algorithm:
1) Start the program
2) Create a class with the name “even implements Runnable” and “odd
implements Runnable”.
3) Create thread objects and Random class object.
4) Pass the objects of our class to thread class .
5) Call the start method.
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
{
public void run()
{
int num = 0;
Random r = new Random();
try
{
for (int i = 0; i < 5; i++)
33
{
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 Lab9
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}
Output:
Main Thread and Generated Number is 26
New Thread 26 is EVEN and Square of 26 is: 676
--------------------------------------
Main Thread and Generated Number is 97
New Thread 97 is ODD and Cube of 97 is: 912673
--------------------------------------
Main Thread and Generated Number is 66
New Thread 66 is EVEN and Square of 66 is: 4356
--------------------------------------
Main Thread and Generated Number is 44
New Thread 44 is EVEN and Square of 44 is: 1936
--------------------------------------
Main Thread and Generated Number is 62
New Thread 62 is EVEN and Square of 62 is: 3844
------------------------------------
Result:
Thus the java program for multithreading application has been implemented
successfully.
34
Ex.No:10 Implement a java program to find the maximum value from
Date: the given type of elements using a generic function.
Aim:
To write a java program to find the maximum value from the given type of
elements using a generic function.
Algorithm:
1) Start the program
2) Themax() function accepts any number of generic elements
3) Sets the first element as the max element, and then compares all other elements
with the max element using compareTo() method of java.lang.Comparable
interface.
4) Finally the function returns an element which has the maximum value.
5) Stop the program and display the result.
Program:
class Lab10
{
public static <T extends Comparable<T>> T max(T... elements) {
T max = elements[0];
for (T element : elements) {
if (element.compareTo(max) > 0) {
max = element;
}
}
return max;
}
public static void main(String[] args) {
System.out.println("Integer Max: " + max(Integer.valueOf(32),
Integer.valueOf(56), Integer.valueOf(89), Integer.valueOf(3), Integer.valueOf(456),
Integer.valueOf(78), Integer.valueOf(45)));
System.out.println("Double Max: " + max(Double.valueOf(5.6),
Double.valueOf(7.8), Double.valueOf(2.9), Double.valueOf(18.6),
Double.valueOf(10.25), Double.valueOf(18.6001)));
System.out.println("String Max: " + max("Strawberry", "Mango", "Apple",
"Pomegranate", "Guava", "Blackberry", "Cherry", "Orange", "Date"));
}
}
Output:
Result:
Thus the implementation of generic function is achieved for finding the
maximum value from the given type of elements.
35
Ex.No:11 Design a calculator using event-driven programming
Date: paradigm of Java
Aim:
To develop a program that works as simple calculator using event-driven
programming paradigm of Java.
Algorithm:
1) Start the program
2) Create a class with the name “A” extends JFrame implements
ActionListener.
3) Declare the JButton ,JTextField ,JPanel variables.
4) Add listener to each button and to the layout.
5) Add Text Field to display the result.
6) Handle any Exceptions like divide by zero.
Program:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class A extends JFrame implements ActionListener
{
public JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16;
public JTextField tf1;
public JPanel p;
public String v = "";
public String v1 = "0";
public char op;
public A()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
p = new JPanel(new FlowLayout());
tf1 = new JTextField(10);
p.add(tf1);
add(p);
setLayout(new GridLayout(0, 3));
b1 = new JButton("1");
b1.addActionListener(this);
add(b1);
b2 = new JButton("2");
b2.addActionListener(this);
add(b2);
b3 = new JButton("3");
b3.addActionListener(this);
add(b3);
36
b4 = new JButton("4");
b4.addActionListener(this);
add(b4);
b5 = new JButton("5");
b5.addActionListener(this);
add(b5);
b6 = new JButton("6");
b6.addActionListener(this);
add(b6);
b7 = new JButton("7");
b7.addActionListener(this);
add(b7);
b8 = new JButton("8");
b8.addActionListener(this);
add(b8);
b9 = new JButton("9");
b9.addActionListener(this);
add(b9);
b10 = new JButton("0");
b10.addActionListener(this);
add(b10);
b11 = new JButton("+");
b11.addActionListener(this);
add(b11);
b12 = new JButton("-");
b12.addActionListener(this);
add(b12);
b13 = new JButton("*");
b13.addActionListener(this);
add(b13);
b14 = new JButton("/");
b14.addActionListener(this);
add(b14);
b16 = new JButton("%");
b16.addActionListener(this);
add(b16);
b15 = new JButton("=");
b15.addActionListener(this);
add(b15);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String b = ae.getActionCommand();
char ch=b.charAt(0);
switch (ch)
{
case '1':
{
v = v + "1";
tf1.setText(v);
}
break;
case '2':
37
{
v = v + "2";
tf1.setText(v);
}
break;
case '3':
{
v = v + "3";
tf1.setText(v);
}
break;
case '4':
{
v = v + "4";
tf1.setText(v);
}
break;
case '5':
{
v = v + "5";
tf1.setText(v);
}
break;
case '6':
{
v = v + "6";
tf1.setText(v);
}
break;
case '7':
{
v = v + "7";
tf1.setText(v);
}
break;
case '8':
{
v = v + "8";
tf1.setText(v);
}
break;
case '9':
{
v = v + "9";
tf1.setText(v);
}
break;
case '0':
{
v = v + "0";
tf1.setText(v);
}
break;
case '+':
{
38
op = '+';
v1 = tf1.getText();
v = "";
}
break;
case '-':
{
op ='-';
v1 = tf1.getText();
v = "";
}
break;
case '*':
{
op = '*';
v1 = tf1.getText();
v = "";
}
break;
case '/':
{
op = '/';
v1 = tf1.getText();
v = "";
}
break;
case '%':
{
op = '%';
v1 = tf1.getText();
v = "";
}
break;
case '=':
{
switch(op)
{
case '+':
{
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) + Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case '-':
{
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) -Long.parseLong(v);
39
tf1.setText(String.valueOf(i));
v="";
}
break;
case '*':
{
v = tf1.getText();
if (v.equals(""))
{
v = "0";
}
long i = Long.parseLong(v1) * Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}
break;
case '/':
{
try {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) / Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
break;
case '%':
{
try {
v = tf1.getText();
if (v.equals("")) {
v = "0";
}
long i = Long.parseLong(v1) % Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
break;
}
}
break;
}
}
}
public class Calc
{
public static void main(String[] args)
40
{
A a = new A();
}
}
Output:
Result:
Thus the design of calculator using event driven programming has been
implemented successfully.
41