cs3381 oops lab manual

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 87

ANNA UNIVERSITY,CHENNAI .

GKM
COLLEGE OF ENGINEERING AND TECHNOLOGY
(SPONSPERED BY SUGANTHI EDUCATIONAL TRUST)
(AN ISO ISO: 9001 :2005 CERTIFIDE, APPROVED BY AICTE ,AFFLIATED TO ANNA UNIVERSITY)
G.K.M NAGAR,New Perungalathur(Near Tambaram) Chennai-600 063.

ESTD.1996
(BACHELOR OF ENGINEERING)
DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING
And BIO-MEDICAL ENGINEERING

CS3381-OBJECT ORIENTED PROGRAMMING


SYSTEM
LAB MANUAL

Prepared
by
K.Sharmila devi
AP/CSE
LIST OF EXPRIMENTS:

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. Developer java application with an employee salary details.
4. Write a Java program to create an abstract class named Shape that contains two
integers and an empty methos named print Area().
5. Solve the above problem using an interface.
6. Implement exception handling and creation of user defined exceptions.
7. Write a java program the implements a multi-treaded application that has three
threads.First thread generates a random integer every1 second and if the value is even,
the value is odd, the third thread will print the value of the cube of the number.
8.Write a program to perform file operations.
9. Develop applications to demonstrate the features of generics classes.
10. Develop applications using Java FX controls, layouts and menus.
11. Develop a mini project for any application using java concepts.
Ex.No:1(a)
SEQUENTIALSEARCH
Date:

AIM:

TowriteaJavaProgramforsolving theproblembySequentialSearch.

ALGORITHM:

SequentialSearch( ArrayAr,Valuex)St
ep1:Setito1
Step 2: if i> n, then go to step 7Step
3: if Ar[i] = x then go to step
6Step4:Setitoi+1
Step5:GotoStep2
Step 6: Print Element x Found at index i and go to step
8Step7:Printelementnotfound
Step8:Exit

