Java Lab Manual
Java Lab Manual
(AnAutonomousInstitution)
BharathiSalai,Ramapuram, Chennai-89
ACADEMICYEAR:2023-2024
ODD SEMESTER
LABMANUAL
231CBC312L
Tobuildsoftwaredevelopmentskillsusingjavaprogrammingforreal-world
applications.
Tounderstandandapplytheconceptsofclasses,packages,interfaces,arraylist,
exception handling and file processing.
Todevelopapplicationsusinggenericprogrammingandeventhandling.
LIST OFEXPERIMENTS:
1. Develop a Java application to generate Electricity bill. Create a class with the following
members: Consumer no., consumer name, previous month reading, current monthreading,
type of EB connection (i.e domestic or commercial). Compute the bill amount using the
following tariff.
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. Design a Java interface for ADT Stack. Implement this interface using array. Provide
necessary exception handling in both the implementations.
5. Writeaprogram toperformstringoperationsusingArrayList. Writefunctionsforthe
following
a. Append-addatend
b. Insert–addatparticularindex
c. Search
d. Listallstringstartswithgivenletter
6. 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 given shape.
8. 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.
9. 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.
10. Write a java program to find the maximum value from the given type of elements using a
generic function.
11. Designacalculatorusingevent-drivenprogrammingparadigmofJavawiththefollowing
options.
a) Decimalmanipulations
b) Scientificmanipulations
TOTAL: 60 PERIODS
OUTCOMES:
Uponcompletion of thecourse,thestudentswillbeableto
DevelopandimplementJavaprogramsforsimpleapplicationsthatmakeuseof
classes, packages and interfaces.
DevelopandimplementJavaprogramswitharraylist,exceptionhandlingand
multithreading .
Designapplicationsusingfileprocessing, genericprogrammingandeventhandling.
231CBC312L –OBJECT ORIENTED PROGRAMMING LABORATORY
CONTENTS
Ex.
NameoftheExercise PageNo.
No.
1 ElectricityBillGenerationusingClasses 1 –2
Currencyconverter,DistanceconverterandTimeconverter
2 3 –7
Implementation using Packages
3 PayslipGenerationusingInheritance 8 –11
StackADTImplementationusingMultipleInheritance
4 12–14
(Interface)
5 StringOperationsusingArrayList 15–18
6 AbstractClassImplementation 19–20
7 UserDefinedExceptionHandlingImplementation 21–23
8 FileHandling 24–25
9 MultithreadingImplementation 26–27
10 GenericFunctionImplementation 28–29
11 CalculatorDesignUsingEventDrivenProgramming 30–-40
12 MiniProject 41
EX. NO : 1 ELECTRICITYBILLGENERATION
DATE:
AIM:
To develop a Java application to generate Electricity bill. Create a class with the following members:
Consumerno.,consumername,previousmonthreading,currentmonthreading,typeofEBconnection(i.edomestic or
commercial). Compute the bill amount using the following tariff.
IfthetypeoftheEBconnectionisdomestic,calculatetheamounttobepaidasfollows:
First100units-Rs.1perunit
101-200units-Rs.2.50perunit
201-500units-Rs.4perunit
>501units-Rs.6perunit
IfthetypeoftheEBconnection iscommercial,calculatetheamounttobepaidasfollows:
First100units-Rs.2perunit
101-200units-Rs.4.50perunit
201-500units-Rs.6perunit
>501units-Rs.7perunit
ALGORITHM:
1. Start
2. CreateaclassEbill withthree memberfunctions: getdata(),calc(),display() andobjectobiscreatedfor
another class Customerdata.
3. CreateanotherclassCustomerdatawhichdefinestheabovefunctions.
4. Usinggetdata()functiongettheconsumedunitsforcurrentandpreviousmonth.
5. Usingcalc()functioncalculatetheamountdependingonthetypeofEBconnectionandno.ofunits
consumed.
6. Usingdisplay()functiondisplaythebill.
7. Stop.
PROGRAM:
importjava.util.*;
class Ebill
{
publicstaticvoidmain(Stringargs[])
{
Customerdataob=newCustomerdata();
ob.getdata();
ob.calc();
ob.display();
}
}
classCustomerdata
{
Scanner in = new Scanner(System.in);
Scannerins=newScanner(System.in);
String cname,type;
intbn;
doublecurrent,previous,tbill,units;
void getdata()
{
System.out.print("\n\tEnterconsumernumber"); bn
= in.nextInt();
System.out.print("\n\tEnterTypeofconnection(DforDomesticorCforCommercial)"); type =
ins.nextLine();
System.out.print("\n\tEnterconsumername");
cname = ins.nextLine();
System.out.print("\n\tEnterpreviousmonthreading");
previous= in.nextDouble();
System.out.print("\n\tEntercurrentmonthreading");
current= in.nextDouble();
}
1
voidcalc()
{
units=current-previous;
if(type.equals("D"))
{
if(units<=100)
tbill=1*units;
elseif(units>100&&units<=200)
tbill=2.50*units;
elseif(units>200&&units<=500)
tbill= 4*units;
else
tbill=6*units;
}
else
{
if(units<=100)
tbill=2*units;
elseif(units>100&&units<=200)
tbill=4.50*units;
elseif(units>200&&units<=500)
tbill= 6*units;
else
tbill=7*units;
}
}
voiddisplay()
{
System.out.println("\n\t Consumer number = "+bn);
System.out.println("\n\tConsumername="+cname);
if(type.equals("D"))
System.out.println("\n\ttypeofconnection=DOMESTIC");
else
System.out.println("\n\ttypeofconnection=COMMERCIAL");
System.out.println ("\n\t Current Month Reading = "+current);
System.out.println ("\n\t Previous Month Reading = "+previous);
System.out.println ("\n\t Total units = "+units);
System.out.println("\n\tTotalbill=RS"+tbill);
}
}
OUTPUT:
D:\>javacEbill.java
D:\ >java Ebill
Enterconsumernumber1001
EnterTypeofconnection(DforDomesticorCforCommercial)D Enter
consumer nameSachin
Enterpreviousmonthreading3000
Enter current month reading 4000
Consumer number = 1001
Consumer name = Sachin
type of connection = DOMESTIC
Current Month Reading = 4000.0
Previous Month Reading = 3000.0
Total units = 1000.0
Totalbill=RS6000.0
RESULT:
Thusthejavaprogramtogenerateelectricitybill wasimplemented,executedsuccessfullyandthe output
was verified.
2
EX NO : 2
CURRENCYCONVERTER,DISTANCECONVERTERANDTIMECONVERTERI
MPLEMENTATION USING PACKAGES
DATE:
AIM:
Todevelopajavaapplicationtoimplementcurrencyconverter(DollartoINR,EUROtoINR,Yento
INRandviceversa),distanceconverter(metertoKM,milestoKMandviceversa),timeconverter(hoursto minutes, seconds
and vice versa) using packages.
ALGORITHM:
1. Start
2. CreateaPackagecurrencyconversionandplacetheclasscurrencyunderthepackage
3. Createthemethodstoperformcurrencyconversionfromdollartorupee,rupeetodollar,eurotorupee, rupee to
euro, yen to rupee and rupee to yen.
4. Createthepackagedistanceconverionandcreatetheclassdistancewithinthepackage
5. Createthemethodstoconvertfrommetertokm,kmtometer,milestokm,kmtomiles
6. Createthepackagetimeconversionandcreatetheclasstimer.Createthemethodstoconvertfrom hours to
minutes ,hours to seconds , minutes to hours and seconds to hours
7. Createaclassconverterandimportthepackagescurrencyconversion,distanceconversionandtime
conversion. Create the objects for the class currency, distance and timer.
8. Getthechoice fromtheuserandinvokethemethodstoperformthecorrespondingconversionand display
the value.
9. Stop
PROGRAM:
currency.java
packagecurrencyconversion;
import java.util.*;
publicclasscurrency
{
double inr,usd;
doubleeuro,yen;
Scannerin=newScanner(System.in); public
void dollartorupee()
{
System.out.println("EnterdollarstoconvertintoRupees:");
usd=in.nextInt();
inr=usd*67;
System.out.println("Dollar="+usd+"equaltoINR="+inr);
}
publicvoidrupeetodollar()
{
System.out.println("EnterRupeetoconvertintoDollars:");
inr=in.nextInt();
usd=inr/67;
System.out.println("Rupee="+inr+"equaltoDollars="+usd);
}
publicvoideurotorupee()
{
System.out.println("EntereurotoconvertintoRupees:");
euro=in.nextInt();
inr=euro*79.50;
System.out.println("Euro="+euro+"equaltoINR="+inr);
}
publicvoidrupeetoeuro()
{
System.out.println("EnterRupeestoconvertintoEuro:");
inr=in.nextInt();
euro=(inr/79.50);
System.out.println("Rupee="+inr+"equaltoEuro="+euro);
3
}
4
publicvoid yentorupee()
{
System.out.println("EnteryentoconvertintoRupees:");
yen=in.nextInt();
inr=yen*0.61;
System.out.println("YEN="+yen+"equaltoINR="+inr);
}
publicvoidrupeetoyen()
{
System.out.println("EnterRupeestoconvertintoYen:");
inr=in.nextInt();
yen=(inr/0.61);
System.out.println("INR="+inr+"equaltoYEN"+yen);
}
}
distance.java
packagedistanceconversion;
import java.util.*;
publicclassdistance
{
doublekm,m,miles;
Scannersc=newScanner(System.in);
public void kmtom()
{
System.out.print("Enterinkm");
km=sc.nextDouble();
m=(km*1000);
System.out.println(km+"km"+"equalto"+m+"metres");
}
publicvoid mtokm()
{
System.out.print("Enterinmeter");
m=sc.nextDouble();
km=(m/1000);
System.out.println(m+"m"+"equalto"+km+"kilometres");
}
publicvoid milestokm()
{
System.out.print("Enterinmiles");
miles=sc.nextDouble();
km=(miles*1.60934);
System.out.println(miles+"miles"+"equalto"+km+"kilometres");
}
publicvoidkmtomiles()
{
System.out.print("Enterinkm");
km=sc.nextDouble();
miles=(km*0.621371);
System.out.println(km+"km"+"equalto"+miles+"miles");
}
}
timer.java
packagetimeconversion;
import java.util.*;
publicclasstimer
{
inthours,seconds,minutes;
int input;
Scannersc=newScanner(System.in);
public void secondstohours()
{
System.out.print("Enterthenumberofseconds:");
input = sc.nextInt();
5
hours=input/3600;
minutes = (input % 3600) / 60;
seconds = (input % 3600) % 60;
System.out.println("Hours:"+hours);
System.out.println("Minutes:"+minutes);
System.out.println("Seconds:"+seconds);
}
publicvoid minutestohours()
{
System.out.print("Enterthenumberofminutes:");
minutes=sc.nextInt();
hours=minutes/60;
minutes=minutes%60;
System.out.println("Hours:"+hours);
System.out.println("Minutes:"+minutes);
}
publicvoidhourstominutes()
{
System.out.println("enterthenoofhours");
hours=sc.nextInt();
minutes=(hours*60);
System.out.println("Minutes:"+minutes);
}
publicvoidhourstoseconds()
{
System.out.println("enterthenoofhours");
hours=sc.nextInt();
seconds=(hours*3600);
System.out.println("Minutes:"+seconds);
}
}
converter.javaimpo
rtjava.util.*; import
java.io.*;
importcurrencyconversion.*;
import distanceconversion.*;
import timeconversion.*;
class converter
{
publicstaticvoidmain(Stringargs[])
{
Scanners=newScanner(System.in);
int choice,ch;
currencyc=newcurrency();
distance d=new distance();
timer t=new timer();
do
{
System.out.println("1.dollar to rupee ");
System.out.println("2.rupee to dollar ");
System.out.println("3.Euro to rupee ");
System.out.println("4..rupee to Euro ");
System.out.println("5.Yen to rupee ");
System.out.println("6.Rupee to Yen ");
System.out.println("7.Metertokilometer");
System.out.println("8.kilometertometer");
System.out.println("9.Milestokilometer");
System.out.println("10.kilometertomiles");
System.out.println("11.Hours to Minutes");
System.out.println("12.Hours to Seconds");
System.out.println("13.Seconds to Hours");
System.out.println("14.Minutes to Hours");
System.out.println("Enter ur choice");
choice=s.nextInt();
6
switch(choice)
{
case 1:
{
c.dollartorupee();
break;
}
case 2:
{
c.rupeetodollar();
break;
}
case 3:
{
c.eurotorupee();
break;
}
case 4:
{
c.rupeetoeuro();
break;
}
case 5:
{
c.yentorupee();
break;
}
case 6:
{
c.rupeetoyen();
break;
}
case 7:
{
d.mtokm();
break;
}
case 8:
{
d.kmtom();
break;
}
case 9:
{
d.milestokm();
break;
}
case10:
{
d.kmtomiles();
break;
}
case 11:
{
t.hourstominutes();
break;
}
case 12:
{
t.hourstoseconds();
break;
}
7
case13:
{
t.secondstohours();
break;
}
case14:
{
t.minutestohours();
break;
}
}
System.out.println("Enter0toquitand1tocontinue");
ch=s.nextInt();
}
while(ch==1);
}
}
OUTPUT:
RESULT
ThustheJavaapplicationtoimplementcurrencyconverter,distanceconverterandtime converter
was implemented, executed successfully and the output was verified.
8
EX NO: 3
PAYSLIPGENERATIONUSINGINHERITANCED
ATE:
AIM:
Todevelopajavaapplicationtogeneratepayslipfordifferentcategoryofemployeesusing the
conceptofinheritance.
ALGORITHM:
1. Start
2. CreatetheclassEmployeewithname,Empid,address,mailid,mobilenoasdatamembers.
3. InherittheclassesProgrammer,Asstprofessor,AssociateprofessorandProfessorfromemployee
class.
4. AddBasicPay(BP)asthememberofalltheinheritedclasses.
5. CalculateDAas97%ofBP,HRAas10%of BP,PFas12%ofBP,Staffclubfundas0.1%ofBP.
6. Calculategrosssalaryandnetsalary.
7. Generatepayslipforallcategoriesofemployees.
8. CreatetheobjectsfortheinheritedclassesandinvokethenecessarymethodstodisplaythePayslip
9. Stop
PROGRAM:
Salary.java
importjava.util.*;
class Employee
{
int empid;
longmobile;
Stringname,address,mailid;
Scannerget=newScanner(System.in); void
getdata()
{
System.out.println("EnterNameoftheEmployee"); name
= get.nextLine();
System.out.println("EnterMailid");
mailid = get.nextLine();
System.out.println("EnterAddressoftheEmployee:");
address = get.nextLine();
System.out.println("Enter employee id ");
empid = get.nextInt();
System.out.println("EnterMobileNumber");
mobile = get.nextLong();
}
voiddisplay()
{
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("MobileNumber:"+mobile);
}
}
classProgrammerextendsEmployee
{
doublesalary,bp,da,hra,pf,club,net,gross;
void getprogrammer()
{
System.out.println("Enterbasicpay");
bp = get.nextDouble();
}
9
voidcalculateprog()
{
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);
System.out.println("HRA: Rs. "+hra);
System.out.println("PF: Rs. "+pf);
System.out.println("CLUB: Rs. "+club);
System.out.println("GROSSPAY:Rs."+gross);
System.out.println("NET PAY: Rs. "+net);
}
}
classAsstprofessorextendsEmployee
{
doublesalary,bp,da,hra,pf,club,net,gross;
void getasst()
{
System.out.println("Enterbasicpay");
bp = get.nextDouble();
}
voidcalculateasst()
{
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("PAYSLIPFORASSISTANTPROFESSOR");
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("GROSSPAY:Rs."+gross);
System.out.println("NET PAY: Rs. "+net);
}
}
classAssociateprofessorextendsEmployee
{
doublesalary,bp,da,hra,pf,club,net,gross;
void getassociate()
{
System.out.println("Enterbasicpay");
bp = get.nextDouble();
}
voidcalculateassociate()
{
da=(0.97*bp);
hra=(0.10*bp);
pf=(0.12*bp);
club=(0.1*bp);
gross=(bp+da+hra);
net=(gross-pf-club);
10
System.out.println("***********************************");
System.out.println("PAYSLIPFORASSOCIATEPROFESSOR");
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("GROSSPAY:Rs."+gross);
System.out.println("NET PAY: Rs. "+net);
}
}
classProfessorextendsEmployee
{
doublesalary,bp,da,hra,pf,club,net,gross;
void getprofessor()
{
System.out.println("Enterbasicpay");
bp = get.nextDouble();
}
voidcalculateprofessor()
{
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("PAYSLIPFORPROFESSOR");
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);
}
}
classSalary
{
publicstaticvoidmain(Stringargs[])
{
intchoice,cont;
do
{
System.out.println("PAYROLL");
System.out.println("1.PROGRAMMER\t2.ASSISTANTPROFESSOR\t3.ASSOCIATE PROFESSOR
\t 4.PROFESSOR ");
Scanner c = new Scanner(System.in);
System.out.print(“EnterYourChoice:”);
choice=c.nextInt();
switch(choice)
{
case1:
{
Programmerp=newProgrammer();
p.getdata();
p.getprogrammer();
p.display();
p.calculateprog();
break;
}
11
case2:
{
Asstprofessorasst=newAsstprofessor(); asst.getdata();
asst.getasst();
asst.display();
asst.calculateasst();
break;
}
case3:
{ Associateprofessorasso=newAssociateprofessor();
asso.getdata();
asso.getassociate();
asso.display();
asso.calculateassociate();
break;
}
case4:
{ Professorprof=newProfessor();
prof.getdata();
prof.getprofessor();
prof.display();
prof.calculateprofessor();
break;
}
}
System.out.print("Pleaseenter0toquitand1tocontinue:"); cont=c.nextInt();
}while(cont==1);
}
}
OUTPUT
1.PROGRAMMER2.ASSISTANTPROFESSOR3.ASSOCIATEPROFESSOR4.PROFESSOR
EnterYourChoice:2
EnterNameoftheEmployee:ArunK Enter
Mail id: arun007@gmail.com
EnterAddressoftheEmployee:12,AnnaNagar,Chennai-65
Enter employee id: 5002
EnterMobileNumber:9876543210
Enter basic pay : 20000
EmployeeName:ArunK
Employee id : 5002
Mail id : arun007@gmail.com
Address:12,AnnaNagar,Chennai-65
Mobile Number: 9876543210
***********************************
PAYSLIPFORASSISTANTPROFESSOR
***********************************
Basic Pay:Rs. 20000.0
DA:Rs. 19400.0
HRA:Rs.2000.0
PF:Rs.2400.0
CLUB:Rs.2000.0
GROSSPAY:Rs.41400.0
NETPAY:Rs.37000.0
Pleaseenter0toquitand1tocontinue:0
RESULT
ThustheJavaapplicationto generatepayslip fordifferentcategoryofemployeeswasimplemented using
inheritance and the program was executed successfully.
12
EX NO: 4
STACKADTIMPLEMENTATIONUSINGINHERITANCE(INTERFACE)D
ATE:
AIM
TodesignaJavaapplicationtoimplementarrayimplementationofstackusingtheconcept of
InterfaceandExceptionhandling.
ALGORITHM
1. Start
2. CreatetheinterfaceStackoperationwithmethoddeclarationsforpushandpop.
3. CreatetheclassAstackwhichimplementstheinterfaceandprovidesimplementationforthemethods push
and pop. Also define the method for displaying the values stored in the stack. Handle the stack
overflow and stack underflow condition.
4. Createtheclassteststack.Getthechoice fromtheuser fortheoperationtobeperformedandalso handle
the exception that occur while performing the stack operation.
5. Createtheobjectandinvokethemethodforpush,pop,displaybasedontheinputfromtheuser.
6. Stop.
PROGRAM
Teststack.java
import
java.io.*;interfaceStacko
peration
{
publicvoidpush(inti);
public void pop();
}
classAstackimplementsStackoperation
{
intstack[]=newint[5]; int
top=-1;
inti;
publicvoidpush(intitem)
{
if(top>=4)
{
System.out.println("Overflow");
}
else
{
top=top+1;
stack[top]=item;
System.out.print("Elementpushed:"+stack[top]);
}
}
publicvoidpop()
{
if(top<0)
System.out.println("Underflow");
else }
{
13
S
y
s
t
e
m
.
o
u
t
.
p
r
i
n
t
(
"
E
l
e
m
e
n
t
p
o
p
p
e
d
:
"
+
s
t
a
c
k
[
t
o
p
]
)
;
t
o
p
=
t
o
p
-
1
;
14
publicvoiddisplay()
{
if(top<0)
System.out.println("NoElementinstack");
else
{
for(i=0;i<=top;i++)
System.out.println("Element:"+stack[i]);
}
}
}
classTeststack
{
publicstaticvoidmain(Stringargs[])throwsIOException
{
intch,c;
int i;
Astacks=newAstack();
DataInputStreamin=newDataInputStream(System.in); do
{
try
{
System.out.println("ARRAY STACK");
System.out.println("1.Push2.Pop3.Display4.Exit");
System.out.print("Enter your Choice:");
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1:
System.out.print("Enterthevaluetopush:");
i=Integer.parseInt(in.readLine());
s.push(i);
break;
case 2:
s.pop();
break;
case 3:
System.out.println("Theelementsare:"); s.display();
break;
default: break;
}
}
catch(IOExceptione)
{
System.out.println("IOError");
}
System.out.println("Pleaseenter0toquitand1tocontinue");
c=Integer.parseInt(in.readLine());
}while(c==1);
}
}
15
OUTPUT
D:\>javacTeststack.java
D:\ >java Teststack
ARRAY STACK
1.Push2.Pop3.Display4.Exit
Enter your Choice: 1
Enterthevaluetopush:10
Element pushed: 10
Pleaseenter0toquitand1tocontinue 1
ARRAYSTACK
1.Push2.Pop3.Display4.Exit
Enter your Choice: 1
Enterthevaluetopush:20
Element pushed: 20
Pleaseenter0toquitand1tocontinue 1
ARRAYSTACK
1.Push2.Pop3.Display4.Exit
Enter your Choice: 1
Enterthevaluetopush:30
Element pushed: 30
Pleaseenter0toquitand1tocontinue 1
ARRAYSTACK
1.Push2.Pop3.Display4.Exit
Enter your Choice: 3
Theelementsare:
Element:10
Element:20
Element:30
Pleaseenter0toquitand1tocontinue 1
ARRAYSTACK
1.Push2.Pop3.Display4.Exit
Enter your Choice: 2
Elementpopped:30
Pleaseenter0toquitand1tocontinue 1
ARRAYSTACK
1.Push2.Pop3.Display4.Exit
Enter your Choice: 3
Theelementsare:
element:10
element:20
Pleaseenter0toquitand1tocontinue 0
RESULT
ThustheJavaapplicationforADTstackoperationshasbeenimplementedandexecutedsuccessfully.
16
EX NO: 5
STRINGOPERATIONSUSINGARRAYLISTD
ATE:
AIM
TowriteajavaprogramtoperformstringoperationsusingArrayListforthefollowing
functions:
a. Append-addatend
b. Insert–addatparticular index
c. Search
d. Listallstringstartswithgiven letter
ALGORITHM:
1. Start
2. CreatetheclassArraylistexample.CreatetheobjectfortheArrayListclass.
3. Displaytheoptionstotheuserforperformingstringhandling.
4. Usethefunctionadd()toappendthestringattheendandtoinsert thestringattheparticular index.
5. Thefunctionsort()isusedtosorttheelementsinthearraylist.
6. Thefunctionindexof()isusedtosearchwhethertheelement isinthearraylistornot.
7. ThefunctionstartsWith()isusedtofindwhethertheelement startswiththespecified
character.
8. Thefunctionremove()isusedtoremovetheelementfromthearraylist.
9. Thefunctionsize()isusedtodeterminethenumberofelementsinthearraylist.
10. Stop.
PROGRAM:
Arraylistexample.java
importjava.util.*;
import java.io.*;
publicclassArraylistexample
{
publicstaticvoidmain(Stringargs[])throwsIOException
{
ArrayList<String> obj = new ArrayList<String>();
DataInputStreamin=newDataInputStream(System.in);
int c,ch;
inti,j;
Stringstr,str1;
do
{
System.out.println("STRINGMANIPULATION");
System.out.println("************************");
System.out.println("1.Appendatend \t2.Insertatparticularindex\t3.Search\t");
System.out.println("4. List string that starting with letter \t");
System.out.println("5. Size \t 6.Remove \t 7.Sort \t 8.Display\t" );
System.out.println("Enter the choice ");
c=Integer.parseInt(in.readLine());
switch(c)
{
case1:
{
System.out.println("Enterthestring");
str=in.readLine();
obj.add(str);
break;
}
17
case2:
{
System.out.println("Enterthestring");
str=in.readLine();
System.out.println("Specifytheindex/positiontoinsert");
i=Integer.parseInt(in.readLine());
obj.add(i-1,str);
System.out.println("Thearraylisthasfollowingelements:"+obj); break;
}
case3:
{ System.out.println("Enterthestringtosearch");
str=in.readLine();
j=obj.indexOf(str);
if(j==-1)
System.out.println("Elementnotfound"); else
System.out.println("Indexof:"+str+"is"+j);
break;
}
case4: System.out.println("EnterthecharactertoListstringthatstartswith specified character");
{ str=in.readLine();
for(i=0;i<(obj.size()-1);i++)
{
str1=obj.get(i);
if(str1.startsWith(str))
{
System.out.println(str1);
}
}
break;
}
case5:
{
System.out.println("Sizeofthelist"+obj.size()); break;
}
case6:
{ System.out.println("Entertheelementtoremove");
str=in.readLine();
if(obj.remove(str))
{
System.out.println("ElementRemoved"+str);
}
else
{
System.out.println("Elementnotpresent");
}
break;
}
18
case7:
{
Collections.sort(obj);
System.out.println("Thearraylisthasfollowingelements:"+obj); break;
}
case8:
{ System.out.println("Thearraylisthasfollowingelements:"+obj); break;
}
}
System.out.println("PleaseEnter0tobreakand1tocontinue"); ch=Integer.parseInt(in.readLine());
}while(ch==1);
}
}
OUTPUT
D:\JavaPrograms>javacArraylistexample.java
D:\Java Programs>java Arraylistexample
STRINGMANIPULATION
************************
1.Appendatend 2.Insertatparticularindex3.Search
4. Liststringthatstartingwithletter
5. Size 6.Remove 7.Sort 8.Display
Enter the choice: 1
Enterthestring:FIRST
Enter0tobreakand1tocontinue:1
STRINGMANIPULATION
************************
1.Appendatend 2.Insertatparticularindex3.Search
4. Liststringthatstartingwithletter
5. Size 6.Remove 7.Sort 8.Display
Enter the choice: 1
Enterthestring:LAST
Enter0tobreakand1tocontinue:1
STRINGMANIPULATION
************************
1.Appendatend 2.Insertatparticularindex3.Search
4. Liststringthatstartingwithletter
5. Size 6.Remove 7.Sort 8.Display
Enter the choice : 8
Thearraylisthasfollowingelements:[FIRST,LAST] Enter
0 to break and 1 to continue : 1
STRINGMANIPULATION
************************
1.Appendatend 2.Insertatparticularindex3.Search
4. Liststringthatstartingwithletter
5. Size 6.Remove 7.Sort 8.Display
Enter the choice : 2
Enterthestring:SECOND
Specifytheindex/positiontoinsert:1
Thearraylisthasfollowingelements:[SECOND,FIRST,LAST]
Enter 0 to break and 1 to continue: 1
19
STRINGMANIPULATION
************************
1.Appendatend 2.Insertatparticularindex3.Search
4. Liststringthatstartingwithletter
5. Size 6.Remove 7.Sort 8.Display
Enter the choice : 3
Enterthestringtosearch:LAST Index
of: LAST is 2
Enter0tobreakand1tocontinue:1
STRINGMANIPULATION
************************
1.Appendatend 2.Insertatparticularindex3.Search
4. Liststringthatstartingwithletter
5. Size 6.Remove 7.Sort 8.Display
Enter the choice : 5
Sizeofthelist3
Enter0tobreakand1tocontinue:1
STRINGMANIPULATION
************************
1.Appendatend 2.Insertatparticularindex3.Search
4. Liststringthatstartingwithletter
5. Size 6.Remove 7.Sort 8.Display
Enter the choice : 7
Thearraylisthasfollowingelements:[FIRST,LAST,SECOND]
Enter 0 to break and 1 to continue : 0
RESULT
ThusthejavaprogramtoperformstringoperationsusingArrayListhasbeenimplemented and
executed successfully.
20
EX NO : 6
ABSTRACTCLASSIMPLEMENTATION
DATE :
AIM
TowriteaJavaprogramtocalculatetheareaofrectangle,circleandtriangleusing the
conceptofabstract class.
ALGORITHM:
1. Start
2. Createanabstractclassnamedshapethatcontainstwointegersandanemptymethodnamed
printarea().
3. Providethreeclassesnamedrectangle,triangleandcirclesuchthateachoneoftheclasses extends
the class Shape.
4. Eachoftheinheritedclassfromshapeclassshouldprovidetheimplementationforthemethod
printarea().
5. Gettheinputandcalculatetheareaofrectangle,circleandtriangle.
6. Intheshapeclass,createtheobjectsforthethreeinheritedclassesandinvokethemethodsand display
the area values of the different shapes.
7. Stop.
PROGRAM
Shapeclass.javaimpo
rt java.util.*;
abstractclassshape
{
inta,b;
abstractpublicvoidprintarea();
}
classrectangleextendsshape
{
public int area_rect;
publicvoidprintarea()
{
Scanners=new Scanner(System.in);
System.out.println("Enterthelengthandbreadthofrectangle"); a=s.nextInt();
b=s.nextInt();
area_rect=a*b;
System.out.println("Lengthofrectangle:"+a+"breadthofrectangle:"+b);
System.out.println("The area of rectangle is:"+area_rect);
}
}
classtriangleextendsshape
{
double
area_tri;publicvoidpri
ntarea()
{
Scanner s=new Scanner(System.in);
System.out.println("Enterthebaseandheightoftriangle:");
a=s.nextInt();
b=s.nextInt();
System.out.println("Baseoftriangle:"+a+"heightoftriangle:"+b); area_tri=(0.5*a*b);
System.out.println("Theareaoftriangleis:"+area_tri);
}
}
21
classcircleextendsshape
{
double area_circle;
publicvoidprintarea()
{
Scanner s=new Scanner(System.in);
System.out.println("Entertheradiusofcircle:");
a=s.nextInt();
area_circle=(3.14*a*a);
System.out.println("Radiusofcircle:"+a);
System.out.println("Theareaofcircleis:"+area_circle);
}
}
publicclassShapeclass
{
publicstaticvoidmain(String[] args)
{
rectangler=newrectangle();
r.printarea();
trianglet=newtriangle();
t.printarea();
circler1=newcircle();
r1.printarea();
}
}
OUTPUT
D:\JavaPrograms>javacShapeclass.java
D:\Java Programs>java Shapeclass
Enterthelengthandbreadthofrectangle: 2
3
Lengthofrectangle:2breadthofrectangle:3 The
area of rectangle is:6
Enterthebaseandheightoftriangle: 5
6
Baseoftriangle:5heightoftriangle:6 The
area of triangle is: 15.0
Entertheradiusofcircle 4
Radiusofcircle:4
Theareaofcircleis:50.24
RESULT
ThustheJavaprogramforcalculatetheareaofrectangle,circleandtrianglewasimplemented and
executed successfully.
22
EX NO : 7
USERDEFINEDEXCEPTIONHANDLINGIMPLEMENTATIOND
ATE :
AIM
TowriteaJavaprogramtoimplementuserdefinedexception handling.
ALGORITHM:
1. Start
2. Createaclass NegativeAmtExceptionwhichextendsExceptionclass.
3. Createaconstructorwhichreceivesthestringasargument.
4. GettheAmountasinputfromtheuser.
5. Iftheamountisnegative,theexceptionwillbegenerated.
6. Usingtheexceptionhandlingmechanism,thethrownexceptionishandledbythecatch
construct.
7. Aftertheexceptionishandled,thestring“invalidamount“willbe displayed.
8. Iftheamountisgreaterthan0,themessage“AmountDeposited“willbedisplayed
9. Stop.
PROGRAM1:
userdefined.java
importjava.util.*;
classNegativeAmtExceptionextendsException
{
String msg;
NegativeAmtException(Stringmsg)
{
this.msg=msg;
}
publicStringtoString()
{
return msg;
}
}
publicclass userdefined
{
publicstaticvoidmain(String[]args)
{
Scanners=newScanner(System.in);
System.out.print("Enter Amount:");
int a=s.nextInt();
try
{
if(a<0)
{
thrownewNegativeAmtException("InvalidAmount");
}
System.out.println("AmountDeposited");
}
catch(NegativeAmtException e)
{
System.out.println(e);
}
}
23
}
24
OUTPUT
PROGRAM2:
example.java
classMyExceptionextendsException
{
String str1;
MyException(Stringstr2)
{
str1=str2;
}
publicStringtoString()
{
return("MyExceptionOccurred:"+str1);
}
}
classexample
{
publicstatic void main(Stringargs[])
{
try
{
System.out.println("Startingoftryblock");
thrownew MyException("This is Myerror Message");
}
catch(MyExceptionexp)
{
System.out.println("CatchBlock");
System.out.println(exp) ;
}
}
}
25
OUTPUT
RESULT
ThustheJavaprogramtoimplementuserdefinedexceptionhandlinghasbeenimplemented and
executed successfully.
26
EXNO:8 FILEHANDLING
DATE:
AIM
Towriteajavaprogramthatreadsafilenamefromtheuser,displaysinformationabout
whetherthefileexists,whetherthefileisreadable,orwritable,thetypeoffileandthelengthofthe file in
bytes.
ALGORITHM:
1. Start
2. Createaclassfiledemo.Getthefilenamefromtheuser.
3. Usethefilefunctionsanddisplaytheinformationaboutthe file.
4. getName()displaysthenameofthefile.
5. getPath()diplaysthepathnameofthefile.
6. getParent()-Thismethodreturnsthepathnamestringofthisabstractpathname’sparent,or
7. nullifthispathnamedoesnotnameaparent directory.
8. exists()–Checkswhetherthefileexistsornot.
9. canRead()-Thismethodisbasicallyacheckifthefilecanberead.
10. canWrite()-verifieswhethertheapplicationcanwritetothefile.
11. isDirectory()–displayswhetheritisadirectoryornot.
12. isFile()–displayswhetheritisafileornot.
13. lastmodified()–displaysthelastmodifiedinformation.
14. length()-displaysthesizeofthefile.
15. delete()–deletesthefile
16. Invokethepredefinedfunctionstodisplaytheinformationaboutthefile.
17. Stop.
PROGRAM
filedemo.java
import java.io.*;
importjava.util.*;
class filedemo
{
publicstaticvoidmain(Stringargs[])
{
Stringfilename;
Scanner s=new Scanner(System.in);
System.out.println("Enterthefilename");
filename=s.nextLine();
File f1=new File(filename);
System.out.println("******************");
System.out.println("FILE INFORMATION");
System.out.println("******************");
System.out.println("NAMEOFTHEFILE"+f1.getName());
System.out.println("PATH OF THE FILE "+f1.getPath());
System.out.println("PARENT"+f1.getParent());if(f1.exists())
System.out.println("THEFILEEXISTS");
else
System.out.println("THEFILEDOESNOTExISTS");
if(f1.canRead())
System.out.println("THEFILECANBEREAD");
else
System.out.println("THEFILECANNOTBEREAD");
if(f1.canWrite())
System.out.println("WRITEOPERATIONISPERMITTED");
27
else
System.out.println("WRITEOPERATIONISNOTPERMITTED");
if(f1.isDirectory())
System.out.println("ITISADIRECTORY");
else
System.out.println("NOTADIRECTORY");
if(f1.isFile())
System.out.println("ITISAFILE");
else
System.out.println("NOTAFILE");
System.out.println("File last modified "+ f1.lastModified());
System.out.println("LENGTHOFTHEFILE"+f1.length());
System.out.println("FILE DELETED "+f1.delete());
}
}
OUTPUT
RESULT
Thusthejavaprogramtodisplayfileinformationhasbeenimplementedandexecuted successfully.
28
EX NO : 9 MULTITHREADINGIMPLEMENTATION
DATE :
AIM
Towriteajavaprogramthatimplementsamulti-threadedapplication.
ALGORITHM:
1. Start
2. Createaclass evenwhichimplementsfirstthreadthatcomputesthesquareofthenumber.
3. run()methodimplementsthecodetobeexecutedwhenthreadgetsexecuted.
4. Createaclassoddwhichimplementssecondthreadthatcomputesthecubeofthenumber.
5. Createathirdthreadthatgeneratesrandomnumber. Iftherandomnumberiseven,itdisplays the
square of the number. If the random number generated is odd, it displays the cube of the
given number.
6. TheMultithreadingisperformedandthetaskswitchedbetweenmultiple threads.
7. Thesleep()methodmakesthethreadtosuspendforthespecifiedtime.
8. Stop.
PROGRAM
multithreadprog.java
importjava.util.*;
classevenimplementsRunnable
{
public int x;
publiceven(intx)
{
this.x=x;
}
publicvoidrun()
{
System.out.println("NewThread"+x+" isEVENandSquareof" +x+" is:" +x*x);
}
}
classoddimplementsRunnable
{
public int x;
publicodd(intx)
{
this.x=x;
}
publicvoidrun()
{
System.out.println("NewThread"+x+" isODDandCubeof" +x+"is:" +x*x*x);
}
}
classAextendsThread
{
publicvoidrun()
{
intnum=0;
Randomr=newRandom(); try
{
for(int i= 0; i<5;i++)
{
num= r.nextInt(100);
29
System.out.println("MainThreadandGeneratedNumberis"+num); if
(num % 2 == 0)
{
Threadt1=newThread(neweven(num)); t1.start();
}
else
{ Threadt2=newThread(newodd(num)); t2.start();
}
Thread.sleep(1000);
System.out.println(" ");
}
}
catch(Exceptionex)
{
System.out.println(ex.getMessage());
}
}
}
publicclassmultithreadprog
{
publicstaticvoidmain(String[] args)
{
Aa=newA();
a.start();
}
}
OUTPUT
RESULT
ThustheJavaprogramformulti-threadedapplicationhasbeenimplementedandexecuted successfully.
30
EX NO : 10 GENERICFUNCTIONIMPLEMENTATION
DATE :
AIM
Towriteajavaprogramtofindthemaximumvaluefromthegiventypeof elementsusinga generic
function.
ALGORITHM:
1. Start
2. CreateaclassMyclasstoimplementgenericclassandgenericmethods.
3. Getthesetofthevaluesbelongingtospecificdatatype.
4. Createtheobjectsoftheclasstoholdinteger,characteranddoublevalues.
5. Createthemethodtocomparethevaluesandfindthemaximumvaluestoredinthearray.
6. Invokethemethodwithinteger,characterordoublevalues.Theoutputwillbedisplayed based
on the data type passed to the method.
7. Stop.
PROGRAM
genericdemo.java
classMyClass<TextendsComparable<T>>
{
T[]vals;
MyClass(T[]o)
{
vals=o;
}
publicT min()
{
Tv= vals[0];
for(inti=1;i<vals.length;i++)
if(vals[i].compareTo(v) < 0)
v=vals[i];
return v;
}
publicT max()
{
Tv= vals[0];
for(inti=1;i<vals.length;i++)
if(vals[i].compareTo(v) > 0)
v=vals[i];
return v;
}
}
classgenericdemo
{
publicstaticvoidmain(Stringargs[]){ int
i;
Integer inums[]={10,2,5,4,6,1};
Characterchs[]={'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=newMyClass<Character>(chs);
MyClass<Double>dob = new MyClass<Double>(d);
System.out.println("Max value in inums: " + iob.max());
System.out.println("Min value in inums: " + iob.min());
System.out.println("Max value in chs: " + cob.max());
System.out.println("Min value in chs: " + cob.min());
System.out.println("Max value in chs: " + dob.max());
System.out.println("Min value in chs: " + dob.min());
}
}
31
OUTPUT
D:\>JavaPrgs>javacgenericdemo.java
D:\>Java Prgs>java genericdemo
Maxvalueininums:10
Max value in inums: 1
Max value in chs: v
Max value in chs: a
Max value in chs: 88.3
Max value in chs: 10.4
RESULT
32
EX NO : 11 CALCULATORDESIGNUSINGEVENTDRIVENPROGRAMMING
DATE :
AIM
TodesignacalculatorusingeventdrivenprogrammingparadigmofJavawiththefollowing
options
a) DecimalManipulations
b) ScientificManipulations
ALGORITHM:
1. Start
2. Importtheswingpackagesandawt packages.
3. Createtheclassscientificcalculatorthatimplementsactionlistener.
4. Createthecontainerandaddcontrolsfordigits,scientificcalculationsanddecimal
Manipulations.
5. Thedifferentlayoutscanbeusedtolaythecontrols.
6. Whentheuserpressesthecontrol,theeventisgeneratedandhandled.
7. Thecorrespondingdecimal,numericandscientificcalculationsareperformed.
8. Stop
PROGRAM
import java.awt.*;
import javax.swing.*;
importjava.awt.event.*;
importjavax.swing.event.*;
publicclassScientificCalculatorextendsJFrameimplementsActionListener
{
JTextFieldtfield;
doubletemp,temp1,result,a;
static double m1, m2;
intk=1,x=0,y=0,z=0; char ch;
JButtonb1,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;
JPaneltextPanel,buttonpanel;
ScientificCalculator()
{
cont = getContentPane();
cont.setLayout(newBorderLayout());
JPanel textpanel = new JPanel();
tfield = new JTextField(25);
tfield.setHorizontalAlignment(SwingConstants.RIGHT);
tfield.addKeyListener(new KeyAdapter()
{
publicvoidkeyTyped(KeyEventkeyevent)
{
charc=keyevent.getKeyChar(); if
(c >= '0'&& c <= '9') { }
else
{
keyevent.consume();
}
}
});
textpanel.add(tfield);
33
buttonpanel = new JPanel();
buttonpanel.setLayout(newGridLayout(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");
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=newJButton("+/-");
buttonpanel.add(addSub);
34
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");
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);
}
publicvoidactionPerformed(ActionEvente)
{
Strings=e.getActionCommand(); if
(s.equals("1"))
{
if(z== 0)
{
tfield.setText(tfield.getText()+"1");
}
else {
tfield.setText("");
tfield.setText(tfield.getText()+"1");
z= 0;
}
}
35
if(s.equals("2")){
if (z == 0) {
tfield.setText(tfield.getText()+"2");
}
else
{
tfield.setText("");
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) {
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");
}
36
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;
}
}
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);
}
}
34
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);
}
}
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;
}
else
{
tfield.setText(tfield.getText());
}
}
if(s.equals(".")){ if
(y == 0) {
tfield.setText(tfield.getText()+"."); y
= 1;
}
35
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
{
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("*")){
36
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"))
{
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()));
37
tfield.setText("");
field.setText(tfield.getText()+a);
}
}
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("");
}
else
{
temp1=Double.parseDouble(tfield.getText());
switch (ch)
{
case '+':
result=temp+temp1; break;
case'-':
result=temp-temp1; break;
case'/':
38
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();
}
doublefact(doublex)
{
inter=0; if
(x < 0)
{
er= 20;
return0;
}
doublei,s = 1;
for(i= 2;i <= x;i += 1.0)
s*=i;
return s;
}
publicstaticvoidmain(Stringargs[])
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch(Exception e)
{
}
ScientificCalculatorf=newScientificCalculator();
f.setTitle("ScientificCalculator");
f.pack();
f.setVisible(true);
}
}
39
OUTPUT
RESULT
ThustheJavaprogramsforscientificcalculatorhasbeenimplementedandexecuted successfully.
40
EXNO:12 MINIPROJECT
DATE:
1. AirlineReservationSystem
2. MarksheetPreparationsystem
3. NAAConlineapplicationcreation
4. LibraryManagementSystem
5. ConvertingRGBimagetoGrayImage
6. HealthCareSystem
7. Appdevelopment
8. IncomeTaxSystem
9. VehicleTrackingSystem
10. EbankingSystem
41
VIVAQUESTIONS
1. WhataretheprincipleconceptsofOOPS?
2. Whatis Abstraction?
3. Whatis Encapsulation?
4. Whatis Inheritance?
5. Whatis Polymorphism?
6. ExplainthedifferentformsofPolymorphism?
7. Defineaconstructor?
8. DefineDestructor?
9. Whatis JVM?
10. WhatisdifferencebetweenStreamclassesandReaderwriterclasses?
11. ExplaintheuseofRandomAccessFileclasses.
12. WhatisobjectSerialization?ExplaintheuseofPersistingobject.
13. Whatisthedifferencebetweenproceduralandobject-orientedprograms?
14. Whatismultithreadingandwhatistheclassinwhichthesemethodsaredefined?
15. Whatisthedifferencebetweenapplicationsandapplets?
16. Whatisadapterclass?
17. WhatisthedifferencebetweenProcessandThread?
18. Howdoyoudeclareaclassasprivate?
19. Whatisthedrawbackofinheritance?
20. Whyaretherenoglobalvariablesin Java?
General
1. Whatisgarbagecollection?Howdoesithappen?
2. Whatisthedifferencebetweenaconstructorandamethod?
3. Whatisastaticblock?Howdoyoucreateastaticblock?Whyisitused?
4. Whatarestaticvariable,staticmethodandstatic class?
5. Whatarefinalvariable,finalmethodandfinal class?
6. Whydoweusefinalize()method?
Abstractclassesandinterfaces
1. Whatisanabstractclass?
2. Whatarethedifferencesbetweenabstractclassand interface?Canyoutellmeexampleswherewe use
interface and abstract class?
Exception
1. Whatarethedifferencesbetween“NullPointerException”and“Exception”classes?
2. Whatarethedifferencesbetweenexceptionanderrorclasses?
String
1. Whatisthedifferencebetween“==”and“equals”
2. CanweextendStringclass?
3. WhatarethedifferencesbetweenString,StringBufferand StringBuilder?
42