PROGRAM:
importjava.util.Scanner;
PublicclassSequential Search
{
Publicstaticvoidmain(String[]args)
{
inti,j,k,l=0;
Scanners=newScanner(System.in);
System.out.println("Enterthesizeofarray: ");
i=s.nextInt();
int[]ar =newInt[i];
for(j=0;j<i; j++){
System.out.println("No"+(j+1) +"=");
ar[j] =s.nextInt();
}
System.out.println("TotalInserted listis:");
for(j=0;j<i ; j++)
{
System.out.println("No "+(j+1)+"="+ar[j]);
}
System.out.println("Enterthenumber whichneedsto
find:");
k= s.nextInt();

for(j=0;j<i ; j++)
{
if(k==ar[j])
{
System.out.println("Found");
l=l+1;
break;
}
}
if(l==0)
{
System.out.println("DataNotFoundinthelist");
}
}
}
OUTPUT

RESULT:
Thusthejavaprogramforsolvingtheproblembysequentialsearchwasexecutedandtheoutputis

verified.
EX.NO.:1(b)
DATE: BINARYSEARCH

AIM:

TowriteaJavaProgramfor solvingtheproblembybinarysearch.

ALGORITHM:

Step1 :Readnnumbersand searchvalue.

Step2:Ifsearchvalueisequaltomiddleelementthenprintvalueis found.

Step3:Ifsearchvalueislessthanmiddleelementthensearchlefthalfoflistwiththesamemethod

Step4:Elsesearchrighthalfoflistwiththesamemethod.

PROGRAM:
BinarySearch.java

classBinarySearch
{
publicstaticintbinarySearch(intarr[],intfirst,intlast,intkey)
{
if(last>=first)
{
int mid = (first
+last)/2;if(arr[mid]==
key)
{
returnmid;
}
elseif(arr[mid]>key)
{
returnbinarySearch(arr,first,mid-1, key);
}
else
{
returnbinarySearch(arr,mid+1,last, key);

}
}
return-1;

}
publicstaticvoidmain(Stringargs[])
{
intarr[]={10,20,30,40,50};
intkey= 30;
intlast=arr.length-1;
intresult=binarySearch(arr,0,last,key);if
(result==-1)
System.out.println("Elementisnotfound!");
else

}
}
OUTPUT:

RESULT:

Thusthejavaprogramforsolvingtheproblem

byBinarySearchwasexecutedandtheoutputisverified.
EX.NO.:1(c)
DATE: INSERTIONSORT

AIM:

TowriteaJavaProgramforsolvingtheproblembyInsertionSorting.

ALGORITHM:

Step1 :Getthe nelementsto be sorted.

Step2:Theithelementiscomparedfrom(i-1)thto0thelement.

Step3:Thenplacedinproperpositionaccordingtoascendingvalue.Step3:

Repeatthe above stepuntilthelastelement.

PROGRAM:
InsertionSort.java

PublicclassInsertionSort
{
Publicstaticvoidmain(Stringargs[])
{
intnum[]={12,9,37,86,2,17,5};
inti,j,x;
System.out.println("ArraybeforeInsertionSort");f
or(i=0;i<num.length;i++)
{
System.out.print(num[i]+"");
}
for(i=1;i<num.length;i++)
{
x=num[i];j
=i-
1;while(j>=
0)
{

if(x<num[j])
{
num[j+1]=num[j];
}
else
{
}
j=j-1;
break;
}
num[j+1]=x;
}
System.out.print("\n\nArray after Insertion Sort\
n");for(i=0;i<num.length;i++)
{
System.out.print(num[i]+"");
}
}
}
OUTPUT:

RESULT:

ThusthejavaprogramforsolvingtheproblembyInsertionSortingwasexecutedandthe

outputisverified.
EX.NO.:1(d)
DATE: SELECTIONSORT

AIM:

TowriteaJavaProgramforsolvingtheproblembySelectionSorting.

ALGORITHM:
Step1:Startfromthefirstelementinthearrayandsearchforthesmallestelementinthearray.

Step2:Swapthefirstelementwiththesmallestelementofthearray.

Step3:Takeasubarray(excludingthefirstelementofthearrayasitisatitsplace).

Step4:Searchforthesmallestnumberinthesubarray(secondsmallestnumber oftheentirearray)

Step5:Thenswapitwiththefirstelementofthearray(secondelementoftheentirearray).Step6:Repeat

the steps 2and3withnew subarrays untilthe arraygetssorted.

PROGRAM:
SelectionSort.java

PublicclassSelectionSort
{
Publicstaticvoidselectionsort(int[]arr)
{
intn=arr.length;

for(inti=0;i<n-1;i++)
{
intmin=i;
for(intj=i+1;j<n;j++)
{
if(arr[j]<arr[min])
{
min=j;

}
}
inttemp=arr[i];
arr[i]=arr[min];
arr[min]=temp;
}
}
Publicstaticvoidmain(String[]args)
{
int[]arr={15,21,6,3,19,20};
System.out.println("ElementsinthearraybeforeSorting");

for(int i:arr)
System.out.print(i+"");s
electionsort(arr);
System.out.println("\
nElementsinthearrayafterSorting");for(inti:arr)

System.out.print(i+"");
}
}
OUTPUT:

RESULT:

ThusthejavaprogramforsolvingtheproblembySelectionSortingwasexecutedandthe

outputisverified
EX.NO.:2(a)
DATE: IMPLEMENTATIONOFSTACK

AIM:

Towriteajavaprogramfor implementationofstackdatastructures..

ALGORITHM:

Stack:
Itisalineardatastructurethatfollowsaparticularorderinwhichtheoperationsareperformed.

LIFO(LastInFirstOut):

BasicOperationsonStack

Inordertomakemanipulationsinastack,therearecertainoperationsprovidedtous.
 push()toinsertanelementintothestack
 pop()toremoveanelementfromthestack
 top()Returnsthetopelementofthestack.
 isEmpty()returnstrueisstackisempty elsefalse
 size()returnsthesizeofstack
Push:
Addsanitemtothestack.Ifthestackisfull,thenitissaidtobeanOverflowcondition.
Algorithmforpush:
begin
ifstackisfullre
turn
endif
else
incrementtopstack[top]
assignvalueendelse
endprocedure
Pop:
Removesanitemfromthestack.Theitemsarepoppedinthereversedorderinwhichtheyarepushed.
Ifthestackisempty,thenitissaidtobeanUnderflowcondition.
Algorithmforpop:
begin
ifstackisemptyre
turn
endif
else
storevalueofstack[top]de
crementtop
returnvalueen
delse
endprocedure
Top:
Returnsthetopelementofthestack.
AlgorithmforTop:
begin
returnstack[top]en
dprocedure
isEmpty:
Returnstrueifthestackisempty,elsefalse.
AlgorithmforisEmpty:b
egin
iftop<1return
true
else
returnfalsee
ndprocedure

PROGRAM:

importstaticjava.lang.System.exit;

//
StackclassusingLinkedListclas
sStack_Linkedlist{

//
DefineNodeofLinkedListpri
vateclassNode {
intdata; // node
dataNodenlink;//Nodeli
nk
}
// top of the
stackNodetop;
//
stackclassConstructorSta
ck_Linkedlist(){
this.top=null;
}

// push ()
operationpublicvoidpush
(intval){
//
createanewnodeNodetem
p=newNode();

//checksifthestackis
fullif(temp==null){
System.out.print("\
nStackOverflow");return;
}

// assign val to
nodetemp.data=
val;

//settopofthe stackto node


linktemp.nlink=top;

// update
toptop=tem
p;
}
//isEmpty()operation
publicbooleanisEmpty()
{returntop ==null;
}

//
peek()operationp
ublicintpeek(){
// check if the stack is
emptyif(!isEmpty()){
returntop.data;
}
else{
System.out.println("Stackisempty!");r
eturn-1;
}
}

//
pop()operationpu
blicvoidpop(){
//checkifstackisout
ofelementsif(top==null){
System.out.print("\
nStackUnderflow!!");return;
}
//settoptopoint
tonextnodetop=(top).nlink;
}

//
printstackcontentspublicv
oiddisplay(){
//
checkforstackunderflowif(t
op==null){
System.out.printf("\
nStackUnderflow!!");exit(1);
}
else{
Node temp =
top;System.out.println("Stackelements
:");while(temp!= null){
//
printnodedataSystem.out.print(tem
p.data+"->");
//
assigntemplinktotemptem
p= temp.nlink;
}
}
}
}

publicclassMain{publicstaticvoidmai
n(String[]args)
{
//Createastackclassobject
Stack_Linkedliststack_obj=newStack_Linkedlist();
// push values into the
stackstack_obj.push(9);stac
k_obj.push(7);stack_obj.pu
sh(5);stack_obj.push(3);sta
ck_obj.push(1);

//
printStackelementssta
ck_obj.display();

//printcurrentstacktop
System.out.println("\nStacktop:"+stack_obj.peek());

//Popelements
twiceSystem.out.println("Poptwoelemen
ts");stack_obj.pop();
stack_obj.pop();
//
printStackelementssta
ck_obj.display();
//printnewstacktop
System.out.println("\nNewStacktop:"+stack_obj.peek());
}
}

OUTPUT:

RESULT:

ThustheJavaProgramforstackimplementationwasexecutedandtheoutputwasverifi

ed.
EX.NO.:2(b)
DATE: QUEUEDATASTRUCTURE

AIM:
TowriteaJavaProgramforimplementQueueDatastructureusingclassesandobjects.

ALGORITHM:

Description:
Aqueuedatastructureisrepresentedasshownbelow:

Definetheoperationstobeperformedinthis queue.

Step 1 :Enqueue: An operation to insert an element in the queue is Enqueue


(functionqueueEnqueue in the program). For inserting an element at
the rearend, we need to first check if the queue is full. If it is full, then
wecannotinserttheelement.Ifrear<n,thenweinserttheelementinthequeue.

Step2: Dequeue:Theoperation
todeleteanelementfromthequeueisDequeue(functionqueueDequeueint
heprogram).First,wecheckwhetherthequeue is empty. For dequeue
operation to work, there has to be atleastoneelementinthequeue.

Step3:Front:Thismethodreturnsthefrontofthequeue.

Step4:Display:Thismethodtraversesthequeueanddisplaystheelementsofthequeue.

Javaprogramdemonstrates theArrayimplementationofQueue.

classQueue{
privatestaticintfront,rear,capacity;p
rivatestaticintqueue[];

Queue(intsize)
{front = rear =
0;capacity=size
;
queue=newint[capacity];
}

//insertanelementintothequeue
staticvoidqueueEnqueue(intitem){
//checkifthequeue
isfullif(capacity==rear){
System.out.printf("\nQueueisfull\
n");return;
}

//
insertelementattherearelse
{
queue[rear]=item;r
ear++;
}
return;
}

//
removeanelementfromthequeuestati
cvoidqueueDequeue(){
// check if queue is
emptyif(front== rear){
System.out.printf("\nQueueisempty\
n");return;
}

//shiftelementstotherightbyoneplaceuntilrearelse{
for(inti=0; i<rear-1;i++)
{queue[i]=queue[i+ 1];
}

// set queue[rear] to
0if(rear <
capacity)queue[re
ar]=0;

// decrement
rearrear--;
}
return;
}

// print queue
elementsstaticvoidqueue
Display()
{
Inti;
if(front==rear)
{System.out.printf("QueueisEmpty\
n");return;
}
//traversefront torearandprintelements
for(i = front; i< rear; i++)
{System.out.printf("%d=",queue[i]);
}
return;
}

// print front of
queuestaticvoidqueue
Front()
{
if(front==rear)
{System.out.printf("QueueisEmpty\
n");return;
}
System.out.printf("\nFront Element of the queue: %d",
queue[front]);return;
}
}

publicclassMain{publicstaticvoidmain(
String[]args){
//
Createaqueueofcapacity4Que
ue q= newQueue(4);

System.out.println("InitialQueue:");
//print
Queueelementsq.queu
eDisplay();

//
insertingelementsinthequeueq.qu
eueEnqueue(10);q.queueEnqueu
e(30);q.queueEnqueue(50);q.que
ueEnqueue(70);

//printQueueelements
System.out.println("QueueafterEnqueueOperation:");q.
queueDisplay();

//
printfrontofthequeueq.qu
eueFront();

//
insertelementinthequeueq.qu
eueEnqueue(90);

//
printQueueelementsq.q
ueueDisplay();
q.queueDequeue();
q.queueDequeue();
System.out.printf("\nQueueaftertwodequeueoperations:");
//
printQueueelementsq.q
ueueDisplay();

//
printfrontofthequeueq.qu
eueFront();
}
}

OUTPUT:

TheLinkedListimplementationofQueueinJava.

classLinkedListQueue
{
privateNodefront,
rear;privateintqueueSize;//queues
ize

//
linkedlistnodepriv
ateclassNode{intd
ata;
Nodenext;
}

//default constructor - initially front & rear are null; size=0; queue is
emptypublicLinkedListQueue()
{
front=null;rear
=
null;queueSize
=0;
}
//check if the queue is
emptypublicbooleanisEmpt
y()
{
return(queueSize==0);
}

//Removeitemfromthefront ofthe
queue.publicintdequeue()
{
intdata=front.data;f
ront=front.next;if(i
sEmpty())
{
rear =null;
}
queueSize--;
System.out.println("Element"+data+"removedfromthequeue");returndata;
}

//
Adddataattherearofthequeue.publicvoide
nqueue(intdata)
{
Node oldRear =
rear;rear =
newNode();rear.data
=
data;rear.next=null;if
(isEmpty())
{
front=rear;
}
else{
oldRear.next=rear;
}
queueSize++;
System.out.println("Element"+data+"addedtothequeue");
}
//print front and rear of the
queuepublicvoidprint_frontRear(
){
System.out.println("Frontofthequeue:"+front.data
+ " Rearofthe queue:"+rear.data);
}
}
classMain{publicstaticvoidmain(
Stringa[]){

LinkedListQueuequeue=newLinkedListQueue();q
ueue.enqueue(6);
queue.enqueue(3);queue.print_fr
ontRear();queue.enqueue(12);qu
eue.enqueue(24);queue.dequeue(
);queue.dequeue();queue.enqueu
e(9);

queue.print_frontRear();
}
}

OUTPUT:

RESULT:
ThusthejavaprogramforimplementationofQueueDatastructuresusingclassesandobjectswasexecut

edandtheoutputisverified.
EX.NO.:3
DATE: EMPLOYEEPAYROLLSYSTEM

AIM:
TocreateaJavaconsoleapplicationforemployeepayrollprocess
management.ThisprojectincludesEmployeeand theyfurtherclassified
asProgrammer,AssistantProfessor,AssociateProfessor,Professor.

ALGORITHM:

Step1: Inheritance is a mechanism that allows one class to inherit properties


orbehaviorsfromanotherclass.Multipleclassescaninheritfromthesameparentclass,formingatr
ee-likehierarchystructure.Step

Step2:Inheritingclassescanaddfeaturesbeyondthoseinheritedfromtheparentclasstoallowforuni
quebehavior.

Step 3 :.In Java, the parent class is called the superclass, and the inheritor class is
calledthesubclass. Developers
mayalsocallsuperclassesbaseorparentclassesandsubclassesderivedorchildclasses.

Step 4:Subclasses are linked to superclasses using the extendskeyword during


theirdefinition.Subclassescandefinenewlocalmethodsorfieldsto useorcanuse
thesuperkeywordtocallinheritedmethodsorthesuper constructor.

Step 5:super is essentially a “previous value” button called from within a child class
thatallows youtoreadandaccessfeatures
fromtheparentclassregardlessoftheirvalueinthecurrentchildclass.

PROGRAM:

PaySlip.java

importjava.util.Scanner;cl
assEmployee
{
StringEmp_name,Mail_id,Address,Emp_id,Mobile_no;do
ubleBP,GP,NP,DA,HRA,PF,CF;
Scannerget=newScanner(System.in);Emplo
yee()
{
System.out.println("EnterNameoftheEmployee:");
Emp_name=get.nextLine();

System.out.println("EnterAddressoftheEmployee:");Address=get.nex
tLine();
System.out.println("Enter
IDoftheEmployee:");Emp_id=get.nextLine();Syst
em.out.println("Enter Mobile
Number:");Mobile_no=get.nextLine();
System.out.println("EnterE-
MailIDoftheEmployee:");Mail_id=get.nextLine();
}
Voiddisplay()
{
System.out.println("Employee Name:
"+Emp_name);System.out.println("EmployeeAddress:
"+Address);System.out.println("Employee
ID:"+Emp_id);System.out.println("EmployeeMobileNumber:"+Mobil
e_no);System.out.println("Employee E-Mail
ID"+Mail_id);DA=BP*0.97;HRA=BP*0.10;PF=B
P*0.12;CF=BP*0.01
;GP=BP+DA+HRA;N
P=GP-PF-CF;
System.out.println("Basic
Pay :"+BP);System.out.println("Dearness Allowance :
"+DA);System.out.println("HouseRentAllowance:"+HRA);
System.out.println("ProvidentFund :"+PF);System.out.pr
intln("ClubFund:"+CF);

System.out.println("GrossPay:"+GP);S
ystem.out.println("NetPay:"+NP);
}
classProgrammerextendsEmployee
{
Programmer()
{
System.out.println("EnterBasicpayoftheProgrammer:");BP=g
et.nextFloat();
}
voiddisplay()
{
System.out.println("=============================="+"\n"+"ProgrammerPaySlip"+"\
n"+"=============================="+"\n");
super.display();
}
}
classAssistantProfessorextendsEmployee
{
AssistantProfessor()
{
System.out.println("EnterBasicpayoftheAssistantProfessor:");
BP=get.nextFloat();
}
voiddisplay()
{
System.out.println("=============================="+"\n"+"AssistantProfessorPaySlip"+"\
n"+"=============================="+"\n");
super.display();
}
}
classAssociateProfessorextendsEmployee
{
AssociateProfessor()
{
System.out.println("EnterBasicpayoftheProfessor:");BP=get.
nextFloat();
}
voiddisplay()
{
System.out.println("=============================="+"\n"+"AssociateProfessorPaySlip"+"\
n"+"=============================="+"\n");
super.display();
}
}
classProfessorextendsEmployee
{
Professor()
{
System.out.println("Enter
BasicpayoftheProfessor:");BP=get.nextFloat();
}
voiddisplay()
{
System.out.println("=============================="+"\n"+"ProfessorPaySlip"+"\
n"+"=============================="+"\n");
super.display();
}
}
classPayslip
{
publicstaticvoidmain(String[]args)
{
charans;Scannersc=newScanner(Syste
m.in);do
{
System.out.println("MainMenu");
System.out.println("1.Programmer\n2.AssistantProfessor\n3.AssociateProfessor\
n4.Professor");
System.out.println("Enteryourchoice:");intchoice=sc.nextInt(
);
switch(choice)
{
case1:
Programmerp=newProgrammer();p.display()
;
break;
case2:
AssistantProfessorap=newAssist
antProfessor();ap.display();
case3:break;

AssociateProfessorasp=newAssociateProfessor();
asp.display();
case4:break;

ProfessorPR=newProfessor();
PR.display();
} break;
System.out.println("Do
youwanttogotoMainMenu?(y/n):");ans=sc.next().charAt(0)
;
}while(ans=='y'||
ans=='Y');sc.close();
}
}

OUTPUT:

RESULT:
Thejavaconsoleapplicationforemployeepayrollsystemwasdevelopedandtestedsuc

cessfully.
Ex.No:4
JAVAAPPLICATIONTOFINDAREAOFDI
Date:
FFERENTSHAPES

AIM:

TocreateaJavaconsoleapplicationtofindtheareaofdifferentshapes
usingabstract

ALGORITHM:

Step1: StarttheProcess
Step 2:Prompt user with List Operation
Choices1.Rectangle 2.Triangle
3.Circle,4.ExitGetthech
oicefromuser.
Step3: Ifuser selectsRectangle
Step3.1Getthe LengthandBreathfromthe user
Step3.2ComputeArea=Length*Breath
Step3.3DisplayAreaSte
p4:IfuserselectsTriangle
Step4.1:GettheLengthand
HeightfromtheuserStep4.2 :Compute Area =
Length *Height * 0.5Step4.3:DisplayArea
Step5:Ifuser selectsCircle
Step5.1:GettheRadiusoftheCircle
Step5.2:ComputeArea=3.14*Radius*Radius
Step5.3:DisplayArea
Step6:Ifuserselectsexitendtheprocess
Step7:Stopthe Process

PROGRAM:
AbstractArea.java

importjava.util.*;ab
stractclassShape
{
inta,b;
abstractvoidprintArea();

}
classRectangleextendsShape
{
voidprintArea()
{
System.out.println("\t\tCalculatingAreaofRectangle");
Scannerinput=newScanner(System.in);System.out.print("Enterlength:");a=
input.nextInt();System.out.print("\nEnterbreadth:");
b=input.nextInt();

intarea=a*b;
System.out.println("AreaofRectangle:"+area);
}
}
classTriangleextendsShape
{
voidprintArea()
{
System.out.println("\t\
tCalculatingAreaofTriangle");Scannerinput=new
Scanner(System.in);System.out.print("Enterheight:");
a=input.nextInt();System.out.println("\
nEnterbreadth:");b=input.nextInt();
doublearea=0.5*a*b;System.out.println("Area
ofTriangle:"+area);
}
}
classCircleextendsShape
{
voidprintArea()
{
System.out.println("\t\
tCalculatingAreaofCircle");Scannerinput=new
Scanner(System.in);System.out.print("Enter radius:
");a=input.nextInt();
doublearea=3.14*a*a;

System.out.println("AreaofCircle:"+area);
}
}
classAbstractArea
{
publicstaticvoidmain(String[]args)
{
Shapeobj;
obj=newRectangle();
obj.printArea();obj=n
ew
Triangle();obj.printA
rea();obj=new
Circle();obj.printArea
();
}
}

OUTPUT:

RESULT:

Thejavaconsoleapplicationforemployeepayrollsystemwasdevelopedandtestedsu

ccessfully.
EX.NO.:5
DATE: INTERFACE

AIM:

TocreateaJavaconsoleapplicationtofindtheareaofdifferentshapes
usingInterfaceconceptinjava.

ALGORITHM:

Step1 :Createtheinterfaceclassnamedshapethatcontainstwointegersandanemptymethodnamedprintar
ea().

Step2:Providethreeclassesnamedrectangle,triangleandcirclesuchthateachoneofThe classes
extends the class Shape.

Step3:Eachoftheinheritedclass
fromshapeclassshouldprovidetheimplementationforThemethodprintarea().

Step4:Gettheinputandcalculatetheareaofrectangle, circleandtriangle.

Intheshapeclass,createtheobjectsforthethreeinheritedclassesandinvokethemethodsanddisplay
theareavaluesofthedifferentshapes

PROGRAM:
TestArea.java
importjava.util.Scanner;i
nterface Shape
{
PublicvoidprintArea();
}
ClassRectangleimplementsShape
{
PublicvoidprintArea()
{
System.out.println("\t\
tCalculatingAreaofRectangle");Scannerinput=newScanner(S
ystem.in);System.out.print("Enterlength:");
inta=input.nextInt();System.out.print(
"\nEnter breadth:
");intb=input.nextInt();
intarea=a*b;System.out.println("AreaofRectangle:
"+area);
}
}
ClassTriangleimplementsShape
{
PublicvoidprintArea()
{
System.out.println("\t\
tCalculatingAreaofTriangle");Scannerinput=new
Scanner(System.in);System.out.print("Enterheight:");
inta=input.nextInt();System.out.print(
"\nEnter breadth:
");intb=input.nextInt();
double
area=0.5*a*b;System.out.println("AreaofTriangle:
"+area);
}
}
ClassCircleimplementsShape
{
PublicvoidprintArea()
{
System.out.println("\t\
tCalculatingAreaofCircle");Scannerinput=new
Scanner(System.in);System.out.print("Enterradius
:");inta=input.nextInt();
doublearea=3.14*a*a;System.out.println("Areaof
Circle:"+area);
}
}

PublicclassTestArea
{
Publicstaticvoidmain(String[]args)
{
Shapeobj;obj=newR
ectangle();obj.printA
rea();obj=new
Triangle();obj.print
Area();obj=new
Circle();obj.printAre
a();
}
}
OUTPUT:

RESULT:

Thejavaconsoleapplicationfor employeepayrollsystemwasdevelopedandtestedsuccessfully.
EX.NO.:6
USERDEFINEDEXCEPTIONHANDLING
DATE:

AIM:
TocreateaJava consoleapplicationfor
Bankingtransactionsystemusingexceptionhandlingtechniques.

ALGORITHM:

Step1:CreateaclasswhichextendsExceptionclass.
Step2:Createaconstructorwhichreceivesthestringasar
gument.

Step3:GettheAmountasinputfromtheuser.
Step4:Iftheamountisnegative,theexceptionwill be generated.
Step5:Usingtheexceptionhandlingmechanism,thethrownexceptionisHandledbythe
catchconstruct.
Step6:Aftertheexceptionishandled,thestring“invalidamount“willbedisplayed.
Iftheamountisgreaterthan0,the message“AmountDeposited“willbedisplayed.
PROGRAM:
UserDefinedException.java

importjava.util.*;classNegativeAmtExceptionext
endsException
{
Stringmsg;NegativeAmtException(String
msg)
{
this.msg=msg;
}
publicStringtoString()
{
returnmsg;
}
}
classBankAccount
{
Privatedoublebalance;p
rivateintaccountNumbe
r;
publicBankAccount(int
accountNumber,doubleinitialBalance)throwsN
egativeAmtException
{
if(initialBalance<0)
thrownewNegativeAmtException("Initialamountshouldnotbenegative!")
;
balance
=initialBalance;this.accountNumber=accountNum
ber;
}
Publicvoiddeposit(doubleamount)throwsNegativeAmtException
{
if(amount<0)
{
ThrownewNegativeAmtException("Don'tdepositnegativeamount!");
}
balance
=balance+amount;System.out.println("Amountdeposited");S
ystem.out.println("Balanceamount:"+getBalance());
}
Publicvoidwithdraw(doubleamount) throwsNegativeAmtException
{
if(amount<0)
{
thrownewNegativeAmtException("Don'twithdrawanegativeamount!")
;
}
elseif(amount<=balance)
{
balance=balance–amount;
}
else
{
System.out.println("Insufficientamount");
}
System.out.println("Balanceamount:"+getBalance());
}
PublicdoublegetBalance()
{
returnbalance;
}
PublicintgerAccountNumber()
{
returnaccountNumber;
}
PublicStringtoString()
{
return"AccountNumber:"+accountNumber+"Balance:"+balance;
}
}
PublicclassUserDefinedException
{
Publicstaticvoidmain(String[]args)
{
intch,amt;
Scannersc=new
Scanner(System.in);System.out.print("Enter
AccountNumber:");inta=sc.nextInt();System
.out.print("EntertheinitialAmount:");intb=sc.
nextInt();
BankAccount
ac;try
{
ac=newBank Account(a,b)
;while(true)
{
System.out.println("MainMenu");System.out.println("1.Deposit\n2.Withdraw\
n3.CheckBalance
\n4.Display \
n5.Exit");System.out.print("EnteryourChoice:
");ch=sc.nextInt();
switch(ch)
{
case1:
System.out.print("Entertheamounttodeposit:");
amt=sc.nextInt();
ac.deposit(amt);
break;
case2:
System.out.print("EntertheamounttoWit
hdraw:");
amt=sc.nextInt();a
c.withdraw(amt);
case3: break;

System.out.println("Balanceamount:"
+ac.getBalance());
break;

case4:

System.out.println("Youraccountdetails\
n"+ac);
break;
case5:
sc.close();Syst
em.exit(0);
default:
System.out.println("InvalidChoice");
}
}
}
catch(NegativeAmtExceptione)
{
System.out.println("ExceptionCaught:"+e);
}
}
}
OUTPUT:

RESULT:
The javaconsoleapplicationthatusesuserdefined
exceptionhandlingtechniqueswasdevelopedandtestedsuccessfully.
EX.NO.:7
MULTITHREADING
DATE: IMPLEMENTATION

AIM:

TocreateaJavaconsoleapplicationtheusesthemultithreadingconceptsinjava.

ALGORITHM:

Step1:Createaclassevenwhichimplementsfirstthreadthatcomputes.thesquareofthenumber.Step2:r

un()methodimplementsthecodetobeexecutedwhenthreadgetsexecuted.

Step3:Createaclassoddwhichimplementssecondthreadthatcomputesthecubeofthenumber.

Step4:Createathirdthreadthat generatesrandomnumber.Iftherandomnumberiseven,It
displays the square of the number.If the random number generated is odd ,
itdisplaysthecubeofthe givennumber.

Step5:TheMultithreading

isperformedandthetaskswithedbetweenmultiplethreads.Step6:Thesleep()method

makesthethreadtosuspendforthespecified time
.
PROGRAM:
MultiThread.java
import java.util.*;
classevenimplementsRunnable
{
Publicintx;Pu
bliceven(intx)
{
this.x=x;
}
Publicvoidrun()
{
System.out.println("NewThread"+x+"isEVENandSquareof"+x+"is:"
+x*x);
}
}
ClassoddimplementsRunnable
{
Publicintx;Public
odd(intx)
{
this.x=x;
}
Publicvoidrun()
{
System.out.println("NewThread"+x+"isODDandCubeof"+x+"is:"+x*x*x);
}
}
class AextendsThread
{
Publicvoidrun()
{
intnum=0;Randomr=new
Random();try
{
for(inti=0;i<5;i++)
{
num=r.nextInt(100);System.out.println("MainThreadandGeneratedNumberis"
+
num);if(num
%2==0)
{
Threadt1=newThread(neweven(num));t1.start(
);
}
els
e
{ Threadt2=newThread(newodd(num));t2.start()
;
}
Thread.sleep(1000);
System.out.println(" ");
}
}
catch(Exceptionex)
{
System.out.println(ex.getMessage());
}
}
}
PublicclassMultiThread
{
Publicstaticvoidmain(String[]args)
{
Aa=newA();
a.start();
}
}
OUTPUT:

RESULT

Thejavaconsoleapplicationformultithreadingwasdevelopedandtest

edSuccessfully.
EX.NO.:8
FILEOPERATIONS
DATE:

AIM

TocreateaJavaconsoleapplicationtohandlethefilesandfindthefileproperties[Availabilit

y,ReadableorWriteableorBoth,LengthoftheFile].

ALGORITHM:

Step1Startthe Process
Step2Prompttheuserto enterthe filenamewithpath
Step3Get thefilename
Step3.1 Checkthefileisexits
Step3.2 If fileexists then proceed to step3.3else proceed to
3.8Step3.3 Check theFileisBothReadableandWriteableStep3.4
Ifyesdisplayfileis“ReadandWriteable”
Step3.5

Elsecheckisreadableifyesdisplay“ReadOnly”elseMov
etostep3.6
Step3.6 Elsecheck iswriteable ifyesdisplay“WriteOnly”
Step3.7 Computefilesizeanddisplay
PROGRAM Step3.8 Iffilenotexistingthendisplay“FileNotFound”
Step4StoptheProcess

UserFileHandler.java

import java.io.File;
publicclassUserFileHandler{
FileaFile;
booleanisReadable =
false;booleanisWriteable=f
alse;booleanisExists=false;
intlength=0;
publicUserFileHandler(Stringpath)
{
aFile=newFile(path);this.is
Exists=aFile.exists();
this.isReadable =
aFile.canRead();this.isWriteable=
aFile.canWrite();this.length=(int)
aFile.length();
}
publicvoid fileDetails()
{
if(isExists)
{
System.out.println("TheFile"+aFile.getName()
+"isAvailableat:"+aFile.getParent());if(isReadable&&isWriteable)
System.out.println("FileisReadableandWriteable");
elseif(isReadable)

System.out.println("FileisOnlyReadable");

elseif(isWriteable)
System.out.println("FileisOnlyWriteable");System.out.println("Totallengthofthefilei
s:"+this.length+"bytes"
);
}
else
System.out.println("Filedoesnotexists");

}
}

Main.java
importjava.io.File;impor
tjava.util.Scanner;
importcom.raja.oopslab.files.*;
publicclass Main{

publicstaticvoidmain(String[]args)
{
String file_path=null;
Scannerinput=newScanner(System.in);Syste
m.out.println("File
Handler");System.out.println("***********
*");System.out.println("Enter the
filepath");file_path
=input.next();newUserFileHandler(file_path
).fileDetails();
}
}

OUTPUT

Avalibility offile
FileReadandWriteable:

FileReadandWriteable:
Filesize

FileNotExists:

RESULT

The javaconsoleapplicationforhandlingfileswasdevelopedandtestedsuccessfully.
Ex.No:9
JAVAAPPLICATIONFORGENERICMAXFINDER
Date:

AIM

TocreateaJavaconsoleapplicationthatfindsthemamaximumin aarraybased onthetypeofThe

elements usinggenericfunctionsinjava.

ALGORITHM:

Step1 StarttheProcess
Step2 Createaarrayofnumberandarrayofstringsandpassitto genericfunction.
Step3 Ifthe arrayisIntegertype
Step3.1 AssumefirstelementasMAX
Step3.2 Compare[NumericPerspetive]thiselement withMAX
Step3.3 IfitisgreaterthanMAXthenstorecurrentelementasMAX
Step3.4 Elsedonothing
Step3.5 Gotostep3.1untilallthe elementshasbeenprocessed.
Step4 Ifthe arrayisString type
Step4.1 AssumefirstelementasMAX
Step4.2 Compare [Dictionary Perspective] this element with
MAXStep4.3IfitisgreaterthanMAXthenstorecurrentelement
asMAX
Step4.4 Elsedonothing
Step4.5 Goto step3.1untilalltheelementshasbeenprocessed.
Step5 StoptheProcess

PROGRAM:

ClassGenericMax
{
public<TextendsComparable<T>>voidmaxFinder(T[]array)
{Tmax=array[0];
for(Telement:array){
System.out.println(element);if(element
.compareTo(max)>0)
max=element;
}
System.out.println("Maxis:"+max);
}
}
publicclassMain{

public static void main(String[] args)


{GenericMaxmax=newGenericMax();Integ
er[]numbers
={14,3,42,5,6,10};

String[]strings=
{"R","Ra","Raj"};max.maxFinder(numbers);max.maxFinder(strin
gs);
}

OUTPUT:

RESULT:

Thejavaconsoleapplicationfor
findinggenericmaxofgivenelementswasdevelopedandtestedsuccessfully.
EX.NO.:10(a)
DATE: MULTIPLECHOICETESTQUESTIONINJ
AVAFX

AIM:

TocreateaJavaFXconsoleapplicationmultiplechoicetestquestionusingradiobuttons.

ALGORITHM:

Step1:RadioButtoncanbeaddedto ToggleGroupsothattheuser cannotselectmorethanone item.

Step2:Theselected itemofatogglegroupcanbefound

usinggetSelectedToggle()function.Step3:ConstructorsoftheRadioButtonclass:

Step 3.1 :RadioButton():Creates a radio button with an empty string for its

label.Step3.2:RadioButton(String t):Createsaradiobuttonwiththespecified

textasitslabel

Step4:

Method explanation
getText() returnsthetextLabelfor radiobutton
isSelected() returnswhether theradiobuttonisselectedornot
setSelected(booleanb) setswhethertheradiobuttonisselected ornot
setToggleGroup(ToggleGrouptg
setsthe toggle groupfortheradiobutton
)
Togglesthestateoftheradiobuttonifand only ifthe
fire()
RadioButtonhasnotalreadyselectedoris notpartofaToggleGroup
PROGRAM:
importjavafx.application.Application;importstaticjavafx.a
pplication.Application.launch;importjavafx.scene.Scene;i
mportjavafx.scene.control.Button;importjavafx.scene.cont
rol.Label;importjavafx.scene.control.RadioButton;importj
avafx.scene.control.ToggleGroup;importjavafx.scene.layo
ut.VBox;
importjavafx.stage.Stage;publicclassMCTestextendsAppli
cation
{
@Overridepublicvoidstart(Stageprimary
Stage)
{
primaryStage.setTitle("TestQuestion1");
Labellabelfirst=newLabel("Whatis10+20?");Labellabelresponse
=new Label();
Buttonbutton=newButton("Submit");RadioButtonrad
io1,radio2,radio3,radio4;radio1=new
RadioButton("10");
radio2= new
RadioButton("20");radio3=new
RadioButton("30");radio4=new
RadioButton("40");

ToggleGroupquestion1=newToggleGroup();ra
dio1.setToggleGroup(question1);radio2.setTo
ggleGroup(question1);radio3.setToggleGroup
(question1);radio4.setToggleGroup(question1
);

button.setDisable(true);
radio1.setOnAction(e ->button.setDisable(false)
);radio2.setOnAction(e->button.setDisable(false)
);radio3.setOnAction(e->button.setDisable(false)
);radio4.setOnAction(e-
>button.setDisable(false));

button.setOnAction(e->
{
if(radio3.isSelected())
{
labelresponse.setText("Correctanswer");button.setDisable(true
);
}
else
{
labelresponse.setText("Wronganswer");button.setDisable(true)
;
}
});
VBoxlayout=newVBox(5);layout.getChildren().addAll(labelfirst,radio1,radio2,radio3,r
adio4,button,labelrespon se);
Scenescene1=newScene(layout,400,250);pri
maryStage.setScene(scene1);primaryStage.
show();
}
publicstaticvoidmain(String[]args)
{
launch(args);
}
}
OUTPUT:

RESULT:

TheJavaFXconsoleapplicationforcreatingformwithradiobuttonswasdevelopedandt

estedsuccessfully.
EX.NO.:10(b)
DATE: SIMPLEEDITORUSINGJAVAFX

AIM:

TocreateaJavaFXconsoleapplicationsimpleeditorusingMenubar.

ALGORITHM:

Step1:MenuBar():createsanewemptymenubar.

Step2:MenuBar(Menu…m):createsanewmenubar withthegivensetofmenu.

Step3:Menu(): createsanemptymenu

Step4:Menu(Strings):createsamenuwithastringasitslabel

Step5:Menu(Strings,Noden):ConstructsaMenuand setsthedisplaytextwiththespecifiedtextandsets

thegraphicNodetothegivennode.

Step6:Menu(Strings,Noden,MenuItem…i):ConstructsaMenuandsetsthedisplaytextwiththe

specified text, the graphic Node to the given node, and inserts the given items into

theitemslist.
PROGRAM:
importjavafx.application.Application;im
portjavafx.event.ActionEvent;importjav
afx.event.EventHandler;importjavafx.st
age.Stage;importjavafx.scene.Scene;im
portjavafx.scene.control.Label;importja
vafx.scene.control.Menu;importjavafx.s
cene.control.MenuBar;importjavafx.sce
ne.control.MenuItem;importjavafx.scen
e.layout.VBox;publicclassMenuUI
extendsApplication{@Overridepublicvoidstart(StageprimaryStage)throwsEx
ception
{
Menunewmenu
=newMenu("File");Menu newmenu2
=newMenu("Edit");MenuItemm1=newMe
nuItem("Open");MenuItem m2 =
newMenuItem("Save");MenuItem m3 =
newMenuItem("Exit");MenuItem m4 =
newMenuItem("Cut");MenuItemm5=new
MenuItem("Copy");MenuItem m6 =
newMenuItem("Paste");newmenu.getItem
s().add(m1);newmenu.getItems().add(m2);
newmenu.getItems().add(m3);newmenu2.
getItems().add(m4);newmenu2.getItems().
add(m5);newmenu2.getItems().add(m6);M
enuBarnewmb=new
MenuBar();newmb.getMenus().add(newmenu);newmb.getMenus().add(
newmenu2);
Label l = new Label("\t\t\t\t\t\t+ "You have selected no
menuitems");EventHandler<ActionEvent>event=newEventHandler<ActionEvent>()
{publicvoidhandle(ActionEvente)
{
l.setText("\t\t\t\t\t\t"+((MenuItem)e.getSource()).getText()
+"menuitemselected");
}
};
m1.setOnAction(event);
m2.setOnAction(event);
m3.setOnAction(event);
m4.setOnAction(event);
m5.setOnAction(event);
m6.setOnAction(event);
VBoxbox= new
VBox(newmb,l);Scene scene =
newScene(box,400,200);primaryStage.s
etScene(scene);
primaryStage.setTitle("JavaFXMenu");
primaryStage.show();
}
publicstaticvoidmain(String[]args)
{Application.launch(args);
}
}
OUTPUT:

RESULT:

TheJavaFXconsoleapplicationforcreatingsimpleeditorwithmenubarw

asdevelopedandtestedsuccessfully.
Ex.No:11
MINIPROJECTFORCALCULATOR
Date: APPLICATION

AIM

TocreateaJavaGUIapplicationforthebasicandadvancedfunct

ionalitiesofa scientificcalculator.

ALGORITHM:

Step1Startthe Process
Step2DisplayTextViewand Number Pad andOptionPads
Step3Ifuser pressesanynumbergettheexistingnumbers
inTextView addthemupanddisplay
Step4Ifuserpress Operators
Step4.1GettheTextViewcontentasOperant1 andSet thedisplaytonull.
Step4.2 If user pressed “+”
buttonoperatorasplus
Step4.3 Ifuser pressed
“-”buttonsetoperatorasminus
Step4.4 Ifuser
pressed“x”buttonsetoperator
asmultiply
Step4.5

Ifuserpressed“/”buttonsetop
eratorasdivide.
Step4.6 Gotostep 3
Step5Ifuserpressed“=”buttonthenproceed followingsteps.
Step5.1 GettheTextViewcontentasOperant2andSetthe
displaytonull.
Step5.2Ifoperator is
“plus”thendisplayTextViewasOperant1+Operant2
Step5.3Ifoperatoris“minus”thendisplayTextViewasOpera
nt1-Operant2
Step5.4Ifoperatoris“multiply”thendisplayTextViewasOperant1*Operant2
Step5.5Ifoperatoris“divide”thendisplayTextViewasOperant1/Operant2
Step5.6Go tostep4
Step6Ifadvancedbuttonpressed
Step6.1ChangeOperantTypes[+,-,x,/intosin,cos,tan,log] andgotostep2
Step7Ifuserpressedanyofthe operator
Step7.1GettheTextViewcontentasOperant1andSetthedisplaytonull.
Step7.2Ifuserpressed“sin”buttonsetdisplaythesinvalueofOperant1
Step7.3 If user pressed “cos” button set display the cos value
ofOperant1
Step7.4If user pressed “tan” button set display the tan value
ofOperant1
Step7.5Ifuserpressed “log”buttonset displaythelog
valueofOperant1
Step7.6Gotostep7
Step8 Ifadvanced pressed againthenrevert thebuttonchangesand
returnbacktonormal
Step9 Repeat the process until user presses the close
buttonThenStoptheProcess.

PROGRAM:

importjava.awt.BorderLayout;
importjava.awt.Button;importj
ava.awt.Font;
importjava.awt.Frame;impor
t
java.awt.GridLayout;importj
ava.awt.Panel;importjava.a
wt.TextField;
importjava.awt.event.ActionEvent;imp
ort
java.awt.event.ActionListener;importja
va.awt.event.WindowAdapter;importja
va.awt.event.WindowEvent;importjava
.awt.event.WindowListener;

classNumpanextendsPanelimplementsActionListener{

Buttonn0,n1,n2,n3,n4,n5,n6,n7,n8,n9,point,equal;
Buttonplus,minus,multiply,divide;
Buttonm_plus,m_minus,clear,advanced;TextFiel
ddisplay;
String
op1,op2,result;Stringop_flag;St
ringdata;double
dop1,dop2,dresult;booleanflag_advanced=tr
ure;
publicNumpan(TextFielddisplay){this.display
=display;setLayout(newGridLayout(0,4));

n0=newButton("0");n0.setActionCommand("zero");
n0.addActionListener(this);

n1=newButton("1");n1.setActionCommand("one");n
1.addActionListener(this);

n2=newButton("2");n2.setActionCommand("two");n
2.addActionListener(this);

n3=newButton("3");n3.setActionCommand("three");
n3.addActionListener(this);

n4=newButton("4");n4.setActionCommand("four
");n4.addActionListener(this);

n5=newButton("5");n5.setActionCommand("five");n
5.addActionListener(this);

n6=newButton("6");n6.setActionCommand("six");n6
.addActionListener(this);
n7=newButton("7");n7.setActionCommand("seven")
;n7.addActionListener(this);

n8=newButton("8");n8.setActionCommand("eight");
n8.addActionListener(this);

n9=newButton("9");n9.setActionCommand("nine");
n9.addActionListener(this);

point=newButton(".");point.setActionCommand("poi
nt");point.addActionListener(this);

equal =
newButton("=");equal.setActionCommand("equal");
equal.addActionListener(this);
plus=newButton("+");plus.setAction
Command("plus");plus.addActionLi
stener(this);

minus=newButton("-");minus.setActionComman
d("minus");minus.addActionListener(this);

multiply=newButton("x");multiply.setActi
onCommand("multiply");multiply.addActi
onListener(this
);

divide
=newButton("/");divide.setActionCo
mmand("divide");divide.addActionL
istener(this);

m_plus=newButton("M+");m_plus.setActi
onCommand("m_plus");m_plus.addAction
Listener(this);

m_minus=newButton("M-");m_minus.setActionCommand("m_minus")
;m_minus.addActionListener(this);

clear=newButton("C");clear.setActionCo
mmand("clear");clear.addActionListener(t
his);

advanced=newButton("ADV");advanced.s
etActionCommand("advanced");advanced.
addActionListener(this);

add(m_plus);a
dd(m_minus);a
dd(clear);add(a
dvanced);add(n
1);
add(n2);
add(n3);a
dd(plus);a
dd(n4);
add(n5);add
(n6);add(mi
nus);add(n7
);
add(n8);
add(n9);add(
multiply);add(
point);add(n0)
;add(equal);ad
d(divide);
}
publicStringgetDisplayText()
{returndisplay.getText().toString();
}
public void setDisplay(Stringtext)
{display.setText(text);
}
publicvoid
clearDisplay()
{System.out.println("Clear
Called");setDisplay("");data="";
}

publicvoidchangeAdvanced(booleant
oAdvanced){if(toAdvanced){
plus.setLabel("sin");plus.setActionComma
nd("sin");
//
System.out.println("cosin");minus.setLabe
l("cos");minus.setActionCommand("cos")
;
//
System.out.println("cosout");multiply.setLabel("tan");multiply.s
etActionCommand("tan");divide.setLabel("log");divide.setActio
nCommand("log");

}
else
{ plus.setLabel("+");plus.setActionComma
nd("plus");minus.setLabel("-");minus.set
ActionCommand("minus");multiply.setL
abel("x");multiply.setActionCommand("
multiply");divide.setLabel("/");divide.set
ActionCommand("divide");

}
}
@Override

public void actionPerformed(ActionEvent e) {data

=getDisplayText();switch(e.getActionCommand()){

data=getDisplayText();switch(e.getActionCommand())

{case “zero”

setDisplay(data+"0");break;ca
se"one":
setDisplay(data+"1");break;ca
se"two":
setDisplay(data+"2");break;ca
se"three":
setDisplay(data+"3");break;ca
se"four":
setDisplay(data+"4");break;ca
se"five":
setDisplay(data+"5");break;ca
se"six":
setDisplay(data+"6");break;ca
se"seven":
setDisplay(data+"7");break;ca
se"eight":
setDisplay(data+"8");break;ca
se"nine":
setDisplay(data+"9");break;

case"plus":
op1 = data;op_flag
="plus";clearDisplay();break;
case"minus":
op1=data;op_flag="minus";clearDispla
y();break;
case"multiply":
op1=data;
op_flag=
"multiply";clearDisplay();break;case"d
ivide":
op1=
data;op_flag="divide";clearDisplay();b
reak;
case"clear":
clearDisplay();break;case"adv
anced":
if(flag_advanced){
changeAdvanced(true);flag_advanced=false
;
break;

case"cos":
op1 = data;setDisplay(String.valueOf(Math.cos(Double.valueOf(op1))));
break;case"tan":
op1=data;setDisplay(String.valueOf(Math.tan(Double.valueOf(op1))));break;
case"log":
op1 = data;setDisplay(String.valueOf(Math.log(Double.valueOf(op1))));
break;case"equal":
switch(op_flag){case"plus":
op2=data;clearDisplay();
dop1 = Double.parseDouble(op1);dop2
=Double.parseDouble(op2);dresult = dop1
+dop2;result =
String.valueOf(dresult);setDisplay(result);op_flag="
";break;
case"minus":
op2=data;clearDisplay();
dop1 = Double.parseDouble(op1);dop2
=Double.parseDouble(op2);dresult=dop1-
dop2;result =
String.valueOf(dresult);setDisplay(result);op_flag="
";break;

case"multiply":

op2 =
data;clearDisp
lay();
dop1 = Double.parseDouble(op1);dop2
=Double.parseDouble(op2);dresult=dop1*
dop2;result =
String.valueOf(dresult);setDisplay(result);op_flag="
";break;

case"divide":
op2=data;clear
Display();
dop1 = Double.parseDouble(op1);dop2

=Double.parseDouble(op2);dresult=dop1/dop2;resul
t=
String.valueOf(dresult);setDisplay(result);op_flag="
";break;

}
}
}
}

classCalculatorextendsFrame
{TextFielddisplay;
publicCalculator(){
display=newTextField();display.setFont(newFont("TimesNewRoman",Font.BOLD,50));setLay
out(newBorderLayout());
add(newNumpan(display),BorderLayout.CENTER);add(display,BorderLayout.N
O RTH);setVisible(true);
setSize(500,500);
addWindowListener(new WindowAdapter()
{@OverridepublicvoidwindowClosing(WindowEvente){dispose();
}
});
}
}
publicclassMain{

publicstaticvoidmain(String[]args){newCalculator();
}

OUTPUT:

Calculator:
BasicOperations:Add

ition[12+12]
Subraction[90-32]:
Multiplication[36X2]:
Division[45/2]:
ScientificOperations:

Sin30
Cos40:
Tan23:
Log 60:

RESULT:

ThejavaGUIapplicationforcalculatorwithbasic

andadvancedfunctionalitiesWasdevelopedandtestedsuccessfully.

You might also like