Java, A Beginner's Guide: Advanced Features (Core Series) Updated To Java 8. Beginners Guide
User Manual:
Open the PDF directly: View PDF .
Page Count: 605 [warning: Documents this large are best viewed by clicking the View PDF Link!]
JAVA
ABeginner’sGuide
AdvancedFeatures(CoreSeries)
UpdatedToJava8.
-Harry.H.Chaudhary.
(ITManager&AnonymousHacktivist@AnonymousInternational)
Publisher’sNote:
Everypossibleefforthasbeenmadetoensurethattheinformationcontainedinthis
book is accurate, and the publisher or the Author–Harry. H. Chaudhary can’t accept
responsibility for any errors or omissions, however caused. All liability for loss,
disappointment, negligence or other damage caused by the reliance of the Technical
Programmingorotherinformationcontainedinthisbook,ofintheeventofbankruptcyor
liquidationorcessationoftradeofanycompany,individual;orfirmmentioned,ishereby
excluded.
SunMicrosystemsandOraclethetrademarks,aretheTrademarksoftheSun(Now
Oracle)&Oraclegroupofcompanies.SunMicrosystemsandOraclethetrademarksare
listed at their websites. All other marks are property of their respective owners. The
examples of companies, organizations, products, domain names, email addresses, logos,
people, places, and events depicted herein are fictitious. No association with any real
company,organization,product,domainname,emailaddress,logo,person,place,orevent
isintendedorshouldbeinferred.
Theauthorandpublisherhavetakencareinthepreparationofthisbook,butmake
noexpressedorimpliedwarrantyofanykindandassumenoresponsibilityforerrorsor
omissions.Noliabilityisassumedforincidentalorconsequentialdamagesinconnection
withorarisingoutoftheuseoftheinformationorprogramscontainedherein.
This book expresses the author views and opinions. The information contained in
this book is provided without any express, statutory, or implied warranties. Neither the
authors,andPublisher,noritsresellers,ordistributorswillbeheldliableforanydamages
causedorallegedtobecausedeitherdirectlyorindirectlybythisbook.
Copyright©2010-2014.ByHarry.H.Chaudhary(CEOProgrammers
Mind.)
PublishedByProgrammersMind||CreatespaceInc.ODPublishing,LLCUSA.
Allrightsreserved.Thisbookoranyportionthereofmaynotbereproducedorusedinany
mannerwhatsoeverwithouttheexpresswrittenpermissionoftheauthorexceptfortheuse
ofbriefquotationsinabookrevieworscholarlyjournal.
ISBN-13:978-1500864408.
ISBN-10:1500862347.
PrintedByCreatespaceO-DPublishingLLCUSA.[SECONDEDITION 2014 ]
Marketing&DistributedBy||AmazonInc.||Programmer’sMindInc.||Lulu.com
||GoogleBooks&GooglePlayStore.||other25worldwideBookstores.
Dedication
“Thisbookisdedicatedtoallthosewhomakethedailysacrifices,
Especiallythosewho’vemadesacrifice,toensureourfreedom&security.”
ThankstoLordShivaalotforgivingmethetechnicalandallabilitiesin
mylifetowrite.
DearDad,Thankyoubaauji,forteachingmebyexamplewhatitmeans
tolivealifebasedonprinciples.
Dear2Mom’s,Thankyouforshowingmeinarealwayhowtolive
accordingtothemostimp.principle,andunconditionallove.
DearSisters&Brother+Priya,ThankU,yoursmilebrightensmyevery
day.Yourzestmakesmyheartsing.IloveyouAll.
Iwouldespeciallyliketomentionthenameofbeautifulfacesinsidemy
lifewhohelpedmeincopingwithmysorrows:
ThankyouPriyanka,youarethemeaningofmylifeandappleofmy
eyes,ILoveYoumorethanIcansay.
ThankUHemZizu,Navneet,Aman(Rajjo)Eminem-youarethe
inspirationyoumademelike“Singforthemovement”,
ThankstoallAnonymousAndBlackHatHackersworldwide.
InLovingMemoriesofMyLovedOne–MyUncleLt.G.C
InLovingMemoriesofMyLovedOne–MyLt.GrandMom.
Youtoldmethateverythingwillbeokayintheend,
Youalsotoldmethat,ifit’snotokay,it’snottheend.
“I’llsearchforyouthrough1000worlds&10000lifetimesuntilIfindyou
AboutAuthor:
Harry,is an AnonymousHacktivist, GOC Famous computer Programmer and
BestsellingJavaAuthorandscientificallyHackingProfessionalhasauniqueexperience
inthefieldofcomputersProgramming,HackingandCyberSecurity.
He has helped many Countries Governments and many multinational Software
companiesof aroundthe globeto securetheir networksand securities.He hasauthored
severalbooksonVariousComputersProgrammingLanguagesandcomputersecurity&
Hacking.
HeistechnicallygraduatesoftwareengineerandMaster.Heistheleadingauthority
onCProgrammingandC++ProgrammingaswellasonCoreJavaandDataStructure
andAlgorithms. His acclaimed C and C++ ,C# & Java books. He has over 5 years of
experience as a software methodologist. His teaching and research interests are in the
areasofartificialintelligence,programminglanguages.
Heislivingtwolives.Onelife,HeisaComputerprogramwriterforarespectable
softwarecompany.Theotherlifeislivedincomputers,wherehegobythehackeralias
“ChiefHacker–CaptainHarry”.CurrentlyheisworkingasofflineITmanager@world
famouscommunityAnonymousinternationalCommunity.
-TeamAnonymous.
Authorside:
You may have noticed something missing here: no impressive of credentials. I
haven’tbeenaprofessorataPrestigiousUniversityforaquarter-century;neitheramIa
topexecutiveataSiliconValleygiant.Insomeways,I’mastudentofTechnology,just
likeyouare.
Andmyexperienceovertheyearshasshownmethatmanyofthepeoplewhoknow
themostabouthowtechnologyworksalsohaveratherlimitedsuccessinexplainingwhat
theyknow inaway thatwill allowmeto understandit. Myinterests,and Ibelieve my
skills,lienotinbeinganexpert,butaneducator,inpresentingcomplexinformationina
formthatissensible,digestibleandfuntoreadmybooks.
“Whatisreal?Howdoyoudefinereal?Ifyou’retalkingaboutwhatyoucanfeel,what
youcansmell,whatyoucantasteandsee,thenrealissimply,electricalsignalsinterpreted
byyourbrain.”
‘‘…Iamjustnowbeginningtodiscoverthedifficultyofexpressingone’sideason
paper.Aslongasitconsistssolelyofdescriptionitisprettyeasy;butwherereasoning
comesintoplay,tomakeaproperconnection,aclearness&amoderatefluency,istome,
asIhavesaid,adifficultyofwhichIhadnoidea…’’
–HarrY.
∞ InsideChaptersataGlance ∞
Unit Chapters&TopicsInsidetheBook Page
00. Preface. 006.
01. OverviewofJava 008.
02. JavaLanguage 023.
03. ControlStatements 039.
04. Scannerclass,Arrays&CommandLineArgs 048.
05. Class&ObjectsinJava 059.
06. InheritanceinJava 082.
07. Objectorientedprogramming 098.
08. PackagesinJava 106.
09. InterfaceinJava 115.
10. StringandStringBuffer 129.
11. ExceptionHandling 142.
12. Multi-ThreadedProgramming 185.
13. Modifiers/Visibilitymodes 240.
14. WrapperClass 255.
15. Input/OutputinJava 273.
16. AppletFundamentals 338.
17. AbstractWindowsToolkit(AWT) 357.
18. IntroductonToAWTEvents 404.
19. PaintinginAWT 445.
20. java.lang.ObjectClass 470.
21. CollectionFramework 490.
22. Java8FeaturesforDevelopers–Lambdas. 540.
23. Java8Functionalinterface,Stream&TimeAPI. 565.
24. KeyFeaturesthatMakeJavaMoreSecurethanOtherLanguages. 579.
Preface
∞EssentialJavaSkills—MadeEasy! ∞
Learn the all basics and advanced features of Java programming in no time from
BestsellerJavaProgrammingAuthorHarry.H.Chaudhary(Morethan1,67,000
BooksSold!).ThisJavaGuide,startswiththebasicsandLeadstoAdvancefeaturesof
JavaindetailwiththousandsofJavaCodes,I promisethisbook willmakeyouexpert
levelchampionofjava.Anyonecanlearnjavathroughthisbookatexpertlevel.
Engineering Students and fresh developers can also use this book. This book
coverscommoncoresyllabusforallComputer ScienceProfessional Degrees Ifyou are
reallyseriousthengoaheadandmakeyourdaywiththisultimatejavabook.
ThemainobjectiveofthisjavabookisnottogiveyoujustJavaProgramming
Knowledge,Ihavefollowedapatternofimprovingthequestionsolutionofthousandsof
CodeswithcleartheoryexplanationswithdifferentJavacomplexitiesforeachjavatopic
problem,andyouwillfindmultiplesolutionsforcomplexjavaproblems.
WhatSpecial–
InthisbookIcoveredandexplainedseveraltopicsoflatestJava8Featuresindetailfor
Developers&Fresher’s,TopicsLike–Lambdas.||Java8Functionalinterface,||Stream
andTimeAPIinJava8.
If you’ve read this book, you know what to expect a visually rich format
designed for the way your brain works. If you haven’t, you’re in for a treat. You’ll see
whypeoplesayit’sunlikeanyotherJavabookyou’veeverread.
Learninganewlanguageisnoeasytaskespeciallywhenit’sanObjectoriented
programminglanguagelikeJava.Youmightthinktheproblemisyourbrain.Itseemsto
haveamindofitsown,amindthatdoesn’talwayswanttotakeinthedry,technicalstuff
you’reforcedtostudy.Thefactisyourbraincravesnovelty.
It’s constantly searching, scanning, waiting for something unusual to happen.
Afterall,that’sthewayitwasbuilttohelpyoustayalive.Ittakesalltheroutine,ordinary,
dullstuffandfiltersittothebackgroundsoitwon’tinterferewithyourbrain’srealwork
—recordingthingsthatmatter.Howdoesyourbrainknowwhatmatters?
This Java book doesn’t require previous programming experience. However, if
youcomefromaCorC++programmingbackground,thenyouwillbeabletolearnfaster.
Forthisreason,thisjavabookpresentsaquickdetailedoverviewofseveralkey
featuresofJava.Thematerialdescribedherewillgiveyouafootholdthatwillallowyou
towriteandunderstandsimple&typicalprograms.Mostofthetopicsdiscussedwillbe
examined in greater detail in upcoming chapters with thousands of live java code
examples.
As we know in the past few years document the following fact: The Web has
irrevocably recast the face of computing and programmers unwilling to master its
environmentwillbeleftbehind.Theprecedingisastrongstatement.Itisalsotrue.
More and more, applications must interface to the Web. It no longer matters
muchwhattheapplicationis,nearuniversalWebaccessisdragging,pushing,andcoaxing
programmerstoprogramfortheonlineworld,andJavaisthelanguagethatmanywilluse
todoit.Frankly,fluencyinJavaisnolongeranoptionfortheprofessionalprogrammer,it
isarequirement.Thisbookwillhelpyouacquireit.
CHAPTER
∞1∞
(OverviewofJava)
Introduction-
Java is a powerful object oriented programming language developed by Sun
MicrosystemsInc.in1991.Javawasdevelopedforconsumerelectronicdevicesbutlater
it was shifted towards Internet. Now Java has become the widely used programming
language for the Internet. Java is a platform neutral language (Machine Independent).
ProgramdevelopedbyJavacanrunonanyhardwareoronanyoperatingsysteminthis
world.
Sun Microsystems (Oracle) formally announced Java at a major conference in
May 1995. Ordinarily, an event like this would not have generated much attention.
However, Java generated immediate interest in the business community because of the
phenomenalinterestintheWorldWideWeb.
Javaisnowusedto createWebpageswithdynamicandinteractivecontent,to
developlarge-scaleenterpriseapplications,toenhancethefunctionalityofWorldWide
NeedforJava-
Javawasdevelopedduetotheneedforaplatformneutrallanguagethatcouldbe
usedtocreatesoftwaretobeembeddedinvarious consumerelectronicdevices,suchas
microwaveovensandremotecontrols.TheprogramwritteninCandC++arecompiled
foraparticularpieceofhardwareandsoftwareandthatprogramwillnotrunonanyother
hardware or software. So we need C/C++ compilers one for each type of hardware to
compileasingleprogram.Butcompilersareexpensiveandtime-consumingtocreate.So
there is a need for platform neutral language. So that program compiled from that
compilercanrunonanyhardware.ThisneedledtothecreationofJava.
JavaClassLibraries-
Java programs consist of pieces called classes. Classes consist of pieces called
methodsthat perform tasks andreturn information whenthey complete theirtasks.You
can program each piece you may need to form a Java program. However, most Java
programmerstakeadvantageofrichcollectionsofexistingclassesinJavaclasslibraries.
TheclasslibrariesarealsoknownastheJavaAPIs(ApplicationProgrammingInterfaces).
Thus, there are really two pieces to learning the Java “world.” The first is
learningtheJavalanguageitselfsothatyoucanprogramyourownclasses;thesecondis
learninghowtousetheclassesintheextensiveJavaclasslibraries.
Throughout the book, we discuss many library classes. Class libraries are
provided primarily by compiler vendors, but many class libraries are supplied by
independent software vendors (ISVs). Also, many class libraries are available from the
Internet and World Wide Web as freeware or shareware. You can download free ware
productsandusethemforfreesubjecttoanyrestrictionsspecifiedbythecopyrightowner.
BasicsofaTypicalJavaEnvironment-
Java systems generally consist of several parts: An environment, the language,
the Java Applications Programming Interface (API) and various class libraries. The
following discussion explains a typical Java program development environment, Java
programsnormallygothroughfivephasestobeexecuted.Theseare:edit,compile,load,
verify and execute. The descriptions that follow use the standard Java SE 7
DevelopmentKit(JDK7),whichisavailablefromOracle.
IfyouareusingadifferentJavadevelopmentenvironment,thenyoumay
needtofollowadifferentprocedureforcompilingandexecutingJavaprograms.In
thiscase,consultyourcompiler’sdocumentationfordetails.
Note: If you are not using UNIX/Linux, Windows 95/98/ME or Windows
NT/2000,refertothemanualsforyoursystem’sJavaenvironmentoraskyourinstructor
howtoaccomplishthesetasksinyourenvironment(whichwillprobablybesimilartothe
environment,Phase1consistsofeditingafile.
Thisisaccomplishedwithaneditorprogram(normallyknownasaneditor).The
programmertypesaJavaprogram,usingtheeditor,andmakescorrections,ifnecessary.
Whentheprogrammerspecifiesthatthefileintheeditorshouldbesaved,theprogramis
storedonasecondarystoragedevice,suchasadisk.Javaprogramfilenamesendwiththe
.javaextension.
TwoeditorswidelyusedonUNIX/Linuxsystemsareviandemacs.OnWindows
95/98/MEandWindowsNT/2000,simpleeditprogramsliketheDOSEditcommandand
theWindowsNotepadwillsuffice.
Java integrated development environments (IDEs), such as Forte for Java
Community Edition, NetBeans, Borland’s JBuilder, Symantec’s Visual Cafe and IBM’s
VisualAgehavebuiltineditorsthatareintegratedintotheprogrammingenvironment.
We assume the reader knows how to edit a file. Languages such as Java are
object-oriented—programminginsuchalanguageiscalledobject-orientedprogramming
(OOP)andallowsdesignerstoimplementtheobjectorienteddesignasaworkingsystem.
Languages such as C, on the other hand, are procedural programming languages, so
programmingtendstobeaction-oriented.
InC,theunitofprogrammingisthefunction.InJava,theunitofprogrammingis
theclassfromwhichobjectsareeventuallyinstantiated(afancytermfor“created”).Java
classes contain methods (that implement class behaviors) and attributes (that implement
classdata).
Cprogrammersconcentrateonwritingfunctions.Groupsofactionsthatperform
some common task are formed into functions, and functions are grouped to form
programs.Data arecertainlyimportantinC, butthe viewisthat dataexist primarilyin
supportoftheactionsthatfunctionsperform.Theverbsinasystemspecificationhelpthe
Cprogrammerdeterminethesetoffunctionsneededtoimplementthatsystem.
Java programmers concentrate on creating their own user-defined types called
classesandcomponents.Eachclasscontainsdataandthesetoffunctionsthatmanipulate
thatdata.ThedatacomponentsofaJavaclassarecalledattributes.
ThefunctioncomponentsofaJavaclassarecalledmethods.Justasaninstance
ofabuilt-intypesuchasintiscalledavariable,aninstanceofauser-definedtype(i.e.,a
class)iscalledanobject.Theprogrammerusesbuilt-intypesasthe“buildingblocks”for
constructinguser-definedtypes.
The focus in Java is on classes (out of which we make objects) rather than on
functions.ThenounsinasystemspecificationhelptheJavaprogrammerdeterminetheset
of classes from which objects will be created that will work together to implement the
system.
Classes are to objects as blueprints are to houses. We can build many houses
fromoneblueprint,andwecaninstantiatemanyobjectsfromoneclass.Classescanalso
haverelationshipswithotherclasses.
Forexample,inanobject-orienteddesignofabank,the“bankteller”classneeds
torelatetothe“customer”class.Theserelationshipsarecalledassociations.Wewillsee
that,whensoftwareispackagedasclasses,theseclassescanbereusedinfuturesoftware
systems.Groupsofrelatedclassesareoftenpackagedasreusablecomponents.
Eachnewclassyoucreatewillhavethepotentialtobecomeavaluablesoftware
assetthatyouandotherprogrammerscanusetospeedandenhancethequalityoffuture
software-developmentefforts—anexcitingpossibility.
RelationofJavawithC,C++,&C#
FromCJavaderivesitssyntaxandfromC++itderivesobjectorientedfeatures.
It is not an enhanced version of C++. Java is neither upwardly nor downwardly
compatiblewithC++.OneimportantthingthatIwanttotellyouisthatJavalanguagewas
notdesignedtoreplaceC++andC#.AnotherlanguagedevelopedbyMicrosofttosupport
the.NETFramework,C# iscloselyrelatedtoJavabecausebothshareC++andC style
syntax,supportdistributedprogramming,andutilizethesameobjectmodel.
PrimaryObjectiveofJavaistoachieve-
1. Security:-
ThereisnothreatofvirusinfectionwhenweuseJavacompatibleWeb
Browser.Also thereis no threatofmalicious programs thatcan gather private
information,suchascreditcardnumbers,bankaccountbalancesandpasswords
fromlocalmachine.
Javaprovidesafirewallbetweenanetworkedapplicationandourcomputer.
2. Portability:-
Java programs are portable from one computer to another computer
runningdifferenttypesofoperatingsystemsandhavingdifferenthardware.
JavaBytecode-
Theoutputof aJava compilerisbytecode notthemachine code(“.class”file).
BytecodeisahighlyoptimizedsetofinstructionsdesignedtobeexecutedbytheJavarun-
timesystem,whichiscalledasJVM(JavaVirtualMachine).
JVM is the interpreter which interprets the bytecode. Compiled program runs
faster but still Java uses interpreter to achieve portability so Java programs runs a little
slower.NowaprogramcompiledthroughaJavacompilercanruninanyenvironmentbut
JVMneedstobeimplementedforeachplatform.Javaprogramsareinterpreted.Thisalso
helpstomakeitsecurebecausetheexecutionofeveryJavaprogramisunderthecontrol
ofJVM.
JIT(JustInTime):-
JITisatranslatorusedbyJVMtotranslatebytecodeintoactualmachinecode.It
doesnottranslateentirebytecodesratherittranslatespiecebypieceondemandbasis.
VariousVersionsofJava:-
Java1
JDK1.0
JDK1.1
Java2
JDK1.2
JDK1.3
JDK1.4
JDK1.5orJDK5
JDK1.6orJDK6
Java1.7orSE7
JavaSE8(Java8,April2014)
Note1-JDK(JavaDevelopmentKit)
Note2-ManyfeaturesofoldJavaversionsaredeprecatedbynewversions
OfJavabutstillwecanusethem.
TypeofapplicationsJavacandevelop:-
1. StandaloneApplications-Astandaloneapplicationisaprogramthatrunsonour
localcomputerundertheoperatingsystemofthatcomputerjustlikeaCoraC++
program.
2. Applets- An applet is a small program which travel across the Internet and
executed by a Java-Compatible web browser, such as Internet Explorer or
NetscapeNavigator,ontheclientmachine.
Anapplet is actuallya tinyJava program,dynamicallydownloaded acrossthe
network.Appletprogramsarestoredonawebserverandtheytravelstoclient
machineonrequestfromtheclientmachine.
Anappletcannotbeexecutedlikestandaloneapplication.Appletcanbe
executedonlybyembeddingitintoanHTMLpagelikeasoundfileoraimage
fileoravideoclip.
Now this HTML page which has applet embedded into it can be run
afterdownloadingsuchHTMLpagebyawebbrowseronalocalmachine.An
appletisaprogramthatcanreacttouserinputandcanchangedynamically.It
doesnotrunthesameanimationorsoundoverandover.
3. WebApplications-ThesearetheprogramswhichrunonWebServer.Whenwe
accessawebsitebyspecifyingtheURL(UniversalResourceLocator)inaweb
browserthenthewebbrowsersendsarequesttothewebserverforaparticular
Website.Afterreceivingthisrequestserverrunsaprogramandthisprogramis
calledasWebApplication.WeuseJavaServletsandJSP(JavaServerPages)to
writesuchprograms.
Theseprogramsrunontheserverandthensendtheresult/responseto
the client. JSP pages can be thought of as a combination of HTML and Java
Code.TheWebServerconvertsJSPpagesintoJavaServletsbeforeexecution.
WhenaclientrequestforaparticularURLandtheURLcorrespondsto
an HTML page the web server simply returns the HTML page to the client,
which then displays it. If the URL corresponds to the servlet or JSP then it is
executedontheServerandtheresult/responseisreturnedtotheclient,whichis
thendisplayedbytheclient.
4. DistributedApplications-Javaapplicationisdividedintosmallprogramswhich
can run on separate machines. The objects used in these programs can
communicate with each other. These applications are known as Distributed
Applications. This allowed objects on two different computers to execute
procedureremotely.ForthisRMI(RemoteMethodInvocation)isused.
CharacteristicsofJava:-
1. Simple- The syntax of Java is almost similar to C and C++ so that a
programmer is familiar with C/C++ does not have to learn the syntax from
scratch. But many features of C/C++, which are either complex or result in
ambiguityhavebeenremovedinJava.
1. Java does not support multiple inheritance, as the concept is a bit
complexandmayresultinambiguity.
2. Javadoesnotsupportglobalvariables,whichalsoleadtomanybugsin
C/C++programs.
3. Javadoesnotusepointersanddoesnotallowpointerarithmetic,which
is cause of most of the bugs in C/C++ programs due to inherent
complexity.
4. Javadoesnotsupportoperatoroverloadingasitmayleadtoconfusion.
5. There is no concept of garbage value in Java. We have to initialize
variablesbeforeuse.
2. Secure-JavaprogramsrunwithintheJVM(JavaVirtualMachine)andthey
are inaccessible to other parts. This greatly improves the security. A Java
programrarelyhangsduetothisfeature.ItisquiteunlikeC/C++programs,
whichhangfrequently.Java’ssecuritymodelhasthreeprimarycomponents:
1. Classloader.
2. BytecodeVerifier.
3. SecurityManager.
Java uses different class loaders to load class files (executable files)
fromlocalmachineandremotemachines.Theclassesloadedfromremote
machines like Applet classes are not allowed to read or write files on the
localmachine.Thispreventsamaliciousprogramfromdamagingthelocal
file system.Bytecode verifier verifies the bytecode as soon as class loader
completes its work. It ensures that bytecode is valid Java code. It almost
eliminates the possibility of Java program doing some malicious activity
likeaccessingthememoryoutsidetheJVM.TheSecurityManagercontrols
many critical operations like file deletion, creation of threads etc. These
operations are allowed only if the Java programs have sufficient
permissionsotherwiseSecurityManagerdoesnotallowtheoperationsand
generatesSecurityException.
3. Portable-Javaprogramsareplatformindependent.Theyfollowthepolicyof
write-once-run-anywhere.AJavaprogramwrittenforWindowsPlatformcan
runonanyotherplatform(Unix,Linux,SunSolarisetc.)simplybycopying
the bytecode (“.class” files). There is no need to copy the source code and
compile it again as in case of a C/C++ program. This feature has made the
Javaapowerfullanguage.Wecanrunbytecodeonanymachineprovidedthat
themachinehastheJVM.JVMisitselfisplatformdependentbutitmakesthe
Java code platform independent. It is actually JVM which converts the
bytecodeintomachinecodeandexecutesthem.
SowecansaythatJavaisaportablelanguage.Onemorefeaturewhich
makesJavahighlyportableisthatprimitivedatatypesareoffixedlength
irrespectiveof the platform.For example anint will alwaysbe 4 bytesin
Java. This is unlike C/C++ where size of int can be 2 bytes on some
machinesand4bytesonothermachines.
4. ObjectOriented-Javaisalmostpureobject-orientedlanguagebutitsupports
primitivedatatypeslikebyte,short,int,long,float,double,char,booleanfor
theperformancereasons.
5. Robust:-Mostprogramsfailoneofthetworeasons:
1. MemoryManagement.
2. Exceptionalconditionsatruntime.
Whiledesigning the language oneof the aimwasto ensure thatJava
programs are as robust as possible i.e. they should rarely fail. So due
importancewasgiventotheabovetwofactorsintheJava.
InJavamemoryallocationandde-allocationishandledinthelanguage
itself, which eliminates many problems caused due to dynamic memory
management features in C/C++. Java also supports object oriented
exceptionalhandlingfeaturestohandleexceptionalconditions,whichoccur
atrun-time.ThisallowsaJavaprogramtorecoverandcontinueexecution
evenafteranexceptionalconditionoccurs.
6. Multithreaded:- Java was designed to meet the real world requirement of
creating interactive, networked programs. Java provides support for writing
multi-threadedprogramstoachievethis.Thisallowstheprogrammertowrite
programsthatcandomanythingsconcurrently.
ForexampleaGUI(GraphicalUserInterface)basedapplicationmight
belisteningtousereventsandtakingappropriateaction,aseparatethread
mightbedoingprintingandaseparatethreadmightbedownloadingafile
fromsomemachineacrossthenetwork,allofthisbeingdoneconcurrently.
ThisresultsinbetterperformanceandbetterCPUutilization.
Itispossibletowritemulti-threadedprogramsinotherlanguagesalso
butitisachievedonlybymakinguseofSystemcallswhileincaseofJava
itcanbeachievedbyusingfeaturesofthelanguageitself.
7. Architecture-neutral-Oneofthemainproblemsfacingprogrammersisthat
no guarantee exists that if we write a program today, it will run tomorrow-
even on the same machine. Operating system upgrades, processor upgrades,
and changes in core system resources can all combine to make a program
malfunction.ButthegoalofJavaprogramsis“writeoncerunanywhere”.
8. InterpretedandHighPerformance-Javaprogramsareinterpretedbutstill
theyrunfastascomparedtootherinterpreters.
9. Distributed-JavaisdesignedfordistributedenvironmentoftheInternet.Java
has built-in support for various TCP/IP based protocols for this purpose. In
factaccessingaresourceusingaURLissimilartoaccessingafileonthelocal
machine. Java also has features for Remote Method Invocation, which is
somewhatsimilar to RemoteProcedure Calls(RPC). This allowsobjects on
differentcomputerstoexecuteproceduresremotely.Javahasbuilt-inAPI’sfor
thispurposecalledasRMI.
10. Dynamic-EveryJavaclassisaseparateunitofexecution.Aclassisloadedat
theruntimeonlywhenitisneeded.Defaultmechanismforbindingmethods
inJavaisalsodynamic(run-timebinding).
RunningaStandaloneJavaApplication:-
WhenaCorC++programiscompiled,itisdirectlytranslatedintomachinecode
ofaparticularprocessororaparticularplatform.ButrunningaJavaprogramisatwo-step
process.InJavatranslationfromsourcecodetotheexecutablecodeisachievedusingtwo
translators:
1. Java Compiler - First of all Java program is compiled into bytecode.
Bytecode are just like machine code but not for a particular processor or
platform.Bytecodescannotbedirectlyexecuted.
2. Java Interpreter (JVM) - Java interpreter by using JIT translates the
bytecodeintoactualmachinecodeofaparticularplatform.
Note 1- C or C++ programs are compiled only once but Java bytecodes are translated
everytimeweexecuteJavaprograms.SoJavaprogramsrunalittleslowerascomparedto
C/C++programs.
Note 2- To run a Java program we need a Text Editor (Notepad or Edit), JDK (Java
Development Kit), and JVM (already installed in many operating system). We can also
useEcllipseorJCreaterinplaceofNotepad.
InstallingJava1.7onwinxp-
DoubleClickonMyComputer DoubleClickonCDDrive DoubleClickon
JDK1.7JavaInstallationFile PressNext,Next,…..
TosetthePath-
If we set the path of Java folder then we can run Java programs from anywhere
otherwisewehavetorunourjavaprogramsfromthebinfolderofJava.
RightClickonMyComputer Properties Advanced EnvironmentVariables Click
onPathandthenclickonEdit Clickonthevariablevalue Movethecursorattheend
of this line by pressing END Now type “c:\program files\Java\jdk1.7.0_01\bin; and
thenclickonOK,OK,OK.
CreatingafolderforJavaprograms:-
Double Click on My Computer Double Click on C: Drive Right
Click New Folder TypeJAVAPRG PressEnterandclosetheMyComputer.
StepsforrunningJavaProgramonacommandPrompt:-
Step1:-GoToCommandPrompt
Start Run Type“cmd”andclickonOK.
Step2:-Type“CD\JAVAPRG”andpressEnter
Step3:-Type“EditSum.Java”andpressEnter
Step4:-TypetheJavaProgramandclickonFile SaveandthenFile Exit
Step5:-Type“javacSum.Java”andpressentertocompile.Thiswillcreate
“Sum.class”file.Thisfileisknownasbytecode.
Step6:-Type“javaSum”andpressentertorun.ThiswillinvoketheJVM.
Step7:-Type“Exit”andthenpressentertoexitfromcommandprompt.
Note-WecanalsorunJavaprogramsthroughNotepadusingabovestepsbutinsteadof
usingEdit commandwe will useNotepad. Aftertyping theJavaProgram saveit tothe
folder“C:\JAVAPRG”afterchoosing“Allfiles”insaveasdialogbox.Tocompileandrun
wehavetofollowabovesteps.
JavaProgramSyntax:-
class<classname>
{
publicstaticvoidmain(Stringargs[])or(String[]args)
{
--------
}
}
FirstJavaProgram-Programtoaddtwonumbers(Sum.Java)
1.classSum
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.inta,b,sum;
6.a=5;
7.b=6;
8.sum=a+b;
9.System.out.print(“Sumis“+sum);//Output
10.}
11.}
Output:Sumis11.
Example1.2Programtoswaptwonumbers(Swap.Java)
1.classSwap
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.inta=5,b=7;
6.t=a;
7.a=b;
8.b=t;
9.System.out.print(“AfterSwapValuesare“+a+”,”+b);
10.}
11.}
Output:AfterSwapValuesare7,5
Comments-
Thereare3typesofcomments.
Singlelinecomment//
Multilinecomment/**/
Documentedcomment/***/
EveryJavaprogrammustcontainoneclass.InJavamain()methodcanbe
definedonlyinsideaclass.
Asourcefilemayhaveanynumberofclassandorinterfacedefinitionsbut
therecanbeatthemostonepublicclassorinterface.
Asourcefilemayormaynotcontainaclasshavingmain()methodbuta
standaloneJavaprogramalwaysstartsitsexecutionfrommain()method.So
the class from which we want to start the execution must have the main ( )
methoddefinedinit.
Themain()methodmustalwayshavethefollowingsignature:
publicstaticvoidmain(Stringargs[])
Note-
MethodprototypeisreferredtoassignatureinJava.
The keyword public indicates that the method can be accessed from
anywhere. The main( ) method must be declared public as it is called by the
code,whichis partofthe JVMandis outsidetheclass containingthemain()
method.
Thekeywordstaticindicatesthatmain()isaclasslevelmethodandcanbe
calledwithoutcreatinganyobjectitismustasnoobjectexistsbeforemain()is
calledandanyobjectcreationoccursonlyinsidethemain()method.
Thevoidkeywordprecedingmain()methodindicatesthatitdoesnotreturn
anyvalue.
Themain()methodtakesoneargument,whichisthearrayofStrings.Each
elementofthearrayrepresentsonecommandlineargument.
Systemisapredefinedclassthatprovidesaccesstothesystem,andoutisthe
output stream that is connected to the console. print( ) method can be used to
displayanytypeofinformation.
StructureofaJavaProgram–
All Java source files must end with the extension “.Java”. Java is a case sensitive
language.NotethatintheaboveprogramfirstletterofclassesSum,StringandSystemis
writteninuppercase.ItisbettertosavetheJavaprogramwiththefilenamewhichissame
as of class name, but it is not compulsory. But if class is declared as public then it is
compulsorytosavetheclassinafilewhosenameissameasofclassname.Aclasscan
contain only one public class but may contain as many non-public classes. If a file
containsmorethanoneclassthenaftercompilationseachindividualclassisputintoits
ownoutputfilenamedaftertheclassandusing.classextension.
Documentation Section -The documentation section contains a set of
comment lines giving the name of the program, the author and other details,
whichtheprogrammerwouldliketorefertoatalaterstage.Commentsexplain
whyandwhatofclassesandhowofalgorithms.Inadditiontosingle,multiline
comment Java also uses a third style of comment /**…*/ known as
documentationcomment.
Package Statement -A source file may have at the most one package
statement.Ifapackagestatementispresentitmustbethefirststatementinthe
Javaprogram.Onlycommentsmayappearbeforethepackagestatement.
ImportStatements-Asourcefilemayhavezeroormoreimportstatements.
Import statements are just like #include statement in C/C++. If present all the
importstatementsmust comeafter thepackagestatement andbefore theclass/
interfacedefinition.
InterfaceStatements-AnInterfaceislikeaclassbutincludesagroupof
methoddeclarations.Thisisalsoanoptionalsectionandisusedonlywhenwe
wishtoimplementthemultipleinheritancefeaturesintheprogram.
Classdefinitionnotcontainingmainmethod-AJavaprogrammaycontain
multiple class definitions. Classes are the primary and essential elements of a
JavaProgram.Theseclassesareusedtomaptheobjectsofreal-worldproblems.
Classdefinitioncontainingmainmethod-SinceeveryJavastand-alone
programrequiresa mainmethodasitsstartingpoint,thisclass istheessential
partofaJavaprogram.AsimpleJavaprogrammaycontainonlythispart.The
mainmethodcreatesobjectsofvariousclassesandestablishescommunications
between them. On reaching the end of main, the program terminates and the
controlpassesbacktotheoperatingsystem.
GarbageCollection-
MemoryallocationfortheJavaobjectsiscompletelydynamicbutJavadoesnothave
supportfor pointerarithmetic likeC/C++. Wheneverwe runa Javaprogram, JVMalso
runs another program (thread) called Garbage Collector in the background. Garbage
CollectorkeepscheckontheJavaobjects.
WheneveraJavaobjectisnotbeinguseditiscollectedbytheGarbageCollector
i.e.thememoryallocatedfortheobjectisaddedtothepool/heapoffreememoryandcan
be reused. This simplifies the task of the programmer to a large extent. This also
eliminates lots of bugs caused due to improper use of pointer arithmetic and memory
managementfeatureslikefreeingmemoryexplicitly.
MultiplechoiceQuestions:
1.Whichofthefollowingarevaliddefinitionsofanapplication’smain()method?
(a)publicstaticvoidmain();
(b)publicstaticvoidmain(Stringargs);
(c)publicstaticvoidmain(Stringargs[]);
(d)publicstaticvoidmain(Graphicsg);
(e)publicstaticbooleanmain(Stringargs[]);
2.WhichorganizationdevelopedtheJavalanguage?
(a)Microsoft(b)IBM
(c)SunMicrosytemsInc.(d)AT&T
3.Javabelongstowhichofthefollowinglanguagecategories?
(a)Object-Oriented(b)Procedural
(c)Both(a)&(b)(d)Noneoftheabove
4.Whichofthefollowingisnotacorrectstatement?
(a)GarbagecollectioninJavaisautomatic.
(b)Javaprovidessupportfordistributionapplications.
(c)JavaismoreefficientascomparedtoC/C++.
(d)JavaismoresecureascomparedtoC/C++.
5.Whichofthefollowingisacorrectstatement?
(a)Javaisaplatformindependentlanguage?
(b)JavaisanObject-Orientedlanguage?
(c)Javasupportsmulti-threading.
(d)Alloftheabove.
Answers:1.(c)2.(c)3.(a)4.(c)5.(d)
TheoryQuestions:
1.ExplainworkingofJavaVirtualMachine(JVM).
2.WhatarethedifferencesbetweenC++andJava?
3.Differencebetween“APPLET”and“APPLICATION”.
4.DisadvantagesofJava.
5.Howdoesgarbagecollectionwork?
6.WhatisBYTECode?
7.Isjavaafullyobjectorientedprogrammingornot?ifnotwhy?
8.WhatarethedifferenttypesofJavaApplications/Programs?
9.WhatistheextensionofaJavaexecutablefile?
10.WhatistheextensionofaJavasource/programfile?
11.WhichcommandisusedtocompileaJavaProgram?
12.WhichorganizationdevelopedtheJavalanguage?
13.WhatmakesJavaplatformindependent?
14.WhyJavaismoresecurelanguageascomparedtoC/C++?
15.WhyJavaismorerobustlanguageascomparedtoClanguage?
16.Whatdoweunderstandbydistributedapplication?
17.DescribesanyfourfeaturesofJava.
18.DescribesthestepsneededtocompileandrunaJavaprogram.
19.WhatarethemainreasonsforthepopularityofJava?
20.WhymanyfeaturesofC/C++havebeenremovedinJava?Namesome
ofthesefeatures.
21.NamethreetypesofcommentsinJava.
22.Listany10majordifferencesbetweenCandJava.
23.DescribethestructureofatypicalJavaprogram.
ProgrammingExercise:
1.Writeaprogramtocalculateaverageoftwointegernumbers.
2.Writeaprogramtoswap2numberswithoutusing3rdvariable.
3.Writeaprogramtoconverthours,minutesandsecondsintototalseconds.
4.Writeaprogramtocalculatetheareaandcircumferenceofagivencircle.
CHAPTER
∞2∞
(JavaLanguage)
Tokens-
Thesmallestindividualunitsareknownastokenssuchaskeywords,identifiers,
constants,strings&Operators.
A. Keywords are the reserved names of a language and cannot be used as names of
variables,functionsetc.
B.Identifierreferstothenamesofvariable,arrays,functions,classes,Interfacesetc.
C.Constants/Literalsrefertofixedvaluesthatwecannotchangeinaprogram.
D. Operators are special symbols which operate on variable & constants, and forman
expression.
E.Separatorsarethespecialcharactersusedtoseparatestatementssuchas“(){}[];
,.”
A.Keywords-
abstractcontinuegotopackage
synchronized
assertdefaultifprivate
this
booleandoimplements
protectedthrow
breakdoubleimport
publicthrows
byteelseinstanceofreturn
transient
caseextendsintshorttry
catchfinalinterfacestatic
void
charfinallylong
strictfpvolatile
classfloatnativesuper
while
constfornewswitch
enum
Note1-Thereare50reservedkeywordsinJava.Thekeywordconstandgotoarereserved
butnot used.The assertkeywordwasaddedby Java2 version1.4. Theenum keyword
wasaddedbyJava2version1.5.
Note2-In addition to keywords, Java reserves the following literals true, false, and
null.We can’t use these reserved names as Identifiers (Variable or Class or Interface
names).
B.Identifiers:-
Anidentifierisawordusedinaprogramtonameavariable,method(function),
class,interface,packageetc.Javaidentifiersarecasesensitive.
Identifiernamingrules(wemustfollow):-
1. AJavaidentifiermustbeginwithaletter,dollarsignorunderscore.Itcan’tbegin
withanumber.
2. Thesubsequentcharactersmaybedigitsalso.
3. Thereisnorestrictiononthelengthofidentifiers.
4. Java allows Unicode characters in identifiers. We can use , , , etc. in
identifiersastheyaretreatedaslettersinUnicode(ASCIIisreplacedbyUnicodein
Java).
Identifiernamingrules(weshouldfollow)-
1. Namesofalltheclassesandinterfacesstartwithaleadinguppercaseletterandeach
subsequentwordalsostartswithaleadinguppercaseletter.Restofthelettersmustbe
inlowercase.(ExampleStudentTest).
2. Names of all the public data members and methods start with a leading lowercase
character.Whenmorethanonewordareusedinaname,thesecondandsubsequent
wordsstartwithaleadinguppercaseletter.(ExamplenetAnnualProfit).
3. Names of variables that represent constant values use all uppercase letters and
underscoresbetweenwords.(ExamplePI).
C.Constants/Literals:-
A Literal represents a constant value which we can’t change. A literal can’t
appear on the left side of an assignment operator. A literal is a value specified in the
sourcecodeitisnotdeterminedatruntime.
TypeofLiterals-
1. 5,-5,0x5A,012,5l,5LareIntegerLiteralsinwhich5,-5aredecimal,0x5Aisa
hexadecimal,012isaoctal,lorLisforlong.
2. 5.23,-5.23,5.4f,5.4F,5.4d,5.4D,1.2E-03areFloatingPointLiteralswheref
or F is for single precision(float), d or D is for double precision, 5.23 is a
Standardnotationand1.2E-03isinexponentnotation(Scientificnotation)where
1.2ismantissaand-03isexponent.
3. ‘a’,‘A’,‘\n’,‘\141’,‘\u0061’areCharacterLiteralsinwhich‘\n’isanescape
sequence,‘\141’isoctalcodeforcharacter‘a’and‘\u0061’ishexa-decimalcode
forcharacter‘a’.
4. “matrix”isaStringLiteral.Stringisagroupofcharacters.InJavaStringsthere
is no line-continuation escape sequence as there in other languages. So Strings
mustbeginandendonthesameline.InJavastringsareofobjecttype.“\”Thisis
inquotes\””.
5. True,falseareBooleanLiterals.Trueandfalsearenotequalto1or0inJava.
Wecan’tconvertaBooleanvaluetointegerandvice-versa.
D.Operators-
Javaprovidesarichsetofoperators.Operatorscombineconstants,variablesand
sub-expressionstoformexpressions.MostoftheoperatorsinJavabehavelikeC/C++but
therearefewdifferences,whicharecoveredhere.
Operatorscanbeclassifiedas:
ArithmeticOperators(+,-,*,/,%)
TheseoperatorsaresameasinC/C++.
%operatorcanworkonfloatingnumbersalso.
When binary operator is applied on two operands of different types then
operandoflowertypegetsconvertedtothehighertypebeforetheevaluationand
thetypeoftheresultwillbesameasthatofoperandofhighertype.
DivisionormodulusbyzeroresultinArithmeticException(runtimeError)
incaseofintbutnotincaseoffloatingnumbers.
Whenweapplyarithmeticoperatorsonintandtheresultisoutsidetherange
of int then extra high order bits will be truncated and this new value will be
assigned to the variable receiving their result but in floating type in case of
overflow it will result in Infinity or –Infinity and in case of underflow it will
resultin0.
IncrementandDecrementOperators(++,—)
TheseoperatorsaresameasinC/C++.
inta=5,b;
b=++a*++a;
System.out.print(b);//42
a=5;
System.out.print(++a*++a);//42
RelationalOperators(<,>,<=,>=,instanceof)
TheseoperatorsaresameasinC/C++but<.<=,>,>=cannotbeapplied
onbooleantypesandreferencetypes.
instanceofoperator:-
The instanceof operator is used to test the class of an object. The
instanceofoperatorhasthegeneralform:
if(objectinstanceoftype)
Here, object is an instance of a class, and type is a class type. If object is an
instanceofthespecifiedtypeorinstanceofanysub-classofthespecifiedtype,
thentheinstanceofoperatorreturntrueotherwiseitsresultisfalse.
AssignmentOperators(=,+=,-=,*=,/=,%=)
TheseoperatorsaresameasinC/C++.
EqualityOperators(==,!=)
TheseoperatorsaresameasinC/C++.
LogicalOperators(&&,||,!)
TheseoperatorsaresameasinC/C++.
ConditionalOperator(?:)
ThisoperatorissameasinC/C++.
BitwiseOperators(&,|,^,~,<<,>>,>>>)
TheseoperatorsaresameasinC/C++exceptshiftoperators.Shiftoperatorsworksonly
onintegertype.
LeftShift(<<)Operator
Toobtaintheresultof<<operator,thebitsinthelefthandsideoperandareshiftedto
theleftasspecifiedbytherighthandoperandandtheemptybitpositionstotherightare
filledwithzero.Leftshiftingby1isequivalenttomultiplicationby2.Itispossiblethat
signoftheresultmaydifferfromthesignofthelefthandsideoperand.Thismayhappen
because the sign depends on the left-most bit, which can change from 0 to 1 or 1 to 0
hencethechangeinsign.
Exampleb=a<<2;Toobtainthevalueofb,shiftthebitsinaby2positionstotheleft
andfillthe2rightbitswithzero.
RightShift(>>)Operator(signed)
Toobtaintheresultof>>operator,thebitsinthelefthandoperandareshiftedto
therightasspecifiedbytherighthandoperandandtheemptybitpositionstotheleftare
filledwithsignbit.Rightshiftingby1isequivalenttodivisionby2.Thisoperatornever
changesthesignoftheresulti.e.itwillbesameasthesignofthelefthandoperand.
Exampleb=a>>2;Toobtainthevalueofb,shiftthebitsinaby2positionstotheright
andfillthe2rightbitswithsign(0ifaispositiveor1ifaisnegative.).
RightShiftwithzerofill(>>>)Operator(unsigned)
Rank Operators Description Associativity
1 ()
[]
.
Functioncall
Subscript
Direct
member
LefttoRight
2 ++
—
Increment
Decrement
RighttoLeft
To obtain the result of >>> operator, the bits in the left hand side operand are
shiftedtotherightasspecifiedbytherighthandoperandandtheemptybitpositionsto
theleftarefilledwith0.Rightshiftingby1isequivalenttodivisionby2.Ifshiftingtakes
placethenresultwillalwaysbepositive,astherightmostbitwouldbecomezero.
Exampleb=a>>>2;Toobtainthevalueofb,shiftthebitsinaby2positionstotheright
andfillthe2rightbitswith0.
PrecedenceofOperators:-
E.Separators:-
~
!
Bitwise unary
NOT
Logical unary
NOT
3 *
/
%
Multiplication
Division
Modulus
LefttoRight
4 +
-
Addition
Subtraction
LefttoRight
5 >>
>>>
<<
Bitwise Right
Shift
Bitwise Left
Shift
Bitwise Right
ShiftZeroFill
LefttoRight
6 >
>=
<
<=
instanceof
Greaterthan
Greater than
orequalto
Lessthan
Less than or
equalto
LefttoRight
7 ==
!=
EqualTo
NotEqualTo
LefttoRight
8 & BitwiseAND LefttoRight
9 ^ BitwiseXOR LefttoRight
10 | BitwiseOR LefttoRight
11 && LogicalAND,
circuitAND
LefttoRight
12 || Logical OR,
Short circuit
OR
LefttoRight
13 ?: Conditional
operator(Ternary) LefttoRight
14 =
+=
-=
*=
/=
%=
&=
|=
^=
>>=
<<=
>>>=
Assignment
Addition
assignment
Subtraction
assignment
Multiplication
assignment
Division
assignment
Modulus
assignment
Bitwise And
assignment
Bitwise Or
assignment
Bitwise XOR
assignment
Bitwise Right
Shift
assignment
Bitwise Left
Shift
assignment
Bitwise Right
ShiftZeroFill
assignment
RightToLeft
Symbol Name Purpose
() Parenthesis Used to contain list of
parameters in method
definition and invocation
(calling). Also used for
defining precedence in
expressions, containing
expressions in control
statements, and in
typecasting.
{} CurlyBraces Used to initialize arrays,
Alsousedtodefineablock
of statements, for classes,
interfaces, methods and
localscope.
[] Square
Brackets
Todeclareanarray.
;Semicolon Toterminateastatement.
,Comma Separates consecutive
identifiers in a variable
declaration, Also used to
chain statements together
insideadorstatement.
.Period Used to separate package
names from sub-packages
and classes. Also used to
separate a variable or
method from a reference
variable.
DataTypes-DatatypesinJavacanbebroadlyclassifiedintwocategories:
1.PrimitiveDataTypes/SimpleDataTypes-
Javaisanobjectorientedlanguage,buttheprimitivedatatypesarenotobjects.
TheyarekeptinJavaforperformancereason.Theyformthebasisforallothertypesof
datathatwedefineinourJavaprograms.Javaisastronglytypedlanguage.
NumericDataTypes
IntegerDataTypes
byte(1byte)Range -128to127
short(2bytes)Range -32768to32767
int(4bytes)Range -2147483648to2147483647
long(8bytes)Range -9223372036854775808to
9223372036854775807
Expressionscontainingbytes,shorts,int’sareautomaticallypromotedtoint.
FloatingPointDataTypes-
float(4bytes)Range 1.401298464324817E-45fto
3.4028234663852886E38f
double(8bytes)Range 4.9E-324dto1.7976931348623157E308d
BooleanDataType-Boolean
CharacterDataType-
char(2bytes)Range 0to65535
Note-Thefirst128charactersoftheUnicodesetarethesameasthe128charactersof7-
bitASCIIcharactersetandthefirst256charactersoftheUnicodecorrespondtothe256
charactersoftheExtendedASCII(8-bitISOLatin-1)characterset.
Java characters can also be used in integer expressions. The Unicode value of the
characterisusedwhenitispartofanintegerexpression.
1. Non-PrimitiveDataTypes/DerivedDataTypesorReference
DataTypes-Referencedatatypesarealsocalledderiveddatatypesasthey
arederivedfromtheprimitivedatatypes.
Classes
1. Built-In/LibraryClasses
2. User-DefinedClasses
Interfaces
3. Built-In/LibraryClasses
4. User-DefinedClasses
Arrays-ArraysarealsotreatedasobjectsinJava.
Java’sAutomaticConversionswilltakeplacewhen-
1.Thetwotypesarecompatible.
2.Thedestinationtypeislargerthanthesourcetype.
Variables-
Variablesarethenameofthememorylocationsthatcanstorevalues.Avariable
must be declared before we can store value in it. Or Variable is the place (Memory
Location)insidethemainmemorywherewecanstoreourdataorvalues.
Therearethreekindsofvariables:
LocalVariables:-Localvariablesareusedinsideblocksormethods.Local
variables (also known as automatic variables) are not initialized by default. A
localvariablemust beexplicitlyinitializedbeforebeingusedforthe firsttime
otherwise a compile time error “Variable might not have been initialized” will
come.
Example
inta,b=5;
if(b>2)
{
a=b;
}
System.out.print(a);
In the above program the value of a is not defined if the if condition is false, so the
compilerwillgiveanerror“Variableamightnothavebeeninitialized”.
InJava wecan notdefine avariable inthe innerblock withthe samename asof outer
block.
inta=5;
{
inta=7;//Error
}
InstanceVariables:-Instancevariableareusedtodefineattributesorstateof
anobject.
ClassVariables:-Classvariablesareusedtodefineattributes/state,whichis
commonforalltheobjectsofaclass.
LibraryMethodsofclassMath-
publicstaticdouble
sin(doublex);
Returnthesineoftheanglex
inradians
publicstaticdouble
cos(doublex);
Returnthecosineoftheangle
xinradians
publicstaticdouble
tan(doublex);
Return the tan of the angle x
inradians
publicstaticdouble
asin(doublex);
Returntheanglexofsine
publicstaticdouble
acos(doublex);
Returntheanglexofcosine
publicstaticdouble
atan(doublex);
Returntheanglexoftan
publicstaticdouble
toRadians(doublex);
Convertdegreesxtoradians
publicstaticdouble
toDegrees(doublex);
Convertradiansxtodegrees
publicstaticdouble
exp(doublex);
Returneraisedtox(ex)
publicstaticdouble
log(doublex);
Returnthenaturallgorithmof
x
publicstaticdoublelog10(double
x); Returnthenaturallgorithmof
xbase10
publicstaticdouble
sqrt(doublex);
Returnthesqrtofx
publicstaticdouble
ceil(doublex);
Return the smallest whole
number greaterthan orequal
tox(roundingup)
publicstaticdouble
floor(doublex);
Return the largest whole
numberlessthanorequaltox
(roundeddown)
publicstaticdouble
rint(doublex);
Returntheroundedvalueofx
publicstaticdouble
atan2(doublex,doubley);
Returntheanglewhose
tangentisx/y
publicstaticdouble
pow(doublex,doubley);
Returnxraisedtoy(xy)
publicstaticintround(float
x);
Returntheroundedvalueofx
inint
publicstaticlong
round(doublex);
Returntheroundedvalueofx
inlong
publicstaticdouble
random();
Returnsarandomnumber
between0to
0.999999999999999999
publicstaticintabs(intx); Returntheabsolutevalueofx.
publicstaticlongabs(long
x);
Returntheabsolutevalueofx.
publicstaticfloatabs(float
x);
Returntheabsolutevalueofx.
publicstaticdouble
abs(doublex);
Returntheabsolutevalueofx.
publicstaticintmax(intx,
inty);
Returnthemaximumofx&y
publicstaticlong
max(longx,longy);
Returnthemaximumofx&y
publicstaticfloat
max(floatx,floaty);
Returnthemaximumofx&y
publicstaticdouble
max(doublex,doubley);
Returnthemaximumofx&y
publicstaticintmin(intx,
inty);
Returntheminimumofx&y
publicstaticlongmin(long
x,longy);
Returntheminimumofx&y
publicstaticfloatmin(float
x,floaty);
Returntheminimumofx&y
publicstaticdouble
min(doublex,doubley);
Returntheminimumofx&y
publicstaticdouble
sinh(doublex);
Returnsthesinhyperbolicof
anglex
publicstaticdouble
cosh(doubley);
Returnsthecoshyperbolicof
anglex
publicstaticdouble
tanh(doublex);
Returnsthetanhyperbolicof
anglex
Note-TouseabovemethodswehavetoprefixMathclassname.
Examples:
1.doubletheta1=120.0;
doubletheta2=1.312;
System.out.println(theta1+”degreeis“+Math.toRadians(theta1)+”radians.”);
System.out.println(theta2+”radiansis“+Math.toDegrees(theta2)+”degrees”.);
Output:
120.0degreeis2.0943951023931953radians.
1.312radiansis75.17206272116401degrees.
2.doublenumber,root;
number=25.0;
root=0.0;
root=Math.sqrt(number);
System.out.println(“Sqrtofnumber”+number+”is”+root);
Output:
Sqrtofnumber25.0is5.0
3.doublex=3,y=3,z=0;
z=Math.pow(x,y);
System.out.println(“Valueofz:”+z);
Output:
Valueofz:27.0
4.doublea=3.0,b=4.0;//dynamicinitilization
doublec=(Math.sqrt(a*a+b*b));
System.out.println(“Hypotenuseis“+c);
Output:
Hypotenuseis5.0
MultipleChoiceQuestions:
1.WhichofthefollowingareJavakeywords?
(a)array
(b)boolean
(c)Integer
(d)protect
(e)super
2.Whichidentifierisinvalid?
(a)_xpoints
(b)r2d2
(c)bBb$
(d)set-flow
(e)thisisCrazy
3.Aninteger,xhasabinaryvalue(using1byte)of10011100.Whatisthe
binaryvalueofzafterthesestatements:
inty=1<<7;
intz=x&y;
(a)10000001
(b)10000000
(c)00000001
(d)10011101
(e)10011100
4.Whichstatementsareaccurate:
(a)>>performssignedshiftwhile>>>performsanunsignedshift.
(b)>>>performsasignedshiftwhile>>performsanunsignedshift.
(c)<<performsasignedshiftwhile<<<performsaninsignedshift.
(d)<<<performsasignedshiftwhile<<performsanunsignedshift.
5.Considerthetwostatements:
1.booleanpassingScore=false&&grade==70;
2.booleanpassingScore=false&grade==70;
Theexpression
grade==70
isevaluated:
(a)inboth1and2
(b)inneither1nor2
(c)in1butnot2
(d)in2butnot1
(e)invalidbecausefalseshouldbeFALSE
6. Giventhevariabledeclarationsbelow:
bytemyByte;
intmyInt;
longmyLong;
charmyChar;
floatmyFloat;
doublemyDouble;
Whichoneofthefollowingassignmentswouldneedanexplicitcast?
(a)myInt=myByte;
(b)myInt=myLong;
(c)myByte=3;
(d)myInt=myChar;
(e)myFloat=myDouble;
(f)myFloat=3;
(g)myDouble=3.0;
7.WhichofthefollowingJavareservedwordhasnouseasofnow.
(a)true(b)false
(c)goto(d)null
8.WhatisthesizeofdatatypeintinJava?
(a)2bytes(b)4bytes
(c)notdefined(d)2bytesor4bytes
Answer’s:
1(b,e)2(d)3(b)4(a)
5(d)6(b,e)7(c)8(b)
Theoryquestions:
1.WhyJavaisnot100%pureobjectorientedlanguage?
2.WhataretheprimitivetypesinJava
3.Namefourtop-levelelementsthatmayappearinaJavasourcefile.
4.Whatotherstatement(s)canappearbeforeapackagestatement?
5.NamethethreeJavareservedwords,whichareusedasliterals.
6.NametwoJavareservedwords,whicharenotusedinthelanguage
7.Whichprimitivedata-typesofJavaarenotthereinC?
8.NamethreekindsofvariablesinJava.
9.BrieflydescribingrulesforJavaidentifiers.
10.WhatisthepurposeofcommentsinaJavaprogram?
11.Nameanyfournumericdatatypesalongwiththeirrange.
12.HowarraysinJavaaredifferentfromC?
13.WhatareJavatokens?GivebriefdescriptionofdifferenttypesofTokens.
14.WhatareJavaliterals?Explainwithexamples.
15.WhatarethedifferentdatatypesinJava?Describeindetail.
ProgrammingExercise:
1.Writeaprogramwhichwillshowtheuseofallthebitwiseoperators.
2.Writeaprogramwhichwillshowallexplicitandimplicitconversions.
3.Writeaprogramwhichwillsolvesomeequationsofdifferentdatatypes
anddisplaytheresult.
4.Writeaprogramtoproofthatnameofainnerscopevariablecannotbe
sameasouterscopevariable.
5.Writeaprogramtocalculateareaofacircle.(usefinaltodeclareaconstant).
6.WriteaprogramtoconvertthechartoUnicode.
7.Writeaprogramtotypeconversioninttofloat.
8.Writeaprogramtocalculatemodulus(%)oftwofloatnumbers.
9.Writeaprogramtofindtherootsofaquadraticequation.
CHAPTER
∞3∞
(ControlStatement)
Introduction-
Controlstatementsareusedtochangetheflowofexecution.Java’scontrolstatements
canbeclassifiedintothreecategories.
1. SelectionStatements(DecisionControlStructure)Selectionstatementallows
theprogramtochooseanyonepathfromdifferentsetofpathsofexecutionbased
upontheoutcomeofanexpressionorthestateofavariable.
1. if
2. ifelse
3. nestedifelse
4. if-else-if
5. switch
(a)Syntaxofif(b)Syntaxofifelse
if(condition)if(condition)
{{
statements;}
}else
{
}
(c)SyntaxofNestedifelse(d)Syntaxofif-else-ifLadder
if(condition)if(condition1)
{{
if(condition)}
{elseif(condition2)
}{
else}
{elseif(condition3)
}{
}}
elseelse
{{
if(condition)}
{
}
else
{
}
}
(e)Syntaxofswitchcase
switch(expression)
{
case1:
statement1sequence;
break;
case2:
statement2sequence;
braek;
case3:
statement3sequence;
break;
—
—
casen:
break;
default:
defaultstatementsequence;
}
Example3.1Programtofindmaxoftwonumbers(Max.Java)
2.classMax
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.inta,b,max;
7.a=10;
8.b=20;
9.if(a>b)
10.max=a;
11.else
12.max=b;
13.System.out.println(“Maxoftwonumbersis“+max);//Output
14.}
15.}
Output:
Maxoftwonumbersis20
2. IterationStatements(LoopControlStructure)Loopingisaprocessbywhich
wecanrepeatasinglestatementoragroupofstatementsnnumberoftimes.
1. for
2. while
3. dowhile
(a)Syntaxofforloop.
for(initialize;condition;increment/decrement)
{
statements;
}
(b)Syntaxofwhileloop.
(c)
initialize;
while(condition)
{
statements;
increment/decrement;
}
(d)Syntaxofdowhileloop.
initialize;
do
{
statements;
increment/decrement;
}while(condition);
Note-
The condition can be any Boolean expression. The body of the loop will be
executed as long as the conditional expression is true. When condition becomes false,
controlpasstothenextlineofcodeimmediatelyfollowingtheloop.
Example3.2
1.classLoop1
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.intn=5;
6.for(inti=1;i<=n;i++)
7.{
8.for(intj=1;j<=i;j++)
9.System.out.print(j);
10.System.out.println();
11.}
12.}}
Output:
1
12
123
1234
12345
3. JumpStatements-Itallowsourprogramtoworkinanon-linearfashion.
1. break.
2. labeledbreak.
3. continue.
4. labeledcontinue.
5. return.
Mostofthestatementshavesamesyntaxasthecorrespondingstatementsin
C/C++.Howevertherearesomesignificantdifferences.
Theconditionalexpressionsusedintheif,for,whileanddostatementsmust
bevalidbooleanexpressionsi.e.theirvaluesshouldbeeithertrueorfalse.We
cannotuse0insteadoffalseoranon-zerovalueinsteadoftruethatisvalidin
C/C++.
Javadoesnothaveanygotostatementalthoughgotoisareservedwordinthe
language.Javaprovideslabeledbreakandlabeledcontinuestatementswhichare
oftenreferredtoasthecivilizedformofgotoastheyaresupposedtobebetter
substitutesofgotostatement.
InJava,switchexpressioncanbeanyintegerexpressionexceptlongi.e.the
typeoftheswitchexpressioncanbebyte,short,charorint.ButtheJava’sintis
of4byteswhichissameassizeoflonginC/C++.
ThecaselabelsareconstantexpressionsasinC/C++butthevaluesofthe
caselabelsmustbeintherangeofthetypeoftheswitchexpressionotherwise
theprogramwillnotcompile.
Thelabeledbreakstatementisusedtoterminatetheblockwhoselabelis
specified in the break statement. Unlike simple break statement, we can
terminateanyblock.Forexample,itispossibletoterminatetheoutermostloop
from inside a deeply nested for loop. The break statement can also be used to
terminateasimpleblock(i.e.theblockneednotbealooporswitchstatement)
Thelabeledcontinuestatementspecifiesthelabeloftheenclosingloopto
continue.Thelabelneednotcorrespondtotheclosestenclosingloop.
JumpStatement:-
(a)break
for(inti=1;i<=10;i++)
{
if(i==5)
break;//terminateloopifiis5
System.out.print(i);
}
Output:1234
(b)labledbreak
booleant=true;
first:{
second:{
third:{
System.out.println(“Beforethebreak”);
if(t)breaksecond;//breakoutofsecondblock
System.out.println(“Thiswillnotexecute”);
}
System.out.println(“Thiswillnotexecute”);
}
System.out.println(“Thisisaftersecondblock”);
}
Output:Beforethebreak
Thisisaftersecondblock
(c)continue
for(inti=0;i<10;i++)
{
System.out.print(i+““);
if(i%2==0)
continue;
System.out.println();
}
Note-Thiscodeusethe%operatortocheckifiiseven.ifitiseventhentheloop
willcontinuewithoutprintinganewline.
Output:
01
23
45
67
89
(d)labeledcontinue
outer:for(inti=0;i<5;i++)
{
for(intj=0;j<5;j++)
{
if(j>i)
{
System.out.println();
continueouter;
}
System.out.print(“\t”+(i*j));
}
}
Output:
0
01
024
0369
0481216
(e)return
intsum(inta,intb)
{
intc;
c=a+b;
return(c);
}
MultipleChoiceQuestions:
1.Giventhevariablesdefinedbelow:
intone=1;
inttwo=2;
charinitial=‘2’;
booleanflag=true;
Whichofthefollowingarevalid?
(a)if(one){}
(b)if(one=two){}
(c)If(one==two){}
(d)if(flag){}
(e)switch(one){}
(f)switch(flag){}
(g)switch(initial){}
2.Ifval=1inthecodebelow:
switch(val)
{
case1:System.out.print(“P”);
case2:
case3:System.out.print(“Q”);
break;
case4:System.out.print(“R”);
default:System.out.print(“S”);
}
Whichvalueswouldbeprinted?
(a)P
(b)Q
(c)R
(d)S
3.Assumethatvalhasbeendefinedasanpositiveintforthecodebelow:
if(val>4)
System.out.println(“TestA”);
elseif(val>9)
System.out.println(“TestB”);
else
System.out.println(“TestC”);
Whichvaluesofvalwillresultin“TestC”beingprinted:
(a)val<0
(b)valbetween0and4
(c)valbetween4and9
(d)val>9
(e)val=0
(f)novaluesforvalwillbesatisfactory
4.Forthecode:
m=0;
while(m++<2)
System.out.println(m);
Whichofthefollowingareprintedtostandardoutput?
(a)0
(b)1
(c)2
(d)3
(e)Nothingandanexceptionisthrown
5.Considerthecodefragmentbelow:
outer:for(inti=1;i<3;i++)
inner:for(j=1;j<3;j++)
{
if(j==2)
continueouter;
System.out.println(“i=”+i+”,j=”+j);
}
Whichofthefollowingwouldbeprintedtostandardoutput?
(a)i=1,j=1
(b)i=1,j=2
(c)i=1,j=3
(d)i=2,j=1
(e)i=2,j=2
(f)i=2,j=3
(g)i=3,j=1
(h)i=3,j=2
Answers:1(c,d,e,f,g)2(a,b)3(b)4(b,c)5(a,d)
TheoryQuestions:
1.DoesJavahas“goto”?
2.Whatarelabeledloops.
ProgrammingExercises:
1.Writeaprogramtocheckwhetheragivenyearisleapornot.
2.Writeaprogramtoprintthenumberofdaysinagivenmonth.(usingswitch)
3.WriteaprogramtoprintFibonacciseries.
4.Writeaprogramtocheckwhetheragivennumberisprimeornot.
5.Writeamenudrivenprogramtocalculateaddition,subtraction,multiplicationand
divisionoftwonumbers.
1forAdd
2forSubtract
3forMultiplication
4forDivide
5forExit(hint:dowhileandswitch)
6.Writeaprogramtoprintthereverseofanumber.(hint:1234willresultin4321).
7.Writeaprogramtofindthemaximumofthegiventhreenumbers.
8.Writeaprogramtoprintfirst10evennumbersusingjumpstatement.
ISBN13:978-1500730413.
CHAPTER
∞4∞
(ScannerClass&Arrays)
(CommandLineArguments)
Introduction-
Scannerclass:-
ThisisanewclassinJavaaddedinJDK1.5-6-7versiontotakeinputofprimitive
datatypefromtheuser.Itisveryeasytotakeinputusingthisclassaswehavetoonly
createanobjectofthisclassandhavetocallaparticularmethod.Thisclassisavailablein
java.utilpackage.
publicjava.util.Scanner(java.io.InputStream);
publicjava.util.Scanner(java.io.File)throwsjava.io.FileNotFoundException;
publicjava.util.Scanner(java.lang.String);
publicvoidclose();
publicbooleanhasNext();
publicjava.lang.Stringnext();
Toinputastringnotcontaininganyspace.
publicjava.lang.StringnextLine();
Toinputastringwhichmaycontainspacealso.
publicbooleanhasNextBoolean();
publicbooleannextBoolean();
publicbooleanhasNextByte();
publicbytenextByte();
publicbooleanhasNextShort();
publicshortnextShort();
publicbooleanhasNextInt();
Tocheckwhethernextvalueininputbufferisintornot.
publicintnextInt();
Toinputaintegervalue.
publicbooleanhasNextLong();
publiclongnextLong();
publicbooleanhasNextFloat();
publicfloatnextFloat();
publicbooleanhasNextDouble();
publicdoublenextDouble();
Example4.1:
1.importjava.util.*;
2.classSumInput
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Scannersc=newScanner(System.in);
7.inta,b,sum;
8.System.out.print(“EnterIstnumber”);
9.a=sc.nextInt();
10.System.out.print(“Enter2ndnumber”);
11.b=sc.nextInt();
12.sum=a+b;
13.System.out.println(“Sumis”+sum);
14.}
15.}
Output:
EnterIstnumber45
Enter2ndnumber55
Sumis100
Array-
AnarrayinJavaisanorderedcollectionofthesimilartypeofvariablesordata
items.Javaallowsarraysofanydimension.AnarrayinJavaisabitdifferentfromC/C++.
Wecannotspecifythesizeofthearrayatthetimeofdeclaration.Thememoryallocation
isalwaysdynamic.EveryarrayinJavaistreatedasanobjectwithonespecialattribute
length,whichspecifiesthenumberofelementsinthearray.
1.One-Dimensionalarray:-
Declaration-
typearray_name[];//Nomemoryallocationtakesplaceindeclaration.
Or
type[]array_name;
Itisimportanttonotethatthedeclarationdoesnotactuallycreateanarray.Itonlydeclares
areferencethatcandenoteanarrayobject.
inta1[],a2;
int[]a3,a4;
These two declarations declare a1, a3 and a4 to be reference variables that can denote
arrayof int,but thevariablea2cannotdenoteanarrayofintvalue. Itis simplyan int
variable.Whenthe[]notationfollowsthetype,allvariableinthedeclarationarearray.
Otherwisethe[]notationmustfollowseachindividualarraynameinthedeclaration.
Memoryallocationwiththehelpofnewoperator:-
array_name=newtype[SIZE];//SIZEcanbeaconstantoravariable.
Note1-Alltheelementsofarraywillbeautomaticallyinitializedtozerobuttoinitialize
the array with different values we can initialize the array in declaration itself. Array
declaration,memoryallocationandinitializationstepscanbecombinedintoone:-
inta[]={5,7,1};
Note2-Arrayindexstartsfromzero.
Note3:-In Java, all arrays store the allocated size in a variable named length. We can
accessthelengthofthearrayusingtheattributelength:
“array_name.length”.
Note4-inta[],b[];
a=b=newint[5];
In the above steps only one array is created by new, the reference of this array will be
stored first in b & then a. So both a & b are pointing to a single array. Assigning a
referencedoesnotcreateacopyoftheobject.
Example4.2SumofallthenumbersstoredinanArray.
1.classSumArr
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.inta[]={10,50,20,40,30};
6.intn=a.length,sum=0;
7.for(inti=0;i<n;i++)
8.sum+=a[i];
9.System.out.println(“Sumofnumbersis”+sum);
10.}
11.}
Output:Sumofnumbersis150
Example4.3Programtosortanarrayusingselectionsortingtechnique.
1.importjava.util.Scanner;
2.classSort
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.intn;
7.Scannersc=newScanner(System.in);
8.System.out.println(“Enterhowmanyelements”);
9.n=sc.nextInt();
10.inta[]=newint[n];
11.//inputarray
12.for(inti=0;i<n;i++)
13.{
14.System.out.print(“Enterelement”+(i+1)+”“);
15.a[i]=sc.nextInt();
16.}
17.//sorting
18.for(inti=0;i<n-1;i++)
19.for(intj=i+1;j<n;j++)
20.if(a[i]>a[j])
21.{
22.intt=a[i];
23.a[i]=a[j];
24.a[j]=t;
25.}
26.//output
27.for(inti=0;i<n;i++)
28.System.out.println(a[i]);
29.}
30.}
2.Two-DimensionalArray-
Declaration:-
typearray_name[][];
or
type[][]array_name;
Memoryallocation:-
array_name=newtype[ROWS][COLUMNS];
//ROWS&COLUMNScanbeconstantsorvariables
Sofarwehavediscussedthearrayvariablesthatcanstorealistofvalues.There
willbesituationwhereatableofvaluewillhavetobestored.Considerthefollowingdata
table,whichshowthevalueofsalesofthreeitemsbysalesperson.
Thetablecontainstotal12value,threeineachline.Wecanthinkofthistableas
amatrixconsistingoffourrowandthreecolumns.Eachrowrepresentsthevalueofsales
byaparticularsalespersonandeachcolumnsrepresentthevalueofsalesofaparticular
item.
Example4.4Programtoprintthetransposeofamatrix
1.importjava.util.*;
2.classTranspose
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Scannersc=newScanner(System.in);
7.intr,c;
8.System.out.print(“Enterhowmanyrows”);
9.r=sc.nextInt();
10.System.out.print(“Enterhowmanycols.”);
11.c=sc.nextInt();
12.
13.intm[][]=newint[r][c];
14.//input
15.for(inti=0;i<r;i++)
16.for(intj=0;j<c;j++)
17.{
18.System.out.print(“Enter”+“element”+(i+1)+“,”+(j+1));
19.m[i][j]=sc.nextInt();
20.}
21.//transpose
22.for(inti=0;i<c;i++)
23.{
24.for(intj=0;j<r;j++)
25.System.out.print(m[j][i]+”\t”);
26.System.out.println();
27.}
28.}
29.}
Example4.5Programtomultiplytwomatricesintoa3rdmatrix.
1.importjava.util.*;
2.classMatrixMult
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Scannersc=newScanner(System.in);
7.intr1,c1;
8.System.out.print(“Enterhowmanyrows”);
9.r1=sc.nextInt();
10.System.out.print(“Enterhowmanycols.”);
11.c1=sc.nextInt();
12.intr2,c2;
13.System.out.print(“Enterhowmanyrows”);
14.r2=sc.nextInt();
15.System.out.print(“Enterhowmanycols.”);
16.c2=sc.nextInt();
17.if(c1!=r2)
18.{
19.System.out.println(“Can’tmult”);
20.System.exit(1);
21.}
22.intm1[][]=newint[r1][c1];
23.//inputm1
24.for(inti=0;i<r1;i++)
25.for(intj=0;j<c1;j++)
26.{
27.System.out.print(“Enter”+“element”+(i+1)+“,”+(j+1));
28.m1[i][j]=sc.nextInt();
29.}
30.intm2[][]=newint[r2][c2];
31.//inputm2
32.for(inti=0;i<r2;i++)
33.for(intj=0;j<c2;j++)
34.{
35.System.out.print(“Enter”+“element”+(i+1)+“,”+(j+1));
36.m2[i][j]=sc.nextInt();
37.}
38.intm3[][]=newint[r1][c2];
39.//matrixmult
40.for(inti=0;i<r1;i++)
41.for(intj=0;j<c2;j++)
42.for(intk=0;k<c1;k++)
43.m3[i][j]+=m1[i][k]*m2[k][j];
44.//Outputm3
45.for(inti=0;i<r1;i++)
46.{
47.for(intj=0;j<c2;j++)
48.System.out.print(m3[i][j]+”\t”);
49.System.out.println();
50.}
51.}
52.}
3.VariablesizeArray:
Arraytreatmultidimensionalarrayas“arrayofarray”itispossibletodeclareatwo-d
arrayasfollows
intarr[][]=newint[4][];
arr[0]=newint[1];
arr[1]=newint[2];
arr[2]=newint[3];
arr[3]=newint[4];
Thismeanstotal4rowsofarrayanditscolumnsstartsfrom1andincreaseonebyone.so
theyarerepresentedinthememoryasthefollows:
(Memoryallocation)
Note1-Alltheelementsofarraywillbeautomaticallyinitializedtozerobuttoinitialize
the array with different values we can initialize the array in declaration itself. Array
declaration,memoryallocationandinitializationstepscanbecombinedintoone:-
inta[][]={{5,7,1},{1,7,9},{4,5,7},{1,1,1}};
Note2-Intheabovearraya.lengthwillshowthenumberofrowsi.e.4anda[0].lengthwill
shownumberofcolumnsin0throwi.e.3
CommandLineArguments-
Sometimeswewillwanttopassinformationintoaprogramwhenwerunit.This
is accomplished by passing command-line arguments to main(). A command line
argumentistheinformationthatdirectlyfollowstheprogram’snameonthecommandline
whenitisexecuted.
To access the command-line arguments inside a Java program we have to use
Stringarraypassedtomain().
TheJVMcallsthemain()methodandpassesthecommandlineargumenttoitas
anarrayofstring.Thelengthofthearray(i.ethenumberofthecommandlinearguments)
isobtainedusingattributelengthintheaboveexample.
Theforloopdisplaysthecommandlineargumentontheconsole/monitor.
Example4.6Programtoinputnamesfromcommandlinearguments.
1.classHello
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.for(inti=0;i<args.length;i++)
6.System.out.println(“Hello”+args[i]);
7.}
8.}
javacHello.java
javaHelloRaviAjayVijay
Output:HelloRavi
HelloAjay
HelloVijay
Example4.7Programtwoprintsumofnumbersinputthroughcommandline
arguments.
1.classSumCmd
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.intsum=0;
6.for(inti=0;i<args.length;i++)
7.sum+=Integer.parseInt(args[i]);
8.System.out.println(“Sumis”+sum);
9.}
10.}
javacSumCmd.java
javaSumCmd56
Output:
Sumis11
Example4.8Programtosortanarrayinputfromcommandline.
1.classSortCmd
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.intn=args.length;
6.inta[]=newint[n];
8.//copyargsarraytoaarray
9.for(inti=0;i<n;i++)
10.a[i]=Integer.parseInt(args[i]);
11.//sorting
12.for(inti=0;i<n-1;i++)
13.for(intj=i+1;j<n;j++)
14.if(a[i]>a[j])
15.{
16.intt=a[i];
17.a[i]=a[j];
18.a[j]=t;
19.}
20.//OutputArray
21.for(inti=0;i<n;i++)
22.System.out.print(a[i]+”\t”);
23.}
24.}
javacSortCmd.java
javaSortCmd54132
Output:12345
Multiplechoicequestions:
1.IfMyProg.javawerecompiledasanapplicationandthenrunfromthe
commandlineas:javaMyProgIliketests
whatwouldbethevalueofargs[1]insidethemain()method?
(a)MyProg
(b)“I”
(c)“like”
(d)3
(e)4
(f)nulluntilavalueisassigned
2. Afterthedeclaration:char[]c=newchar[100];
whatisthevalueofc[50]?
(a)50
(b)49
(c)‘\u0000’
(d)‘\u0020’
3. Whichofthefollowingarelegaldeclarationsofatwo-dimensionalarrayof
integers?
(a)int[5][5]a=newint[][];
(b)inta=newint[5,5];
(c)int[][]a=newint[5][5];
(d)int[][]a=new[5]int[5];
4. Whichofthefollowingarecorrectmethodsforinitializingthearray
“dayhigh”with7values?
(a)intdayhigh={24,23,24,25,25,23,21};
(b)intdayhigh[]={24,23,24,25,25,23,21};
(c)int[]dayhigh={24,23,24,25,25,23,21};
(d)intdayhigh[]=newint[24,23,24,25,25,23,21];
(e)intdayhigh=new[24,23,24,25,25,23,21];
5.Whichofthefollowingisacorrectstatement?
(a)AJavaarrayisanObject.
(b)MemoryallocationforarraysinJavaisalwaysdynamic.
(c)Javaarrayisinitializedbydefaultvaluesofthetypeofitselements.
(d)Alloftheabove.
Answer’s:1(c)2(e)3(c)4(b,c)5(d)
ProgrammingExercise:
1. Writeaprogramtosearchanelementinanarrayusinglinearsearch.
2. Writeaprogramtosearchanelementinanarrayusingbinarysearch.
CHAPTER
∞5∞
(ClassandObjects)
Introduction-
Definingaclass-
ClassrepresentsaADT(AbstractDataType).Itactslikeatemplateusingwhich
wecancreatemultipleobjects(instances).Aclassdeclarationonlycreatesatemplate,it
doesnotcreateanactualobject.Aclasscreatesanewdatatypethatcanbeusedtocreate
objects.Thatis,aclasscreatesalogicalframeworkthatdefinestherelationshipbetween
its members. When we declare an object of a class, we are creating an instance of that
class.Thusaclassisalogicalconstruct.Anobjecthasphysicalreality.(Thatis,anobject
occupiesspaceinmemory.)
modifiersclass<classname>
{
modifierstypevariables;
.
.
.
modifierstypemethodName1(parameter-list)
{
<bodyofthemethod>
}
.
.
}
DeclaringObjects-
Students1;
Intheaboveexamples1isnotanobject.InC++s1willbetreatedasobjectbut
inJavas1isonlyavariablewhichcanholdreferencetoanobjectoftypeStudent.This
variablewill holdgarbage ornull referenceuntilwe assignreference ofsome objectof
classStudent.
Itdoesnotyetpointtoanactualobject.Anyattempttousethisvariableatthis
pointwillresultinacompile-timeerror.ItisjustlikeapointertoanobjectinC/C++.If
thisvariableisdeclaredinsideanyblockoramethodthenitisalocalvariableandwill
notbeinitializedtonull,butifitisdeclaredinaclassthenitwillbeaninstancevariable
andwillautomaticallybeinitializedtonull.
AllocatingMemory-
InJavamemoryisallocateddynamicallywiththehelpofnewoperator.
s1=newStudent();
Intheaboveexamplenewoperatorwillallocatememoryfor anobjectofclass
Studentand returnits reference,whichisthenassignedtoreferencetypevariable s1.It
willalsocalladefaultconstructortoinitializemembervariables.
Theabovetwostatementscanbecombined:-
Students1=newStudent();
Note1-newallocatesmemoryfor anobjectduringruntime.Ifnewisunabletoallocate
memory(becausememoryisfinite.)thenitgeneratearuntimeexception/error.
Note2-Ifweassignareferencevariabletoanotherreferencevariablethenonlyreference
(address) will be transferred. There will not be any duplicate copy of the object. For
exampleifwecreateanotherreferencevariables2(Students2)andthen(s1=s2).This
willnotcreateduplicateobject,sameobjectisreferencedbys1ands2.
Any changes made in s2 will also be reflected in s1. No memory allocation is
donewiththisassign.Afterafewstepsifweassignnullins1thenthatobjectwillnotbe
destroyedasitsreferenceiswithobjects2.Butifboths1ands2areassignedwithanull
valuethenthatobjectwillbedestroyedbythegarbagecollectorandthememoryoccupied
bythatobjectwillbefreed.
Example5.1Classcontainingmembervariablesonly.
1.classA
2.{
3.intx;
4.inty;
5.}
6.classClassTest1
7.{
8.publicstaticvoidmain(Stringargs[])
9.{
10.Aa1,a2;//ReferenceVaraibles
11.a1=newA();//ObjectCreateion
12.a2=newA();
13.a1.x=10;
14.a1.y=20;
15.a2.x=5;
16.a2.y=6;
17.System.out.println(a1.x+“\t”+a1.y);
18.System.out.println(a2.x+“\t”+a2.y);
19.}
20.}
Output:
1020
56
Example5.2classcontainingmembervariables&membermethods.
1.classA
2.{
3.privateintx;
4.privateinty;
5.voidsetdata(intx1,inty1)
6.{
7.x=x1;
8.y=y1;
9.}
10.voiddisplay()
11.{
12.System.out.println(x+“\t”+y);
13.}
14.}
15.classClassTest2
16.{
17.publicstaticvoidmain(Stringargs[])
18.{
19.Aa1=newA();
20.Aa2=newA();
21.//a1.x=10;errorasxisprivate
22.a1.setdata(10,20);
23.a2.setdata(5,7);
24.a1.display();
25.a2.display();
26.}
27.}
Output:
1020
57
Note-Wecandeclaretheobjectofaclassoutsidetheclassaswellasinsidetheclass.
Example5.3Definingobjectsofaclassinitself.
1.classA
2.{
3.privateintx;
4.privateinty;
5.voidsetdata(intx1,inty1)
6.{
7.x=x1;
8.y=y1;
9.}
10.voiddisplay()
11.{
12.System.out.println(x+“\t”+y);
13.}
14.publicstaticvoidmain(Stringargs[])
15.{
16.Aa1=newA();
17.Aa2=newA();
18.a1.setdata(10,20);
19.a2.setdata(5,7);
20.a1.display();
21.a2.display();
22.}
23.}
Output:
1020
57
Modifiers/VisibilityLabelsformembersofaclass-
The visibility modifiers are applicable only on members of a class not on local
variables.
1. private-Ifwespecifythemodifierprivatewithamembervariableormethod
thenthatmemberwillnotbevisibleoutsidetheclassinwhichitisdeclared.
Thiswillhidethememberofaclassfromotherclasses.
2. public-Ifwespecifythemodifierpublicwithamembervariableormethod
then that member will be visible to all the classes. This member can be
accessedevenoutsidethepackage.main()methodisalwaysdefinedaspublic
becausethemain()methodisaccessedbytheJVMwhichisoutsidetheclass
inwhichmain()methodisdefined.
3. protected- A member declared as protected can be accessed from all the
classes belonging to the same package. Protected members can also be
accessedfromanysubclassofotherpackages.
4. default/nomodifier-Ifnovisibilitymodifierisspecifiedbeforeamember
declarationthenthatmembercanbeaccessedfromalltheclassesinthesame
package.Thatmembercannotbeaccessedoutsidethepackage.
VisibilityModifiersforaclassorinterface-
1. public-Ifaclassistobevisibletoalltheclassesirrespectiveoftheirpackage,
then it must be declared as public by specifying the modifier public, which
shouldappearbeforethekeywordclass.
2. default/nomodifier:-Intheabsenceofanyaccess/visibilitymodifierbefore
theclass,itsvisibilityisonlywithinthepackage(groupofclasses)inwhichit
isdefined.
thisKeyword:-
thisisareferencevariablewhichstoresthereferenceoftheobjectcurrentlyused
tocallthemethod.Thereferenceofthisisreplacedbythereferenceofthecallingobject
atrun-time.Sometimesamethodwillneedtorefertotheobjectthatinvokedit.Thiscan
bedonewiththehelpofthis.thiscanbeusedinsideanymethodtorefertothecurrent
object.
Note:localvariablehidestheinstancevariable,sowehavetousethiskeyword
explicitly.
InstanceVariableHiding-
As we know, it is illegal in Java to declare two local variables with the same
nameinsidethesameorenclosingscopes.Butwecanhavelocalvariables(parametersof
membermethods)havingsamenameasofinstancemembervariablesofclass.
When a local variable has the same name as an instance variable, the local
variables hides the instance variable. But this keyword allows us to refer to instance
variableseveniflocalvariablehidesit.
Example5.4useofthiskeyword
1.classA
2.{
3.privateintx;
4.privateinty;
5.voidsetdata(intx,inty)
6.{
7.this.x=x;//this.xistheclassmember&xislocalvariable
8.this.y=y;
9.}
10.voiddisplay()
11.{
12.System.out.println(x+“\t”+y);
13.}
14.}
15.classClassTest4
16.{
17.publicstaticvoidmain(Stringargs[])
18.{
19.Aa1=newA();
20.Aa2=newA();
21.a1.setdata(10,20);
22.a2.setdata(5,7);
23.a1.display();
24.a2.display();
25.}
26.}
Output:
1020
57
MethodOverloading:-
We canhavemore thanonemethodwiththesamename aslongas theydiffer
either in numbers of parameters or type of parameters or order of parameters. This is
calledmethodoverloading.
While calling an overloaded method it is possible that type of the actual
parameters passed may not match exactly with the formal parameters of any of the
overloadedmethods.Inthatcaseparameterarepromotedtonexthighertypetillamatch
is found. If no match is found even after promoting the parameters then a compilation
erroroccurs.
Example 5.5 In this example there are two setdata() methods having same name but
havingdifferentarguments,sothisismethodoverloading.
1.classA
2.{
3.privateintx,y;
4.voidsetdata(intx1)
5.{
6.x=y=x1;
7.}
8.voidsetdata(intx1,inty1)
9.{
10.x=x1;
11.y=y1;
12.}
13.voiddisplay()
14.{
15.System.out.println(x+“\t”+y);
16.}
17.}
18.classClassTest5
19.{
20.publicstaticvoidmain(Stringargs[])
21.{
22.Aa1=newA();
23.a1.setdata(5);
24.a1.display();
25.Aa2=newA();
26.a2.setdata(10,20);
27.a2.display();
28.}
29.}
Output:
55
1020
Constructors-
Itisverycommonrequirementtoinitializeanobjectimmediatelyaftercreation.
Wecandefineinstancemethodsforthispurposebuttheyhavetobeinvokedexplicitly.
Java has a solution for this requirement. Java allows objects to initialize
themselveswhentheyarecreatedusingconstructors.Ithasthesame
Thesyntaxoftheconstructorsisverysimilartothatofinstancemethods.They
havethesamenameastheclassanddonothaveanyreturntype.
Thisisbecause theimplicitreturn typeofclass’s constructoristhe classitself.
Constructorscanbeoverloadedjustlikemethods.
Whenoperatornewisusedtocreateaninstance/objectofaclass,JVMallocates
memoryfortheobject,theninitializestheinstancevariablestotheirdefaultinitialvalues,
andthencallstheappropriateconstructortoinitializetheinstancevariables.
Note-
The name constructor is a bit confusing. It appears as if the purpose of the
constructoristocreateanobject/instance.Theobjectiscreatedandinstancevariablesand
staticvariablesareinitializedtotheirdefaultinitialvaluesbeforeconstructoriscalled.
Sothepurposeoftheconstructoristoinitializetheinstancevariableswithvalues
otherthanthedefaultvalues.
Typeofconstructors-
DefaultConstructor:-Everyclasshasadefaultconstructor(ifno
explicitconstructorisdefined)thatdoesnottakeanyargumentanditsbody
does not have any statements. The compiler generates the default
constructorautomatically.
The compiler stops generating default constructor as soon as we add
our own constructor. When we do not create any constructor in the class
then JVM will create the default constructor and initialize the instance
variablewithdefaultvaluesnullorzero.
Example5.6useofdefaultcounstructor
1.classA
2.{
3.privateintx;
4.privateinty;
5.voiddisplay()
6.{
7.System.out.println(x+“\t”+y);
8.}
9.}
10.classClassTest6
11.{
12.publicstaticvoidmain(Stringargs[])
13.{
14.Aa1=newA();
15.a1.display();
16.}
17.}
Output:
00
Note:-Here we have not created any constructor then JVM create automatically default
constructoraftercreatingobjectandinitializetheinstancevariablesfrom0ornull.
DefaultZeroargumentconstructors-Wecanreplacethedefault
constructorwithourownzeroargumentconstructor.Thiswillallowusto
initializetheinstancevariablestoanyvalue.
ParameterizedConstructors:- A constructor which takes
parametersiscalledasparameterizedconstructors.
Note-Itispossibletooverloadtheconstructorjustlikemethods.Itiscalledasconstructor
overloading.
Example5.7useofconstructor.
1.classA
2.{
3.privateintx;
4.privateinty;
5.A()//Zeroargumentconstructor
6.{
7.x=y=0;
8.}
9.A(intx1)//Parameterizedoneargumentconstructor
10.{
11.x=y=x1;
12.}
13.A(intx1,inty1)//Parameterizedtwoargumentconstructor
14.{
15.x=x1;
16.y=y1;
17.}
18.voiddisplay()
19.{
20.System.out.println(x+“\t”+y);
21.}
22.}
23.classClassTest7
24.{
25.publicstaticvoidmain(Stringargs[])
26.{
27.Aa1=newA();
28.a1.display();
29.Aa2=newA(5);
30.a2.display();
31.Aa3=newA(4,7);
32.a3.display();
33.}
34.}
Output:00
55
47
Example5.8:
1.importjava.util.Scanner;
2.classComplex
3.{
4.privateintreal,imag;
5.Complex()//zeroarg.constructor
6.{
7.real=imag=0;
8.}
9.Complex(intreal,intimag)
10.{
11.this.real=real;
12.this.imag=imag;
13.}
14.voidgetdata()
15.{
16.Scannersc=newScanner(System.in);
17.System.out.print(“Enterreal”);
18.real=sc.nextInt();
19.System.out.print(“Enterimag”);
20.imag=sc.nextInt();
21.}
22.voiddisplay()
23.{
24.if(imag>=0)
25.System.out.println(real+”+”+imag+“i”);
26.else
27.System.out.println(real+””+imag+“i”);
28.}
29.Complexsum(Complexc)
30.{
31.Complext=newComplex();
32.t.real=real+c.real;
33.t.imag=imag+c.imag;
34.returnt;
35.//or
36.//returnnewComplex(real+c.real,imag+c.imag);
37.}
38.Complexmult(Complexc)
39.{
40.Complext=newComplex();
41.t.real=real*c.real-imag*c.imag;
42.t.imag=real*c.imag+imag*c.real;
43.returnt;
44.}
45.publicstaticvoidmain(Stringargs[])
46.{
47.Complexc1=newComplex();
48.Complexc2=newComplex();
49.Complexc3=null,c4=null;
50.
51.c1.getdata();
52.c2.getdata();
53.c3=c1.sum(c2);
54.System.out.print(“Sumis“);
55.c3.display();
56.c4=c1.mult(c2);
57.System.out.print(“Productis“);
58.c4.display();
59.}}
finalize()Method-
Sometimes an object will need to perform some action when it is destroyed. For
example,ifan objectisholding somenon-Javaresourcesuchasa filehandler,thenwe
mightwanttomakesuretheseresourcesarefreedbeforeanobjectisdestroyed.
To handle such situations, Java provides a mechanism called finalization. By using
finalizationwecandefinespecificactionsthatwilloccurwhenanobjectisjustaboutto
be reclaimed by the garbage collector. finalize () is only called just prior to garbage
collection. It is not called when an object goes out of scope. In C++ the concept of
destructorfunctionisusedforfinalizationbutitisnotexactlysameasfinalize()inJava.
protectedvoidfinalize()
{
//finalizationcodehere.
}
Note-Insteadofprotectedmodifierwecanalsousepublic.
TypeofVariables-
Javahasthreekindsofvariables:
1.Instancevariables-
Variabledeclaredinaclassasamemberoutsideallmembermethodsareknownas
instance variable. There will be as many copies of that variable as there are number of
objects.
There is no need to initialize instance variable in Java because these variables are
initialized as soon as the object is created and the memory is allocated with the new
operator.
The variables are initialized according to their types. All the numeric variables are
initialized automatically with 0, Boolean variable with false, and reference variables
(objects)withnullvalue.
Wecanaccessthesevariablesbyusingobjectnameandthedot(.)operator.(Object
referencevariable.instancevariablename).Wecannotuse operatortoseparateobject
referencevariableandtheinstancevariableasinC/C++.
2.LocalVariables:-
VariablesdeclaredinsideamethodisknownasLocalvariable.Itisnotsameas
instancevariable.ThereisnoautomaticinitializationfortheLocalvariable.
3.StaticVariables:-
Staticvariablesarealsodeclaredoutsidemethods/blockslikeinstancevariables.
But the static variables make use of the modifier static before the data type. Static
variablesareglobaltoaclassandallofitsinstances(objects).
Theyareusefulforkeepingtrackofglobalstates.Forexample,astaticvariable
count in a class can store the number of instances/objects of the class created in the
programatanyinstanceoftime.
The objects can communicate using static variables just like C functions
communicatethroughglobalvariables.Forstaticvariablesthereisonlyonecopyofthe
variable irrespective of number of instances/objects created in the program, which is
sharedacrossalltheinstances.
Thedot(.)operatorisusedtoaccesstheclassvariablesalso,butwecanaccess
the static variable using class name as well as object name. If we declare to different
objectsthebothwillpointtosamecopythestaticvariable.
Staticvariableisinitializedautomaticallywiththeirdefaultvalues(zero,falseor
null)assoonastheclassisloaded/used.
Theycanonlycallotherstaticmethods.Theymustonlyaccessstaticdata.They
cannotrefertothisorsuperinanyway.(Thekeywordsuperrelatestoinheritanceandis
describedlater.)
Example5.9
1.classA
2.{
3.intx;//instancevariable
4.staticinty;//staticorclassvariable
5.}
6.classClassTest8
7.{
8.publicstaticvoidmain(Stringargs[])
9.{
10.Aa1=newA();
11.Aa2=newA();
12.Aa3=newA();
13.a1.x=10;
14.a1.y=20;
15.a2.x=11;
16.a2.y=21;
17.a3.x=12;
18.a3.y=22;
19.System.out.println(a1.x+“\t”+a1.y);
20.System.out.println(a2.x+“\t”+a2.y);
21.System.out.println(a2.x+“\t”+a3.y);
22.}
23.}
Output:
1022
1122
1222
TypeofMethods:-
1.Instancemethods.
2.Staticmethods.
Instancemethods:-
ThesearesameasC++functions.Instancemethodscanbeinvokedonlythrough
object.Ifwecallainstancemethodinsideastaticmethodofsameclassthenalsowehave
touseobjectname.
StaticMethods:-
Staticmethodscanbeinvokedusingobjectaswellasclassname.Staticmethods
canaccessonlystaticmembers.Staticmethodscanbecalleddirectly(withoutobjector
classname)fromastaticmethodofsameclass.
Example5.10
1.classA
2.{
3.intx;
4.staticinty;
5.staticintsum(inta,intb)
6.{
7.//y=5;noerrorstaticmethodcanaccessstaticvariable
8.//x=10;errorstaticmethodcan’taccessinstancevariable
9.//Aa1=newA();
10.//a1.x=10;Noerrorasstaticmethodcanaccessinstancevariable
11.//throughobjects.
12.//this.x=10;errorasstaticmethodcan’taccessthisorsuperkeyword
13.intc;
14.c=a+b;
15.return(c);
16.}
17.staticfloatavg(inta,intb)
18.{
19.return(float)(a+b)/2;
20.}
21.}
22.classClassTest9
23.{
24.publicstaticvoidmain(Stringargs[])
25.{
26.System.out.println(A.sum(5,6));//staticmethodscanbecalledthrough
27.//classname
28.System.out.println(A.avg(5,6));
29.Aa1=newA();
30.System.out.println(a1.sum(5,6));//staticmethodscanalsobecalled
31.//throughobjects
32.}
33.}
Output:
11
5.5
11
Initialize&staticBlock-Initializeblockisusedtoinitializeinstancemembervariables
ofthe class&staticblockis usedto initializestaticmember variablesoftheclass.But
constructoriscalledaftertheseblocks.
Example5.11:
1.classA
2.{
3.intx;
4.staticinty;
5.
6.{//Inititalizeblocktoinitializeinstancevariables
7.x=10;
8.}
9.
10.static//staticblocktoinitializestaticvariables
11.{
12.y=5;
13.}
14.}
15.classClassTest10
16.{
17.publicstaticvoidmain(Stringargs[])
18.{
19.Aa1=newA();
20.System.out.println(a1.x+“\t”+a1.y);
21.}
22.}
Output:
105
FinalVariables-
Ifavariableisdeclaredasfinalthenwecannotchangeitsvaluefinal(double
PI=3.141;)finalvariabledonotoccupymemoryonaperinstancebasis.Afinalvariable
isaconstantvariableitsvaluecannotbechange.Afinalvariablereferencetypecannot
changeitsreference.
Example5.12
1.classA
2.{
3.voidm1()
4.{
5.System.out.println(“Insidem1()”);
6.}
7.}
8.classClassTest11
9.{
10.publicstaticvoidmain(Stringargs[])
11.{
12.finalintx=10;//cannotchange
13.finalinty;//Variableynotinitializedsowecaninitializeylater
14.y=20;//Nowyisinitializesoafterthiswecan’tchangeitsvalue
15.//y=30;Error
16.System.out.println(x);
17.System.out.println(y);
18.finalAa1=newA();//a1isaconstantreferencesowecannot
19.//assignreferenceofanyotherobjectinf1.
20.a1.m1();
21.Aa2=newA();
22.//a1=a2;error
23.}
24.}
Output:10
20
Insidem1()
ArgumentPassingMechanism-
1. CallbyValue.
2. Callbyreference.
Whenaprimitivetype(int,float,longetc.)ispassedtoamethod,itisdoneby
use of call-by-value approach. In case of objects what is actually passed is an object
reference.
An object reference is also passed by using call-by-value approach. However,
sincethevaluebeingpassedreferstoanobject,thecopyofthatvaluewillstillrefertothe
sameobjectthatitscorrespondingargumentdoes.
For example if we pass a reference variable a1 which stores a reference of an
objectintoafunctionandinfunctiona2istheformalparameterthena1anda2bothpoints
tothesameobject.
Anychangesinthevalueoftheobjectthrougha2willalsobereflectedina1.But
ifweassignanewreferenceina2thenthatreferencewillnotbeautomaticallycopiedin
a1.
Example5.13
1.classBox
2.{
3.privateintfeet;
4.privateintinches;
5.Box()
6.{
7.feet=inches=0;
8.}
9.Box(intfeet,intinches)
10.{
11.this.feet=feet;
12.this.inches=inches;
13.}
14.voiddisplay()
15.{
16.System.out.println(“Feetis”+feet+”\n”+“Inchesis”+inches);
17.}
18.voidswap(Boxobj)
19.{
20.intt;
21.t=feet;
22.feet=obj.feet;
23.obj.feet=t;
24.
25.t=inches;
26.inches=obj.inches;
27.obj.inches=t;
28.}
29.}
30.classClassTest12
31.{
32.publicstaticvoidmain(Stringargs[])
33.{
34.Boxb1=newBox(5,6);
35.Boxb2=newBox(7,4);
36.b1.swap(b2);//Objectispassedbyreference.
37.b1.display();
38.b2.display();
39.}
40.}
Output:
Feetis7
Inchesis4
Feetis5
Inchesis6
NestedandInnerClasses-
Itispossibletodefineaclasswithinanotherclass;suchclassesareknownasnested
classes.Thescopeofanestedclassisboundedbythescopeofitsenclosingclass.
Anestedclasshasaccesstothemembers,includingprivatemembersoftheclassin
whichitisnested.Howevertheenclosingclassdoesnothaveaccesstothemembersof
thenestedclass.
Therearetwotypesofnestedclassesstaticandnonstatic.Astaticnestedclassisone
whichhasthestaticmodifierapplied.Becauseitisstatic,itmustaccessthemembersof
itsenclosingclassthroughanobject.Thatis,itcannotrefertomembersofitsenclosing
classdirectly.Becauseofthisrestriction,staticnestedclassesareseldomused.
Anon-staticnested classhas access toall ofthe variablesandmethods ofits outer
classandmayrefertothemdirectlyinthesamewaythatothernon-staticmembersofthe
outerclassdo.
Example5.14
1.classOuter
2.{
3.classInner
4.{
5.intmember_inner=7;
6.Inner()
7.{
8.member_outer=5;
9.System.out.println(member_outer);
10.}
11.}
12.privateintmember_outer;
13.Outer()
14.{
15.//member_inner=9;error
16.Innerobj=newInner();
17.System.out.println(obj.member_inner);
18.}
19.}
20.classClassTest13
21.{
22.publicstaticvoidmain(Stringargs[])
23.{
24.Outerout_obj=newOuter();
25.}
26.}
Output:
5
7
Example5.15:
1.classOuter
2.{
3.staticclassInner
4.{
5.intmember_inner=7;
6.Inner()
7.{
8.//member_outer=5;error
9.//System.out.println(member_outer);error
10.Outerobj=newOuter();
11.obj.member_outer=5;
12.System.out.println(obj.member_outer);
14.}
15.}
16.privateintmember_outer;
17.voidprn()
18.{
19.Innerobj=newInner();
20.System.out.println(obj.member_inner);
21.}
22.}
23.classClassTest14
24.{
25.publicstaticvoidmain(Stringargs[])
26.{
27.Outerout_obj=newOuter();
28.out_obj.prn();
29.}
30.}
Output:
5
7
ClassRandom
Example5.16:
1.importjava.util.Random;
2.classRandomTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Randomr1=newRandom();
7.for(inti=1;i<=10;i++)
8.System.out.println(Math.abs(r1.nextInt()));
9.}
10.}
TheoryQuestions:
1.Ifwewantamembervariabletonotbeaccessibleoutsidethecurrent
classatall,whatkeywordshouldprecedethenameofthevariablewhendeclaring
it?
2.InJava,howareobjects/valuespassedaround.
3.Considerthecodebelow:
publicstaticvoidmain(Stringargs[])
{
inta=5;
System.out.println(cube(a));
}
intcube(inttheNum)
{
returntheNum*theNum*theNum;
}
Explaintheimportanceof“static”keyword
Whatwillhappenwhenweattempttocompileandrunthiscode?
a)Itwillnotcompilebecausecubeisalreadydefinedinthejava.lang.Math
class.
b)Itwillnotcompilebecausecubeisnotstatic.
c)Itwillcompile,butthrowanarithmeticexception.
d)Itwillrunperfectlyandprint“125”tostandardoutput.
4.Whatdoesastaticinnerclassmean?Howisitdifferentfromanyother
staticmember
5.Howdowedeclareconstantvaluesinjava
6.Whatisthemeaningof“final”keyword?
7.Whatistheclassvariables?
Answer:
When we create a number of objects of the same class, then each object will
shareacommoncopyofvariables.Thatmeansthatthereisonlyonecopyper
class,nomatterhowmanyobjectsarecreatedfromit.Classvariablesorstatic
variablesaredeclaredwiththestatickeywordinaclass.
Thesevariablesarestoredinstaticmemory.Classvariablesaremostly
used for constants, variable that never change its initial value. Static variables
arealwayscalledbytheclassname.
Thisvariableiscreatedwhentheprogramstartsi.e.itiscreatedbefore
theinstanceiscreatedofclassbyusingnewoperatorandgetsdestroyedwhen
theprogramsstops.Thescopeoftheclassvariableissameasinstancevariable.
The class variable can be defined anywhere at class level with the
keyword static. It initial value is same as instance variable. When the class
variableisdefinedasintthenit’sinitialvalueisbydefaultzero,whendeclared
booleanitsdefaultvalueisfalseandnullforobjectreferences.Classvariables
areassociatedwiththeclass,ratherthanwithanyobject.
8.Explaingarbagecollection.
Answer: Garbage collection is one of the most important feature of Java.
Garbage collection is also called automatic memory management as JVM
automatically removes the unused variables/objects (value is null) from the
memory.Userprogramcann’tdirectlyfreetheobjectfrommemory,insteaditis
the job of the garbage collector to automatically free the objects that are no
longerreferencedbyaprogram.
Every class inherits finalize() method from java.lang.Object, the
finalize() method is called by garbage collector when it determines no more
referencestotheobjectexists.
InJava,itisgoodideatoexplicitlyassignnullintoavariablewhenno
more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to
recycle the unused objects, but there is no guarantee when all the objects will
garbagecollected.
9.Canwecalloneconstructorfromanotherifaclasshasmultiple
constructors?
Yes.Usethis()tocallaconstructorfromanotherconstructor.
10.What’sthedifferencebetweenconstructorsandnormalmethods?
Constructorsmusthavethesamenameastheclassandcannotreturnavalue.They
areonlycalledoncewhileregularmethodscouldbecalledmanytimesanditcan
returnavalueorcanbevoid.
11.Howwecanforcethegarbagecollection?
Garbagecollectionautomaticprocessandcan’tbeforced.Wecouldrequestitby
callingSystem.gc().JVMdoesnotguaranteethatGCwillbestartedimmediately.
12.Whichofthefollowingisnotacorrectstatement.
(a)LocalvariableinJavaarealwaysinitializedbydefaultvalues.
(b)LocalvariablesinJavamustbeinitializedbeforeuse.
(c)Localvariablesinaninnerblockcannothavethesamename
asalocalvariableinouterblock.
(d)Localvariablesintwoblocksasthesamelevelcanhavesame
name.
CHAPTER
∞6∞
(Inheritance)
Introduction-
Whenthepropertiesoftheoneclassistransferredintoanotherclassthenit’ssaid
tobean inheritance.Inthisway theinheritedclassis calledtobeasuperclassor base
class or parent class and inheriting class is called to be a child class sub class derived
class.
Inheritance allows us to extend an existing class (Base class) by adding the
additional features. It encourages the code reusability, which help in reducing the code
sizealthoughitmayleadtocomplexityinsomecases.
Asanexampleifwehavecompletedthecodeofthesimplecalculator.Afteritweneedto
developthescientificcalculatorthenwehavetwoalternatives:
(i)Makeanewclass.(Rewritingtheclass)
(ii)Extendingtheclass.
Inthemostcasessecondalternativewillbeabetterchoice.Inthiscasewehave
towritethesmallpieceofcode.Atthesametimewewon’thavetospendmuchtimein
debuggingandtestingasthebaseclassisalreadytestedandisinuseforalongperiodof
time. When we have to inherit one class into another class then we have to use the
“extends”keyword.
Syntax:classsub_classextendsbase_class
ClassA(superclassorbaseclassorparentclass).
ClassB(childclassorderivedclassorsubclass).
The sub class will have all the features of base class in addition to the new features
defined in the extended class. Java does not support the multiple-inheritance but its
supportmultipleinterfaceinheritancesosubclasscanextendsonlyonebaseclass.
Example6.1:
1.classA
2.{
3.intx;
4.voidsetX(intx1)
5.{
6.x=x1;
7.}
8.voiddisplayX()
9.{
10.System.out.println(x);
11.}
12.}
13.classBextendsA
14.{
15.inty;
16.voidsetY(inty1)
17.{
18.y=y1;
19.}
20.voiddisplayY()
21.{
22.System.out.println(y);
23.}
24.}
25.classInheritTest1
26.{
27.publicstaticvoidmain(Stringargs[])
28.{
29.Aa1=newA();//4bytes
30.a1.setX(5);
31.a1.displayX();
32.Bb1=newB();//8bytes
33.b1.setX(10);
34.b1.setY(20);
35.b1.displayX();
36.b1.displayY();
37.}
38.}
Output:
5
10
20
MemberHiding:-
If a sub-class member has the same name (and same signature in case of
methods)asthatofasuper-classmemberthenithidesthesuper-classmember.
Althoughboththemembersmightbeavailableinthesub-classbutusingmember
namewecanonlyaccesssub-classmemberasithidesthememberofthesamenamein
thesuper-class.
Usingkeywordsuper
Wheneverasubclassneedstorefertoitsimmediatesuperclass,itcandosoby
useofkeywordsuper.superhastwogeneraluses:
1. Callingsuperclass’sconstructor
Asubclasscancallaconstructormethoddefinedbyitssuperclassbyuseofthe
followingformofsuper.super(parameter-list);
Here, parameter-list specifies any parameters needed by the constructor in the
super class. In fact super() must always be the first statement executed inside a
subclass’sconstructor.
2. Accessingamemberofthesuperclassthathasbeenhiddenbyamemberofa
subclass.
The keyword super can be used to access the hidden members of the super as
follows:
super.member;
Here,membercanbeeitheramethodoradatamember.
MethodOverloadingandMethodOverriding:-
MethodOverloading:-
Whentwoormoremethodshavingsamenamebutdifferentparametersthenitis
saidtobeamethodsoverloading.Methodoverloadingisusedwhenobjectarerequiredto
performsimilartaskbutusingdifferentinputparameters.
When we call a method, java matches up the method name first and then the
numberandtypeofparameters.Todecidewhichoneofthemethoddefinitionistocalled
isknownaspolymorphism.
MethodOverriding:-
We have seen that a method in a super class is inherited by its subclass and is
usedbytheobjectcreatedby thesubclass.Methodinheritanceenablesus todefineand
use method repeatedly in subclass without having to define the method again in
subclass.
Intheclasshierarchy,whenaninstancemethodinasubclasshasthesamename
signature as an instance method (non private) in its super class, then the method in the
subclassissaidtooverridethemethodinthesuperclass.
Whenanoverriddenmethodiscalledfromwithinasubclass,itwillalwaysrefer
totheversionofthatmethoddefinedbythesubclass.Theversionofthemethoddefined
bythesuperclasswillbehidden.
Example6.2
1.classA
2.{
3.intx;
4.voidset(intx1)
5.{
6.x=x1;
7.}
8.voiddisplay()
9.{
10.System.out.println(x);
11.}
12.}
13.classBextendsA
14.{
15.inty;
16.voidset(intx1,inty1)//setmethodofclassBisnotoverridingset
17.//methodofclassAasargumentsaredifferent
18.{
19.set(x1);//Thiswillcallset()ofclassA
20.y=y1;
21.}
22.voiddisplay()//displaymethodofclassBisoverridingdisplay
23.//methodofclassA
24.{
25.//display();ThiswillcalldisplayofclassB
26.super.display();//ThiswillcalldisplayofclassA
27.System.out.println(y);
28.}
29.}
30.classInheritTest2
31.{
32.publicstaticvoidmain(Stringargs[])
33.{
34.Bb1=newB();
35.b1.set(10,20);
36.b1.display();
37.}
38.}
Output:
10
20
Javasupportthefollowinginheritance:
[1]Singleinheritance.
[2]Multilevelinheritance.
[3]HierarchicalInheritance.
[1]Singleinheritance.
Example6.3:
1.classA
2.{
3.privateintx;
4.A()
5.{
6.x=0;
7.}
8.A(intx1)
9.{
10.x=x1;
11.}
12.voiddisplay()
13.{
14.System.out.print(x);
15.}
16.}
17.classBextendsA
18.{
19.privateinty;
20.B()
21.{
22.super();
23.//x=0;errorasxisprivate
24.y=0;
25.}
26.B(intx1,inty1)
27.{
28.super(x1);
29.//x=x1;errorasxisprivate
30.y=y1;
31.}
32.voiddisplay()
33.{
34.super.display();
35.System.out.print(y);
36.}
37.}
38.classInheritTest3
39.{
40.publicstaticvoidmain(Stringargs[])
41.{
42.Bb1=newB();
43.b1.display();
44.Bb2=newB(10,20);
45.b2.display();
46.}
47.}
Output:
001020
[2]Multilevelinheritance.
Example6.4
1.classA
2.{
3.privateintx;
4.A()
5.{
6.x=0;
7.}
8.A(intx1)
9.{
10.x=x1;
11.}
12.voiddisplay()
13.{
14.System.out.println(x);
15.}
16.}
17.classBextendsA
18.{
19.privateinty;
20.B()
21.{
22.super();
23.y=0;
24.}
25.B(intx1,inty1)
26.{
27.super(x1);
28.y=y1;
29.}
30.voiddisplay()
31.{
32.super.display();
33.System.out.println(y);
34.}
35.}
36.classCextendsB
37.{
38.privateintz;
39.C()
40.{
41.super();
42.z=0;
43.}
44.C(intx1,inty1,intz1)
45.{
46.super(x1,y1);
47.z=z1;
48.}
49.voiddisplay()
50.{
51.super.display();
52.System.out.println(z);
53.}
54.}
55.classInheritTest4
56.{
57.publicstaticvoidmain(Stringargs[])
58.{
59.Cc1=newC();
60.c1.display();
61.Cc2=newC(10,20,30);
62.c2.display();
63.}
64.}
Output:
0
0
0
10
20
30
[3]Hierarchicalinheritance.
OrderofConstructorcalling:-
When a class hierarchy is created, in what order are the constructors for the
classes that make up the hierarchy called? The answer is that in a class hierarchy,
constructorsarecalledintheorderofderivation,fromsuperclasstosubclass.
Further, since super() must be the first statement executed in a subclass’s
constructor;thisorderisthesamewhetherornotsuper()isused.Ifsuper()isnotused,
thenthedefaultorparameterlessconstructorofeachsuperclassbeexecuted.
Constructors are executed in order of derivation. Because a super class has no
knowledgeofanysubclass,anyinitializationitneedstoperformisseparateandpossibly
pre-requisite to any initialization performed by the sub class. Therefore it must be
executedfirst.
Thekeywordsuperisusedsubjecttothefollowingconditions.
super()constructormayonlybecalledwithinasubclassconstructormethod.
Thecalltosuperclassconstructormustappearasthefirststatementwithin
thesubclassconstructor.
The parameter in the super call must match the order and type of the
argumentsofthesuperclassconstructor.
DynamicMethodBinding-
(DynamicMethodDispatchorRunTimeBinding):-
Methodoverridingformsthebasisforoneofjava’spowerfulconceptDynamic
method dispatch is the mechanism by which call to an overridden instance method is
resolved at run time, rather than compile time. Dynamic method dispatch is important
becausethisishowjavaimplementsruntimepolymorphism.
Asuperclassreferencevariablecanrefertoasubclassobjects.Javausesthisfact
toresolvecallstooverriddenmethodatruntime.When anoverriddenmethodiscalled
throughasuperclassreference,javadetermineswhichversionofthatmethodtoexecute
baseduponthetypeoftheobjectbeingreferredtoatthetimethecalloccurs.
Thusthisdeterminationismadeatruntime,whendifferenttypesofobjectsare
referredtodifferentversionofanoverriddenmethodwillbecalled.Inotherwords,itis
thetypeoftheobjectbeingreferredto(notthetypeofreference)thatdetermineswhich
versionofanoverriddenmethodwillbeexecuted.
Overridden methods allow Java to support run-time polymorphism.
Polymorphism is essential for OOP for one reason. It allows a general class to specify
methodsthatwillbecommontoallofitsderivatives,whileallowingsup-classestodefine
thespecificimplementationofsomeorallofthesemethods.
Bycombininginheritancewithoverriddenmethods,asuperclasscandefinethe
generalformofmethodthatwillbeusedbyallofitssub-classes.Theabilityofexisting
code libraries to call methods on instances of new classes without recompiling while
maintainingacleanabstractinterfaceisaprofoundlypowerfultool.
Baseclassreferencecantakethesubclassreferencebutsubclassreferencecannottake
thebaseclassreference.
Example6.5
1.classShape
2.{
3.voidgetdata()
4.{
5.System.out.println(“getdata()ofShape”);
6.}
7.voidarea()
8.{
9.System.out.println(“area()ofShape”);
10.}
11.voiddisplay()
12.{
13.System.out.println(“display()ofShape”);
14.}
15.}
16.classCircleextendsShape
17.{
18.voidgetdata()
19.{
20.System.out.println(“getdata()ofCircle”);
21.}
22.voidarea()
23.{
24.System.out.println(“area()ofCircle”);
25.}
26.voiddisplay()
27.{
28.System.out.println(“display()ofCircle”);
29.}
30.}
31.classRectangleextendsShape
32.{
33.voidgetdata()
34.{
35.System.out.println(“getdata()ofRectangle”);
36.}
37.voidarea()
38.{
39.System.out.println(“area()ofRectangle”);
40.}
41.voiddisplay()
42.{
43.System.out.println(“display()ofRectangle”);
44.}
45.}
46.classInheritTest5
47.{
48.publicstaticvoidmain(Stringargs[])
49.{
50.//superreferencevariablecanacceptsubclassobject
51.//Dynamicbinding
52.Shapes[]={newCircle(),newRectangle()};
53.for(inti=0;i<s.length;i++)
54.{
55.s[i].getdata();
56.s[i].area();
57.s[i].display();
58.}
59.}
60.}
Output:
getdata()ofCircle
area()ofCircle
display()ofCircle
getdata()ofRectangle
area()ofRectangle
display()ofRectangle
AbstractClass&AbstractMethod:
We have seen that by making a method final we ensure that the method is not
redefined in a subclass. Java allows us to do something that is exactly opposite to this.
Thatiswecanindicatethatamethodmustalwaysberedefinedinasubclass,thusmaking
overridingcompulsory.Thisisdoneusingthemodifierkeywordabstractinthemethod
definition.
Therearesituationsinwhichwewillwanttodefineasuperclassthatdeclares
thestructureofagivenabstractionwithoutprovidingacompleteimplementationofevery
method.
That is, sometimes we will want to create a super class that only defines a
generalizedformthatwillbesharedbyallofitssubclasses,leavingittoeachsubclassto
fillinthedetails.
Such a class determines the nature of the methods that the sub classes must
implement.Onewaythissituationcan occuriswhenasuper classisunabletocreatea
meaningfulimplementationforamethod.
Todeclareanabstractmethod,usethisgeneralform:
abstractreturn_typename(parameter-list);
Nobody is present. Any class that contains one or more abstract methods must also be
declaredabstract.Todeclareaclassabstract,wesimplyusetheabstractkeywordinfront
oftheclasskeywordatthebeginningofthedeclaration.
Therecanbenoobjectofanabstractclass.Thatis,anabstractclasscannotbe
directly instantiated with the new operator. Such objects would be useless, because an
abstractclassisnotfullydefined.
Also we cannot declare abstract constructors or abstract static methods. Any
subclass of an abstract class must either implement all of the abstract methods in super
class,orbeitselfdeclaredabstract.
Example6.6:
1.abstractclassShape
2.{
3.abstractvoidgetdata();
4.abstractvoidarea();
5.abstractvoiddisplay();
6.}
7.classCircleextendsShape
8.{
9.voidgetdata()
10.{
11.System.out.println(“getdata()ofCircle”);
12.}
13.voidarea()
14.{
15.System.out.println(“area()ofCircle”);
16.}
17.voiddisplay()
18.{
19.System.out.println(“display()ofCircle”);
20.}
21.}
22.classRectangleextendsShape
23.{
24.voidgetdata()
25.{
26.System.out.println(“getdata()ofRectangle”);
27.}
28.voidarea()
29.{
30.System.out.println(“area()ofRectangle”);
31.}
32.voiddisplay()
33.{
34.System.out.println(“display()ofRectangle”);
35.}
36.}
37.classInheritTest6
38.{
39.publicstaticvoidmain(Stringargs[])
40.{
41.//superreferencevariablecanacceptsubclassobject
42.//Dynamicbinding
43.Shapes[]={newCircle(),newRectangle()};
44.for(inti=0;i<s.length;i++)
45.{
46.s[i].getdata();
47.s[i].area();
48.s[i].display();
49.}
50.}
51.}
Output:
getdata()ofCircle
area()ofCircle
display()ofCircle
getdata()ofRectangle
area()ofRectangle
display()ofRectangle
Finalmethod:-
Ifwedon’twantamethodtobeoverriddenbyaderivedclassmethodthenwe
candefinethebaseclassmethodasfinal.Anyattempttooverridethatmethodwillcausea
compiletimeerror.
classA
{
finalvoidmethod1()
{
–—
}
}
classBextendsA
{
voidmethod1()//error
{
–—
}
}
Finalclass:-
Sometimeswemayliketopreventaclassbeingfurthersub-classedforsecurity
reason.Aclassthatcannotbesubclassediscalledafinalclass.Thisisachieved
injavausingthekeywordfinalasfollows:
finalclassA1
{
------
------
}
classBextendsA//error
{
-------
-------
}
AnyattempttoinheritclassAwillcauseanerrorandthecompilerwillnotallow
it.Declaringaclassfinalpreventsanyunwantedextensiontotheclass.
It also allows the compiler to perform some optimization when a method of a
finalclassisinvoked.
TheoryQuestions:
1. Whatisinheritance?
2. Howmanytypesinheritanceareavailableinjava.
3. Whatisdifferencebetweendefaultconstructorandparameterizedconstructor?
4. Whatisdifferencebetweenfinalclassandfinalmethod?
5. Whatissuperclass?
6. Whatisanabstractclass?
7. Whatisdifferencebetweencompiletimeandruntimebinding?
8. Whatisdifferencebetweenmethodoverloadingandmethodoverriding?
CHAPTER
∞7∞
(Objectorientedprogramming)
Introduction-
Objectorientedprogrammingv/sproceduralprogramming:-
Alltheprogramsconsistoftwoelements:process(logic)anddata.Therecanbe
twodifferentapproachesdependinguponwhetherourmainfocusisonprocessingordata.
Theproceduralprogramminglanguages(c,FORTRAN,PASCAL,COBOLetc.)focuson
theprocessingparti.e.theygivemoreimportanceto“whatishappening”(process)inthe
systemandlessimportanceto“whoisbeingaffected”(data).
The procedural approach becomes less and less suitable as the programs
become large and complex. The object-oriented programming languages were
developed to overcome the limitations of the procedural programming languages. The
object-orientedprogramminglanguagesarerelativelyfarlesscomplexascomparedtothe
similarprogramswithintheprocedurallanguages.
Theobject-orientedprograms areorganizedaroundthe data(i.e. objects)anda
setofwelldefinedinterfaces(publicmethods)tothatdata.
Java is based on object oriented paradigm. Java is almost pure object oriented
programming language. We have termed “almost” as Java also supports primitive data
typesduetoperformancereasons.
TheC++isnotapureobjectorientedlanguage.C++isanextensiontoCsoit
uses an approach, which is a mix of procedure-oriented approach and object-oriented
approach.
Thebasicdifferencesinthetwoapproachesaresummarizedbelow:
(i)The object-oriented programs are data centric while the
programswrittenintheprocedurallanguagesareprocesscentric.
(ii)The object-oriented programs are organized around data
(objects)sotheymodeltherealworldobjectsinabetterway.
(iii)Thedegreeofreusabilityandextensibilityofthecodeisvery
high in case of object-oriented approach as compared to procedural
approach.Socodesizeisless.
(iv)Theobject-orientedprogramsareeasiertomaintain,asthey
arerelativelylesscomplexandsmallerinsize.
(v)Theobject-orientedprogramsarebasedonthebottom-up
design methodology while the procedural programs are based on the
top-downdesignmethodology.
BasicconceptsofOOP(Object-OrientedProgramming):-
Some of the essential elements of the object oriented programming are mentioned
below:
Abstraction
Objectsandclasses
ThreeOOPPrinciples
Encapsulation
Inheritance
Polymorphism
Persistence
Genericity
Composition/Aggregation
1.Abstraction:-
The abstraction is one of the essential elements of any programming language
including the procedural languages. The concept of built-in data type is also an
abstraction. The feature of defining own data type using struct in C language further
extendsthisabstraction.
Thebasic purposeof abstractionisto reducecomplexity byhiding details.For
example, a building is not thought to be a collection of building material but a well
definedobjecthavinguniquefeaturesandproperties.
Abstractioncanbedefinedasanactforidentifyingtheessentialpropertiesand
behaviorofanobjectwithoutgoingintodetails.Thepropertiesandbehaviorsofanobject
differentiateitfromotherobjectsofsimilartypeandalsohelpinclassifying/groupingthe
objects.
Theobjectorientedprogramminglanguagesmodelabstractionusingclassesand
objects.
2.ObjectandClasses:-
Object:-An object is a physical or abstract entity or thing, which can be
distinguishedfromotherobjectsofsimilartypes.Anobjecthasthreecharacteristics:
(i)Identification.
(ii)Properties.(Attributes)
(iii)Behaviors.(Methods/Operations/Functions)
Theobjectcanalsobethoughtofasaninstanceofclass,whereclassislikeabuilt-indata
typeandtheobjectisthevariable.
Class:-Aclassrepresentsacategoryofobjectsbyabstractingtheirpropertiesand
behaviors.Aclasscanbethoughtofasablueprintforcreatingobjects.Anobjecthasthe
propertiesandbehaviorsdefinedbyitsclass.Theclasscanbethoughtofasauser-defined
datatypeandobjectasavariable/instanceofthedatatyperepresentedbytheclass.
The properties/attributes of an object are defined by data members / fields in
Java. A data member/field in a class is a variable that can hold data. The behaviors /
operations of an object are defined using methods in Java. Both data members and
methodsarereferredtoasmembersoftheclass.
A class may also be thought of as a user-defined data type and an object as a
variableofthatdatatype.Onceaclasshasdefinedwecancreateanynumberofobjects
belongingtothatclass.
3.ThreeOOPPrinciples:-
Encapsulation:-Encapsulationisthemechanismthatbindscodeanddataon
whichthecodeacts.Javaclassessupportthisastheyallowustodefinethecodeanddata
together.Encapsulationalsohelpsinachievingdatahidingbydeclaringsomeoftheclass
membersasprivatesothattheycannotbeaccessedfromthecodethatdoesnotbelongto
theclass.
Inheritance:-In object-oriented programming, Inheritance refers to the
propertiesofaclassbeingavailabletootherclassescalledsub-classesorderivedclasses.
Asub-classorderivedclassisonethatisderivedfromanexistingclass.Itinheritsallthe
features of the existing class which is also referred as the base-class or super-class. So
inheritancecanbedefinedastheprocessofderivingaclassfromasuper-classorabase-
class.Inheritingaclassdoesnotintroduceanychangesinthebase-class/super-class.The
derived-class/sub-class has a larger set of properties and behaviors as compared to the
base-class.
Themajoradvantageoftheinheritanceiscodereusability.Ifthebaseclassisin
useforalongtimeandthereisaneedtoaddsomeextraattributesandmethods,wecan
dosobyderivinganotherclass.Thederivedclasswillbeabletousecodeofthebaseclass
withoutdebuggingasitisinuseforalongtime.
ClassHierarchy:-Alltheclassesderivedfromacommonbaseclassbelongtoa
family and form a class hierarchy. The class hierarchy can be compared with a tree
structurewhereonebaseclassisattherootanddoesnothaveasuper-class.
Allotherclassesareeitherderivedfromtheclassattherootofthehierarchyor
from some other class, which is derived from the root class directly or indirectly. More
features are added as we go down the tree. The classes that are represented by the leaf
nodesdonothaveanysub-classes.Thefollowingexampleshowssomeclasshierarchies.
Polymorphism:-
Polymorphismisafeaturethatallowssameinterfacetobeusedforageneralclassof
actions. Most of the object-oriented languages use polymorphism in the following
situations.
OperatorOverloading.
MethodOverloading.
MethodOverriding.
OperatorOverloading:-
Mostofthelanguagesusethisformofpolymorphismforthebuilt-inoperations.
Forexample,allthearithmeticoperatorsinC/C++orJavacanbeusedwithmanytypesof
operands(int,long,float,doubleetc.).Sosameadditionoperatorscanbeusedtoaddtwo
integersaswellastoaddtwofloatingpointnumbers.
TheC++allowstheusertooverloadthebuiltinoperators.Forexample,wecan
overload the arithmetic operators to handle the complex numbers also. Although Java
uses operator overloading for built-in operators but does not allow the user to
overloadtheoperators.
MethodOverloading:-
Thisfeatureallowsustowritemorethanonemethodswiththesamename.Both
C++ and Java have this feature. The methods (function in C++) with same name are
differentiatedbasedontheparameters(arguments).Theoverloadedmethodsmusteither
have different number of parameters or the types of the parameters must differ if their
numberissame.
If the call to an overloaded method can be resolved at compile time i.e. if the
compiler can decide which of the overloaded method will be called then this is called
staticbinding,whichisanexampleofcompiletimepolymorphism.
Ifthecalltoanoverloadedmethodcannotberesolvedatcompiletimei.e.ifthe
compilercannotdecidewhichoftheoverloadedmethodwillbecalledthenthisiscalled
dynamicbinding,whichisanexampleofrun-timepolymorphism.
In general Java resolves calls to overloaded methods at run-time but there are
manysituationswherethecallstooverloadedmethodsareresolvedatcompile-time.
MethodOverriding:-
Thesub-classcandefineamethodwiththesamenameasinthesuperclass,and
thesamenumberandtypeofparameters.Thisiscalledmethodoverriding.
The compiler can not resolve calls to overridden methods. Java normally uses
dynamicbindingtoresolvecallstooverriddenmethodsi.e.thedecisiontakesplaceatrun-
time.
4.Persistence:-
Someobject-orientedlanguagesallowwetostore/retrievethestateofaprogram
to / from a persistence storage media i.e. a permanent storage media like secondary
storage.Thisiscalledpersistence.
Javaallowsustostoreanyobjectonthesecondarystorageandtoretrieveitlater
on.Ifweattempttostoreanobjectatthetopofanobjectgraph,alloftheotherreferenced
objectsarerecursivelylocatedandsaved.Similarlywhentheobjectisretrievedlateron,
alloftheobjectsandtheirreferencesi.e.theentireobjectgraphiscorrectlycreatedinthe
mainmemory.
Forexample,itispossibletosaveanentiretreestructurebyjustsavingtheroot
ofthetree.Atalaterstageitispossibletorecreatetheentiretreestructureinthememory
byjustsavingtherootofthetree.TheC++doesnotsupportthisfeature.
5.Genericity:-
Theconceptofdefininganalgorithmonce,independentlyofanyspecifictypeof
data, and then applying that algorithm to a wide variety of data types without any
additionaleffortiscalledGenericity.C++supportsthisfeatureusingtemplates.Javaalso
supports this feature through Object class, which is at the top of any class hierarchy in
Java.
Forexample,usingthisfeature,wecanimplementagenericdatatypestackso
thatispossibletostoreelementofanytypeinthestack.Thisfeatureincreasesthedegree
ofreusabilitytoalargeextent.
6.Composition/Aggregation
Anobjectmightbemadeupofotherobjects.SuchanobjectiscalledComposite
orAggregateobject.Forexample,itisappropriateifanobjectofclassvehicleisdefined
asacompositeobjectmadeupofobjectslikeEngine,Body,Axle,Seatsetc.
Inheritancev/sComposition:-
Therearetwobasicmechanismsforderivingnewclassesfromtheexistingones:
Inheritance and composition. The class Bus can be derived by inheriting properties of
class vehicle. Here Bus is a kind of vehicle which has some additional properties /
behaviorsbesidethepropertiesandbehaviorswhicharecommonforallthevehicles.
InotherwordsclassBushasis-arelationshipwiththeclassvehicleaswecansay
thatBusisavehicle.
The class vehicle itself might be derived from many other classes using
composition. For example, an object of class vehicle might be composed of objects
belonging to classes like Engine, Gear Box, Seats, Driver’s Seat Body, and Steering
Wheeletc.
The derived class in this case has whole-part relationship with the classes
representing parts of the composite object. We can not say that vehicle is an Engine or
VehicleisaGearBoxasVehicleismadeupofanumberofparts.
SuperclassesandSubclasses
Oftenanobject ofoneclass “isan”objectofanotherclassaswell.A
rectanglecertainlyisaquadrilateral(asaresquares,parallelogramsandtrapezoids).Thus,
class Rectangle can be said to inherit from class Quadrilateral. In this context, class
Quadrilateralisasuperclass,andclassRectangleisasubclass.
Arectangleisaspecifictypeofquadrilateral,butitisincorrecttoclaim
that a quadrilateral is a rectangle (the quadrilateral could be a parallelogram). Figure
shows several simple inheritance examples of superclasses and potential
subclasses.Inheritance normally produces subclasses with more features than their
superclasses,sothetermssuperclassandsubclasscanbeconfusing.
Thereisanotherway,however,toviewthesetermsthatmakesperfectly
good sense. Because every subclass object “is an” object of its superclass, and because
onesuperclasscanhavemanysubclasses,thesetofobjectsrepresentedbyasuperclassis
normallylargerthanthesetofobjectsrepresentedbyanyofthatsuperclass’ssubclasses.
Forexample,thesuperclass Vehiclerepresentsina genericmannerall
vehicles,suchascars,trucks,boats,bicyclesandsoon.However,subclassCarrepresents
onlyasmallsubsetofalltheVehiclesintheworld.Inheritancerelationshipsformtree-like
hierarchicalstructures.
Asuperclass existsinahierarchicalrelationshipwithitssubclasses.A
class can certainly exist by itself, but it is when a class is used with the mechanism of
inheritance that the class becomes either a superclass that supplies attributes and
behaviours to other classes or a subclass that inherits those attributes and behaviours.
Frequently,oneclassisbothasubclassandasuperclass.
Superclass
Subclasses
Student Graduatestudent
UnderGraduate
student
Shape Circle
Triangle
Rectangle
Loan CarLoan
HomeLoan
EducationLoan
Employee FacultyMember
StaffMember
Account CheckingAccount
SavingAccount
CHAPTER
∞8∞
(PACKAGES)
Introduction-
Whenweworkonaprojectwehavetobreakourprograminseveralclasses.To
organizeourclassesweusePackages.Thepackageisbothanamingandvisibilitycontrol
mechanism.Packageisacollectionofclassesandinterfaceswhichareinterrelated.With
thehelpofpackageitispossibletogivesamenamestomorethanoneclassprovidedthey
aredefinedindifferentpackage.
Asinglepackagecan’tcontaintwoclasseswithsamename.
PROGRAMS are organized as sets of packages. Each package has its own set of sub-
packages,whichhelpstopreventnameconflicts.Atoplevelpackageisaccessibleoutside
the package only if it is declared as public. The naming structure for packages is
hierarchical.Themembersofapackageareclassandinterfacetypesandsub-packages.A
package in java is an encapsulation mechanism that can be used to group related class,
interfaceandsub-packages.
For small programs, a package can be unnamed or have a simple name, but if
codeistobewidelydistributed,uniquepackagenamesshouldbechosen.
This can prevent the conflicts that would otherwise occur if two development
groupshappenedtopickthesamepackagenameandthesepackageswerelatertobeused
inasingleprogram.Ifwedonotspecifyapackageforajavaclassthenthatclasswillbe
thepartofthedefaultpackageofJavacalledasunnamedpackage.Butthisrequiresthat
everyclassmusthaveauniquenametoavoidcollision.
Exampleoftheunnamedpackage.
classA
{
-------
-------
}
classA_demo
{
publicstaticvoidmain(Stringargs[])
{
------
------
}
}
Howtodefineapackage
Tocreateapackage,includeapackagecommandasthefirststatementinaJava
sourcefile.Anyclassdeclaredwithinthatfilewillbelongtothespecifiedpackage.The
package statement defines a name space in which classes are stored. If we omit the
packagestatement,theclassnamesareputintothedefaultpackage,whichhasnoname
andiscalledasun-namedpackage.
Thepackagestatementhasthefollowingsyntax:
packagepackage_name;
Java uses file system directories to store packages. Remember that the case is
significant,anddirectorynamemustmatchthepackagenameexactly.Morethatonefile
canincludethesamepackagestatement.
Syntex:
packagep1;//packagedeclaration
classA//classdeclaration
{
-------//bodyofclassA
-------
}
packageisakeyword.p1isthepackagenameinwhichclassAistobestored.
Example8.1:
1.packagep1;
2.classA
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.System.out.println(“FirstPackageprogram.”);
7.}
8.}
Wehaveassumedthatthecurrentfolderis(c:\javaprg\p1>)
C:\javaprg\p1>javacA.java
C:\javaprg\p1>javap1.A
Output:
FirstPackageProgram
Note:-If we compile the above program with –d “javac –d . A.java” in “c:\javaprg>”
thenthefolderp1willbecreatedautomaticallyandthe.classfileoftheaboveprogram
willbesavedinthisfolder.Butifwedonotcompilewith–doptionthenitisourdutyto
createthep1folderandplacethe.classfileinthatfolder.(.)directsthecompilertocreate
thep1folderinthecurrentfolder.Wecanalsotypethecompletepathifwewanttocreate
thefolderinsomeotherfolderasjavac–dc:\javaprgA.java
Importingpackages:
All the inbuilt classes of Java are stored in some named packages; no class is
stored in the unnamed default package. Since classes within packages must be fully
qualifiedwiththeirpackagenameornames.Itcouldbecometedioustotypeinthelong
dot separated package path name for every class we want to use. For this reason, java
includestheimportstatementtobringcertainclasses,orentirepackages,intovisibility.
Onceimported,aclasscanbereferredtodirectly,usingonlyitsname.
Theimportstatementisaconveniencetotheprogrammerandisnottechnically
neededtowriteacompletejavaprogram.Ifwearegoingtorefertoafewdozenclassesin
ourapplication,thentheimportstatementwillsavealotoftyping.
Inajavasourcefile,importstatementoccursimmediatelyfollowingthepackage
statement (if it exists) and before any class definition. This is the general form of the
importstatement.
importpkg1[.pkg2].classname;
importpkg1[.pkg2].*;
Example8.2
1//Programtoprintany10randomnumbersusingclassRandomofpackage
2.//java.utilwithoutusingimportstatement
3.classRandomTest1
4.{
5.publicstaticvoidmain(Stringargs[])
6.{
7.java.util.Randomr1=newjava.util.Random();
8.for(inti=1;i<=10;i++)
9.{
10.System.out.println(Math.abs(r1.nextInt()));
11.}
12.}
13.}
Output:
1588659525
481996564
210875677
386971039
360473512
1922641171
393055462
889442536
1836112189
320882863
Example8.3
1.//Programtoprintany10randomnumbersusingclassRandomofpackage
2.//java.utilusingimportstatement
3.importjava.util.Random;
4.classRandomTest2
5.{
6.publicstaticvoidmain(Stringargs[])
7.{
8.Randomr1=newRandom();
9.for(inti=1;i<=10;i++)
10.{
11.System.out.println(Math.abs(r1.nextInt()));
12.}
13.}
14.}
Output:
686722541
1154462827
452959606
1235134497
1421490552
1065881855
424893046
731473166
1217844570
437181304
CLASSPATH:
Ifweruntheaboveprogramfromanyotherfolderotherthanthecurrentfolder
thenitwillnotrun.BydefaulttheJavarun-timesystemusesthecurrentworkingdirectory
asitsstartingpoint.
Thusif ourpackage isin thecurrent directory,or asubdirectoryofthe current
directory,itwillbefound.Buttoruntheaboveprogramfromanyotherfolderwehaveto
set the class path using command SET CLASSPATH=.;C:\JAVAPRG on command
prompt. CLASSPATH is a environment variable. We have to type this command every
time when we start the computer for the first time. But if we put this command in
MyComputer properties advanced Environment variables then there is no
needtotypethiscommandagain&again.
WecanalsoruntheprogramwithoutsettingtheCLASSPATHenvironmentvariable.To
dothistype
java–classpathc:\javaprgp1.A
Note4:-We can create a hierarchy of packages. To do so, simply separate each package
namefromtheoneaboveitbyuseofadot.Thegeneralformofamulti-leveledpackage
statementis:
packagepackage_name1[.package_name2][.package_name3];
ApackagehierarchymustbereflectedinthefilesystemofJavadevelopmentsystem.For
examplepackagejava.awt.Imageneedtobestoredinjava\awt\image(WINDOWS)or
java/awt/image(UNIX)orjava:swt:image(MACINTOSH)filesystem.
Apackagehierarchyrepresentsanorganizationofthejavaclassesandinterfaces.
Itdoesnotrepresentthesourcecodeorganizationoftheclassesandinterfaces.
Each java source file (also called compilation unit) can contain zero or more
definition of classes and interfaces, but the compiler produces a separate class file
containingthejavabyte-codeforeachofthem.Aclassorinterfacecanindicatethatits
java-bytecodebeplacedinaparticularpackage,usingapackagedeclaration.
Thepackagejavahassub-packagesawt,applet,io,lang,net,andutil,butno
classesorinterface.
Thepackagejava.awthasasub-packagenamedimage,aswellasanumber
ofclassesandinterfaces.
Becausethepackagejava.awthasasub-packageimage,itcannotcontaina
declarationofaclassorinterfacetypenamedimage.
IfthefullyqualifiednameofapackageisP,andQisasub-packageofP,
thenP.Qisthefullyqualifiednameofthesub-package.
If there is a package named mouse and a member class Button in that
package(whichthenmightbereferredtoasmouse.Button),thentherecannotbe
anypackagewiththefullyqualifiednamemouse.Buttonormouse.Button.Click.
Atmostonepackagestatementcanappearinasourcefile,anditmustbethe
firststatementintheJavasourcefile.
Visibilityofclassmember:
Class and package are both means of encapsulating and containing the name
spaceandscopeofvariableandmethods.Packagesactascontainersforclassesandother
subordinatepackages.Classactasacontainerfordataandmethodcode.
Theclassisjava’ssmallestunitofabstraction.Becauseoftheinterplaybetween
theclassesandpackages,Javaaddressesfivecategoriesofvisibilityofclassmembers.
1.Visibilitywithintheclass.
2.Visibilityinsubclassinthesamepackages.
3.Visibilityinnonsubclassinthesamepackages.
4.Visibilityinsubclassesindifferentpackages.
5.Visibilityinsubclassesthatareneitherinthesamepackagenoraresubclass.
Note1:-
Toplevelclassandinterfacehasonlytwopossibleaccessdefaultandpublic.
Note2:-Ifclassisdeclaredpublicthenitisaccessiblebyusingothercode.
Note3:-Ifclasshasdefaultaccessthenitcanonlybeaccessedbyothercodewithinthe
samepackage.
Note4:-The member visibility has meaning only if the class is visible. If visibility
modifieroftheclassisdefaultthenevenpublicmembersoftheclasswillbevisibleonly
withinthepackage.
Accessspecifiers:
JARfiles:(JavaArchiveFiles)
Tocompressafileweusesomeprogramsuchaswinzipinthesamewayjava’s
JAR feature can also be used to compress the entire hierarchy of a Java package. It
providesabetterfacilityforinstallation.
Thereisnoneedtocreatethefilestructureatthecustomerlocation.Wehaveto
justuseJARfileand thisfilewillrestoretheentirefilestructure.Allthepackage,sub-
packageandclassfileswillbecreatedautomaticallyfromtheJARfile.
JAR technology makes it much easier to deliver and install software. Also the
elementinaJARfilearecompressed,whichmakedownloadingaJARfilemuchfaster
thanseparatelydownloadingseveraluncompressedfile.Thisallowsaconsumertobesure
thattheseelementswereproducedbyaspecificorganizationorindividual.
TherearefollowingoptionareavailablefortheJARfiles:
Option Description
c Anewarchiveistobecreated.
C Changedirectoriesduringcommandexecution.
f Firstelementofthefilelististhenameofthearchivethatistobecreated.
i Indexinformationshouldbeprovided
m Thesecondelementinthefilelististhenameoftheexternalmanifestfile.
M Manifestfilenotcreated
t Thearchivecontentsshouldbetabulated
u UpdateexistingJARfile.
v Verboseoutputshouldbeprovidedbytheutilityasitexecute.
x Filesaretobeextractedfromthearchive
o Donotusecompression
CreatingaJARfile:
c:\javaprg>jar-cfMyjar.jarpack1
ThiswillcreateaJARfile“Myjar.jar”whichwillcontainallthefilesofpackagepack1in
compressedform
ExtractJARfiles:
Thiscommandusedfortheextractthejarfiles.(suchasunzip)
c:\javaprg>jar–xfMyjar.jar
TabulatingtheContentsofajarfile:
ThefollowingcommandslistthecontentsofMyjar1.jar.
c:\javaprg>jar–tfMyjar.jar
UpdatinganexistingJARfile:
Thefollowingcommandisusefulfortheupdateofthejarfile.
c:\javaprg>jar–ufMyjar.jarpack1
CreatinganexecutableJARfile:
c:\javaprg>jar–cmfmainClassMyjar.jarpack1
wheremainClassisatextfilewhichcontains“Main-Class:pack1.pack2.pack3.A”saved
injavaprgfolder.
Executeajarfile:
c:\javaprg>java–jarMyjar.jar
Theoryquestion’s:
1.Whatdoweunderstandaboutthepackages?
2.Explainallthemodifiersanditsscopeindifferentpackagesandsub
packageswithsubclassandotherclass.
3.WhatistheuseofJARfiles?
4.Whatistheuseoftheimportstatement?
SearchThisbookonAmazon.comwithISBN-978-1500730413.
CHAPTER
∞9∞
(Interface)
Introduction-
An interface is basically kind of class. Like classes, interface contain methods
and variables but with a major difference. The difference is that interface defined only
abstract methods and final variables (Constants). This means that interface do not write
anycodetoimplementsthesemethodsanddatafieldscontainonlyconstants.
Therefore,itistheresponsibilityoftheclasstoimplementaninterfacedefining
the code for implementation of these methods. Interfaces are syntactically similar to
classes,buttheylackinstancevariables,andtheirmethodsaredeclaredwithoutabody.In
practice,thismeansthatwecandefineinterfaces,whichdonotmakeassumptionsabout
howtheyareimplemented.Thepurposeoftheinterfaceistoseparateaclass’sinterface
from its implementation. Interface just defines what a class must do without saying
anythingabouttheimplementation.Interfacesdefineonlymethodsignaturesandtheydo
nothaveanyinstancevariables.
Anestedinterfaceisanyinterfacewhosedeclarationoccurswithinthebodyof
another class or interface. A top-level interface is an interface that is not a nested
interface.Thesyntaxfordefininganinterfaceisverysimilartothatfordefiningaclass.
Thegeneralformofaninterfacedefinitionis:
interfaceinterface_name
{
variabledeclarations;
methodsdeclarations;
}
Here, interface is the keyword and interface_name is any valid java identifier (just like
classname).
Note:Whenwedefineaninterfacethenbydefaultitispublicandabstract.
InterfaceModifiers:
Theonlymodifierthatcanbeusedwiththetop-levelinterfacesareabstractand
public.Evenifwedonotuseabstractmodifier,theinterfaceisimplicitlydeclaredtobe
abstractsouseofmodifierabstractisnotrequired.Thevisibilityofatop-levelinterface
canbeeitherpackageorpublicjustliketop-levelclass.Ifnovisibilitymodifierisused
thenthevisibilityoftheinterfaceisassumedtobepackage.
DataVariableMemberDeclarations:
Onlyconstantscanbe definedintheinterface.Allthevariablesinaninterface
are implicitly public, final and static meaning they cannot be changed by the
implementingclass.Theymustalsobeinitializedwithconstantvalue.
publicstaticfinaltypevariable_name=value;
Thevariable declaredin an interfaceis public,static andfinal. It meansit isa
staticvariablewithpublicaccess.Thevariableisalsodeclaredfinal,whichmeansthatit
mustbeassignedavalueatthetimeofdeclaration,whichcannotbemodifiedlateron.
ThekeywordfinalislikeconstinC/C++.
MethodsDeclarations:
Methods declaration will contain only a list of methods without anybody
statements. They end with a semicolon after the parameter list. They are essentially,
abstract methods and there can be no default implementation of any method specified
withinaninterface.
All methods in the interface are always public and abstract modifiers by default. We
cannotdeclarestaticmethodsininterfaces.
publicabstractreturn_typemethod_name(parameter_list);
Hereisanexampleofaninterfacedefinitionthatcontainstwovariablesandonemethods.
interfaceitem
{
staticfinalintcode=1001;
staticfinalStringname=“Matrix”;
abstractvoiddisplay();
}
Note:-Code for the methods is not included in the interface and methods declaration
simplyendswithasemicolon.
Anotherexampleofaninterface:
interfacearea
{
floatpi=3.142f;
floatcompute(floatx,floaty);
voidshow();
}
Extendinginterface:
Likeclasses,interfacecanalsobeextendedi.e.aninterfacecanbesub-interfaced
fromotherinterface.Thenewinterfacewillinheritallthemembersofthesubinterfacein
the manner similar to subclass. This is achieved using the keyword extends as shown
below.
interfaceinterface_1
{
intcode=1001;
Stringname=“Matrix”;
}
interfaceinterface_2extendsinterface_1
{
voiddisplay();
}
Theinterface_2wouldinheritboththeconstantcodeandnameintoit.
Note:-
That the variables name and codes are declared like a simple variable. It is
allowedherebutallthevariablesintheinterfacearetreatedasconstant,public&static
althoughthekeywordspublic,staticandfinalarenothere.
Wecancombineseveralinterfacestogetherintoasingleinterface.Followingdeclarations
arevalid.
interfaceinterface_1
{
intcode=1001;
Stringname=“Matrix”;
}
interfaceinterface_2
{
voiddisplay();
}
interfaceinterface_3extendsinterface_1,interface_2
{
-------
-------
}
Note:-
Alwaysrememberthataninterfacecannotextendclasses.Thiswouldviolatethe
rulethataninterfacecanhaveonlyabstractmethodsandconstants.
ImplementingInterface:
Interfacesareusedas“super-classes”whosepropertiesareinheritedbyclasses.It
isthereforenecessarytocreateaclassthatinheritsthegiveninterface.Onceinterfacehas
beendefined,oneormoreclassescanimplementthatinterface.
To implement an interface, include the implements clause in a class definition,
andthencreatethemethodsdeclaredbytheinterface.
Theimplementingclassmustprovidebodyofallthemethodsinalltheinterfaces
otherwiseitmustbedeclaredasabstract.
The implementing class may also extend a class and can implement multiple
interfaces.
modifierclass<class-name>implements<interface-name>
{
bodyoftheclass
}
Syntaxofaninterfaceimplementsintheclass
interfaceinterface_name
{
-------
}
classclass_nameimplementsinterface_name
{
Bodyofclass
}
Javadoesnotsupportmultipleinheritancebutitsupportmultipleinterfaceinheritance
i.e.aclasscanimplementmorethanoneinterfacesasshowbelow:
modifiers class <class-name> implements <interface-1>,<interface-2>,
<interface-3>,….<interface-n>
{
bodyofclass
}
Note:-
When we implement an interface method, it must be declared as public. The
implementinganinterfacemethodislikeover-ridingsowecannotdecreasethevisibility.
Example9.1
1.interfaceinterface_1
2.{
3.voidshow(intx);
4.}
5.classclass_1implementsinterface_1
6.{
7.publicvoidshow(intx);
8.{
9.--------
10.}
11.}
Example9.2ofabstractclass
1.interfacecommon
2.{
3.voidpush(intx);
4.intpop();
5.}
6.abstractclassstackimplementscommon
7.{
8.voiddisp()
9.{
10.--------
11.}
12.}
Here the class stack does not implements the push() and pop() methods. So we must
declare stack class as a abstract class this technique is called to be a partial
implementation.
Variousformofinterfaceinheritance:-
(a)
(singlelevelinterfaceinheritance)
(b)
(multilevelinterfaceinheritance)
(c)
(hierarchicalinterfaceinheritance)
(d)
(hybridinterfaceinheritance)
AccessingImplementingClassObjectsThroughInterfaceReference:
Wecandeclarevariablesasobjectreferencesthatuseaninterfaceratherthana
class type. Any instance of any class that implements the declared interface can be
referredtobysuchavariable.Whenwecallamethodthroughoneofthesereference,the
correctversionwillbecalledbaseontheactualinstanceoftheinterfacebeingreferredto.
Thisisoneoftheimportantfeatureofinterfaces.Themethodtobeexecutedis
lookedupdynamicallyatruntime,allowingclassestobecreatelaterthanthecode,which
callsmethodsonthem.Thecallingcodecandispatchthroughaninterfacewithouthaving
to know anything about the “callee”. This process is similar to using a super class
referencetoaccessasubclassobject.
Becausedynamiclookup ofa methodatrun timeincursasignificantoverhead
whencomparedwiththenormalmethodinvocationinJava,weshouldbecarefulnotto
useinterfacecasuallyinperformance-criticalcode.
Example9.3
1.interfaceMath_function
2.{
3.voiddisplay(intx);
4.}
5.classSqrtimplementsMath_function
6.{
7.publicvoiddisplay(intx)
8.{
9.System.out.println(“sqrtofx=”+Math.sqrt(x));
10.}
11.}
12.classLogimplementsMath_function
13.{
14.publicvoiddisplay(intx)
15.{
16.System.out.println(“logofx=“+Math.log(x));
17.}
18.}
19.classMath_Demo
20.{
21.publicstaticvoidmain(Stringargs[])
22.{
23.Math_functionf1=newSqrt();
24.Math_functionf2=newLog();
25.f1.display(27);
26.f2.display(3);
27.Math_functionf3;
28.f3=f1;//polymorphism(assignthereference)
29.f3.display(30);
30.f3=f2;//polymorphism(assignthereference)
31.f3.display(5);
32.}
33.}
Output:
CharacteristicsofInterface:
Interfaceisakeyword.
Interfacecanbedeclaredasabstractbutitisabstractdefaultsothereisno
needtoaddabstractkeyword.
Allvariablesarealwayspublicstatic&final.
Allmethodsofinterfacemustbeimplementedintheclass.
Allmethodsimplementedbytheimplementingclassmustbepublic.
Interfaceincludesdeclarationofthemethodsonly.
Interfacemethodscannotbedeclaredasstatic.Theyarealwaysdeclaredas
aninstancemethods.
A class can neither narrow the accessibility of an interface method nor
specifynewexceptionsinmethod’sthrowsclause;asattemptingtodosowould
amount to altering the interfaces contract, which is illegal. The criteria for
overridingmethodsalsoapplywhenimplementinginterfacemethods.
Allmethodsneedtobedefinedaspublicintheimplementingclass.
Partialimplementsareallowedhereusingbyabstractkeywords.
Regardlessofhowmanyinterfacesaclassimplementsdirectlyorindirectly,
itonlyprovidesasingleimplementationsofamethodthatmighthavemultiple
declarationsintheinterfaces.
Method prototype declarations can also be overloaded as in the case of
classes.
Aninterfaceconstantcan beaccessedbyanyclient(aclassorinterface)
using its fully qualified name, regardless of whether the client extends or
implements its interface. However, if a client is a class that implements this
interfaceoraninterfacethatextendsthisinterface,thentheclientcanalsoaccess
such constants directly without using the fully qualified name. Such a client
inheritstheinterfaceconstants.
Inthecaseofmultipleinheritanceofinterfaceconstantsanynameconflicts
canberesolvedusingfullyqualifiednamesfortheconstantsinvolved.
InterfaceVariables:
Allvariablesintheinterfacearealwayspublicstaticandfinalbecausetheyare
commonpartfortheaccessofthedatatypesandmethodsfortheimplementing.
MemoryManagementoftheInterfaceVariable:
Staticvariablesalways getthememory whenourprogramisto beloadedthey
taketheseparatememoryanddonotsharewiththeanyobject’smemory.Theyarealso
calledasconstantvariables.Theycanbeaccesseddirectlyusinginterfacenameandthe
{.}dot.
Example9.4
1.interfaceStatic_Var
2.{
3.intsun=1;
4.intmon=2;
5.inttues=3;
6.intwed=4;
7.intthurs=5;
8.intfri=6;
9.intsat=7;
10.}
11.classWeek_DayimplementsStatic_Var
12.{
13.publicstaticvoidmain(Stringargs[])
14.{
15.System.out.println(sun);
16.System.out.println(mon);
17.System.out.println(tues);
18.System.out.println(wed);
19.System.out.println(thurs);
20.System.out.println(fri);
21.System.out.println(sat);
22.}
23.}
or
11.classWeek_Day
12.{
13.publicstaticvoidmain(Stringargs[])
14.{
15.System.out.println(Static_Var.sun);
16.System.out.println(Static_Var.mon);
17.System.out.println(Static_Var.tues);
18.System.out.println(Static_Var.wed);
19.System.out.println(Static_Var.thurs);
20.System.out.println(Static_Var.fri);
21.System.out.println(Static_Var.sat);
22.}
23.}
Output:1
2
3
4
5
6
7
Example9.5
1.interfaceTwo_Methods
2.{
3.voidm1();
4.voidm2();
5.}
6.classThree_MethodsimplementsTwo_methods
7.{
8.publicvoidm1()
9.{
10.bodyofthem1;
11.}
12.publicvoidm2()
13.{
14.bodyofthem2;
15.}
16.publicvoidm3()
17.{
18.bodyofthem3;
19.}
20.}
21.classMethods_Demo
22.{
23.publicstaticvoidmain(Stringargs[])
24.{
25.Two_methodstm1=newThree_methods();
26.tm1.m1();
27.tm1.m2();
28.//tm1.m3();error
29.Three_Methodstm2=newThree_Methods();
30.tm3.m3();
31.}
32.}
Note:- Here we can not call the m3() using interface reference because this
methodsisnotdeclaredintheinterface.Sointerfacereferencecanaccessthosemethods
which are declared in the self block. Otherwise we can call the same classes objects or
extendedclassesobjects.
Example9.6oftwointerfacesimplementedintheoneclass
1.interfaceTwo_Methods
2.{
3.voidm1();
4.voidm2();
5.}
6.interfaceOne_MethodextendsTwo_Methods
7.{
8.voidm3();
9.}
10.classThree_MethodsimplementsOne_methods,
11.{
12.publicvoidm1()
13.{
14.bodyofthem1;
15.}
16.publicvoidm2()
17.{
18.bodyofthem2;
19.}
20.publicvoidm3()
21.{
22.bodyofthem3;
23.}
24.}
25.classMethods_Demo
26.{
27.publicstaticvoidmain(Stringargs[])
28.{
29.Three_methodstm1=newThree_methods();
30.tm1.m1();
31.tm1.m2();
32.tm1.m3();
33.}
34.}
Non Interface Methods: When any class implements the methods of the interface and
alsodefinesadditionalmethodsintheclasswhicharenotdeclaredintheinterface,then
we can say that the additional methods are non interface methods. Using reference
variableofinterfacewecan’tcalltheseadditionalmethods.
Example9.7
1.interfaceTwo_Methods
2.{
3.voidpush(intx);
4.intpop();
5.}
6.classStackimplementsTwo_Methods
7.{
8.intarr[]=newint[5];
9.inttop=-1;
10.publicvoidpush(intitem)
11.{
12.if(top==4)
13.{
14.System.out.println(“Overflow”);
15.return;
16.}
17.top++;
18.arr[top]=item;
19.}
20.publicintpop()
21.{
22.if(top==-1)
23.{
24.System.out.println(“Underflow”);
25.return-1;
26.}
27.intitem=arr[top];
28.top—;
29.return(item);
30.}
31.voiddisp()
32.{
33.for(inti=top;i>=0;i—)
34.{
35.System.out.println(arr[i]);
36.}
37.}
38.}
39.classStack_Demo
40.{
41.publicstaticvoidmain(Stringargs[])
42.{
43.Stacks1=newStack();
44.s1.pop();
45.for(inti=0;i<5;i++)
46.s1.push(i+100);
47.s1.push(600);
48.System.out.println(“–-DisplayingAllItem–-“);
49.s1.disp();//noninterfacemethods
50.System.out.println(“–-RemovingAlltheItems–-“);
51.for(inti=0;i<5;i++)
52.{
53.System.out.println(s1.pop());//-1forunderflow
54.}
55.Two_Methodst1=newStack();
56.t1.push(10);
57.System.out.println(t1.pop());
58.//t1.disp();error
59.}
60.}
Output:
Underflow
Overflow
–-DisplayAllItem–-
104
103
102
101
100
–-RemoveAllItems–-
104
103
102
101
100
10
CHAPTER
∞10∞
(StringandStringBuffer)
Introduction-
In java Strings are class objects and implemented using two classes, namely
String and StringBuffer. Java String, as compared to C strings are more reliable and
predictable. This is basically due to C’s lack of bound checking. A java String is not a
characterarrayandisnotNULLterminated.Ingeneral,Javadoesnotallowoperatorsto
beappliedtoStringobjects.
Theoneexceptiontothisruleis+&+=operator,whichconcatenatestwostrings
producingaStringobjectasaresult.InJavacharacterarrayisnottreatedasstring.InJava
String class is defined to do all string operations. The class String and StringBuffer are
partofthejava.langpackage.
Stringclass:
Strings1=newString(“matrix”);
Strings2=“matrix”;
System.out.println(s1);
System.out.println(s1.length);
System.out.println(“matrix”.length);
TheStringhasthefollowingcharacteristicsinjava:
[i]Stringisanobjectinjava:
String represent a sequence of characters, But unlike many other language that
implementsStringascharacterarrays,javaimplementsstringasobjectsoftypestring.
String manipulation is the most common part of many java programs.
Implementing strings as built in objects allows java to provide a full complement of
features that make string handling convenient. Also string objects can be constructed a
numberofways,makingiteasytoobtainastringwhenneeded.
[ii]Stringisimmutable:
Stringareimmutablei.e.wecannotchangethestringaftercreation.Howevera
variabledeclaredasaStringreferencecanbechangetopointsomeotherstringobjectat
anytime.
Wecanstillperformalltypeof stringoperation.Eachtimeweneed analtered
versionofanexistingstring,anewstringobjectiscreatedthatcontainsthemodifications.
The original string is left unchanged. This approach is used because fixed,
immutablestringscanbeimplementedmoreefficientlythanchangeableones.
Forthosecasesinwhichamodifiedstringisdesired,thereisacompanionclass
called StringBuffer, whose objects contain strings that can be modified after they are
created.
[iii]Stringclassisfinal:
Both String and StringBuffer classes are final. It means we can’t extend class
String in any other class. This allows certain optimizationthat increase performance of
commonstringoperations.
Constructors&MethodsofStringclass:
1 publicString();
Initializes a newly created String object so that it represents an empty character
sequence.
Strings1=newString();
2 publicString(Stringstr);
InitializesanewlycreatedStringobjectsothatitrepresentsthesamesequenceof
charactersastheargument;inotherwords,thenewlycreatedstringisacopyof
theargumentstring.
Strings1=newString(“Matrix”);
Strings2=newString(s1);
The string s2 is a copy of string s1. Although contents are same but s1 and s2
pointstodifferentstringobjects.
3 publicString(charch[]);
Allocateda newString sothatit representsthe sequenceof characterscurrently
containedincharacterarrayargument.
charch[]={‘a’,‘b’,‘c’};
Strings1=newString(ch);//s1willhold“abc”
4 publicString(charvalue[],intoffset,intcount);
AllocatesanewStringthatcontainscharactersfromasub-arrayofthecharacter
arrayargument.
charch[]={‘a’,‘b’,‘c’,‘d’,‘e’,‘f’};
Strings1=newString(ch,2,3);//s1willhold“cde”
5 publicString(intvalue[],intoffset,intcount);
Allocates a new String that contains characters from a sub-array of the integer
arrayargumentcontainingUnicodeofcharacters.
inta[]={97,98,99,100,101,102};
Strings1=newString(a,2,3);//s1willhold“cde”
6 publicString(byteb[],intoffset,intcount);
Constructs a new String by decoding the specified sub-array of bytes using the
platform’sdefaultcharset.
byteb[]={97,98,99,100,101,102};
Strings1=newString(b,2,3);//s1willhold“cde”
7 publicString(byte[]);
Constructs a new String by decoding the specified array of bytes using the
platform’sdefaultcharset.
byteb[]={97,98,99};
Strings1=newString(b);//s1willhold“abc”
EventhoughJava’schartypeused16bitstorepresenttheUnicodecharacterset,
thetypicalformatforstringsontheInternetusesarraysof8-bitbytesconstructed
fromtheASCIIcharacterset.Because8-bitASCIIstringsarecommon,theString
classprovidesconstructorsthatinitializeastringwhengivenabytearray.Ineach
of the above constructors the byte to character conversion is done by using the
defaultcharacterencodingoftheplatform.
8 publicString(StringBuffer);
9 publicintlength();
Thiswilldisplaynumberofcharactersofthestring.
10 publicbooleanisEmpty();
Thiswilldisplaytrueifthestringisemptyotherwisefalse.
Strings1=newString();
System.out.println(s1.isEmpty());
11 publiccharcharAt(intindex);
Returnsthecharvalueatthespecifiedindex.Anindexrangesfrom0tolength()–
1.Thefirstcharvalueofthesequenceisatindex0,thenextatindex1,andso
on,asforarrayindexing.ThrowsStringIndexOutOfBoundsExceptionifinvalid
indexisspecified.
Strings1=“matrix”;
System.out.println(s1.charAt(0));//willprint“m”
12 publicvoidgetChars(intsrcBegin,intsrcEnd,char[]dst,intdstBegin);
Copies characters from this string into the destination character array. The first
character to be copied is at index srcBegin, the last character to be copied is at
index srcEnd-1 (thus the total number of characters to be copied is second-
srcBegin). The characters are copied into the subarray of dst starting at index
dstBeginandendingatindex:dstBegin+(srcEnd–srcBegin)–1.Thismethodmay
throwArrayIndexOutOfBoundExceptionandStringIndexOutOfBoundsException.
13 publicvoidgetBytes(intsrcBegin,intserEnd,bytedst[],intdstBegin);
14 publicbyte[]getBytes();
EncodesthisStringintoasequenceofbytesusingtheplatform’sdefaultcharset,
storingtheresultintoanewbytearray.Thismethodismostusefulwhenweare
exportingastringvalueintoanenvironmentthatdoesnotsupport16-bitUnicode
character. For example, most Internet protocols and text file formats use 8-bit
ASCIIforalltextinterchange
15 publicbooleanequals(Object);
Comparesthe invokingstring withthe specifiedobject. Theresult istrue ifand
only if the argument is not null and is a String object that represents the same
sequenceofcharactersastheinvokingstring.
16 publicbooleanequalsIgnoreCase(String);
Compares the invoking String with the anotherString, ignoring case
considerations.
17 publicintcompareTo(String);
Compares the invoking String with the string passed as argument,
lexicographically.
ReturnvalueMeaning
<0Theinvokingstringislessthanstr
>0Theinvokingstringisgreaterthanstr
0Thetwostringsareequals
18 publicintcompareToIgnoreCase(String);
Comparestwostringslexicographically,ignoringcasedifferences.
19 publicbooleanregionMatches(intstartIndex,Stringstr2,intstr2StartIndex,
intlen);
Testsiftwostringregionsareequal.
20
Public boolean regionMatches(Boolean ignoreCase, int startIndex, String
str2,intstr2StartIndex,intlen);
Testsiftwostringregionsareequal.ItignoresthecasedifferenceifignoreCase
flagistrue
21 publicbooleanstartsWith(Stringprefix,intstartIndex)
Tests if this string starts with the specified prefix beginning at specified index.
ThismethoddoesnotreturnanyexceptionbutreturnsfalseifstartIndexisoutof
bound.
22 PublicbooleanstartsWith(String);
Testsifthisstringstartswiththespecifiedprefix.
23 publicbooleanendsWith(Stringsuffix)
Testsifthisstringendswiththespecifiedsuffix.
24 publicintindexOf(charch);
Returns the index within this string of the first occurrence of the specified
character.
25 publicintindexOf(charch,intfromIndex);
Returns the index within this string of the first occurrence of the specified
character,startingthesearchatthespecifiedindex.
26 publicintindexOf(Stringstr);
Returns the index within this string of the first occurrence of the specified
substring.
27 publicintindexOf(Stringstr,intfromIndex);
Returns the index within this string of the first occurrence of the specified
substring,startingatthespecifiedindex.
28 publicintlastIndexOf(intch);
Returns the index within this string of the last occurrence of the specified
character.
29 publicintlastIndexOf(intch,intfromIndex);
Returns the index within this string of the last occurrence of the specified
character,searchingbackwardstartingtheatthespecifiedindex.
30 publicintlastIndexOf(Stringstr);
Returns the index within this string of the last occurrence of the specified
substring.
31 publicintlastIndexOf(Stringstr,intfromIndex);
Returns the index within this string of the last occurrence of the specified
substring,searchingbackwardstartingatthespecifiedindex.
31 publicStringsubstring(int);
Givessubstringstartingfromnthcharacter
32 publicStringsubstring(intn,intm);
Givessubstringstartingfromnthcharacteruptomth.(notincludingmth)
33 publicStringconcat(Stringstr);
Thiswillconcatthestringstrattheendofthecallingstringobject.
34 publicStringreplace(charx,chary);
Replaceallappearanceofxwithy
35 publicStringreplaceFirst(String,String);
36 publicStringreplaceAll(String,String);
37 publicStringtoLowerCase();
Convertsthestringtolowercase
38 publicStringtoUpperCase();
Convertsthestringtouppercase
39 publicStringtrim();
Removesleadingandtrailingspaces
40 publicchar[]toCharArray();
Convertstheinvokingstringtoanewcharacterarray.Thisfunctionisprovidedas
aconvenience,sinceitispossibletousegetChars()toachievethesameresult
41 publicstaticStringvalueOf(Object);
Createastringobjectoftheparameterp(simpletypeorobject)
StringArray:
Wecanalsocreateandusearraythatcontainstrings.
Example10.1
1.importjava.util.Scanner;
2.classStringArrSort
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Scannersc=newScanner(System.in);
7.System.out.print(“Enterhowmanynames“);
8.intn=sc.nextInt();
9.Strings[]=newString[n];
10.//input
11.for(inti=0;i<n;i++)
12.{
13.System.out.println(“Entername”+(i+1));
14.s[i]=sc.next();
15.}
16.//sorting
17.for(inti=0;i<n-1;i++)
18.for(intj=i+1;j<n;j++)
19.if(s[i].compareTo(s[j])>0)
20.{
21.Stringt=s[i];
22.s[i]=s[j];
23.s[j]=t;
24.}
25//output
26.for(inti=0;i<n;i++)
27.System.out.println(s[i]);
28.}
29.}
StringConversionandtoString()
When Java converts data into its String representation during concatenation, it
doessobycallingoneoftheoverloadedversionsoftheStringconversionmethodvalueOf
( ) defined by String class. The valueOf( ) is a static method overloaded for all simple
typesandfortypeObject.
Forthesimpletypes,valueOf()returnsstringthatcontainsthehuman-readable
equivalentofthevaluewithwhichitiscalled.Forobjects,valueOf()callsthetoString()
methodsontheobject.
Every class inherits toString( ), because it is defined by the Object class.
However, the default implementation of the toString( ) is seldom sufficient. It displays
nameoftheclassfollowedbysymbol“@”andthenobject-id(e.g.Box@ab1342),which
isnormallyofnouse.Formostimportantclassesthatwecreate,wewillwanttooverride
toString()andprovideourownstringrepresentations.
Example10.2:
1.classA
2.{
3.privateintx,y;
4.A()
5.{
6.x=y=0;
7.}
8.A(intx1,inty1)
9.{
10.x=x1;
11.y=y1;
12.}
13.}
14.classToStringTest1
15.{
16.publicstaticvoidmain(Stringargs[])
17.{
18.Aa1=newA(5,6);
19.System.out.println(a1);//toString()ofObjectclassiscalled
20.Strings1=“Objecta1is”+a1;//concatobjectwithstring
21.//againtoString()ofObjectiscalled
22.System.out.println(s1);
23.}
24.}
Output:
A@3e25a5
Objecta1isA@3e25a5
Example10.3:-
1.classA
2.{
3.privateintx,y;
4.A()
5.{
6.x=y=0;
7.}
8.A(intx1,inty1)
9.{
10.x=x1;
11.y=y1;
12.}
13.publicStringtoString()
14.{
15.return(x+“,”+y);
16.}
17.}
18.classToStringTest2
19.{
20.publicstaticvoidmain(Stringargs[])
21.{
22.Aa1=newA(5,6);
23.System.out.println(a1);//toString()ofAclassiscalled
24.Strings1=“Objecta1is”+a1;//concatobjectwithstring
25.//againtoString()ofAclassiscalled
26.System.out.println(s1);
27.}
28.}
Output:5,6
Objecta1is5,6
Example10.4:-
1.importjava.util.*;
2.classFindTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Scannersc=newScanner(System.in);
7.Strings1,s2;
8.System.out.print(“Enterastring”);
9.s1=sc.next();
10.System.out.print(“Enterstringtosearch”);
11.s2=sc.next();
12.intans=s1.indexOf(s2);
13.if(ans==-1)
14.System.out.println(“NotFound”);
15.else
16.System.out.println(“foundatpos”+ans);
17.}
18.}
StringBuffer:
StringBufferisapeerclassofStringthatprovidesmuchofthefunctionalityof
String. As we know, String represents fixed length, immutable character sequence. In
contrast to String, StringBuffer represents growable and writeable character sequences.
StringBuffermayhavecharactersandsubstringsinsertedinthemiddleorappendedtothe
end.
StringBufferwillautomaticallygrowtomakeroomforsuchadditionsandoften
has more characters pre-allocated than are actually needed, to allow room for growth.
Java uses both class heavily, but many programmer deal only with String and java
manipulateStringBufferbehindthescenesbyusingtheoverloaded+operator.
FewimportantpointrelatedtoStringBufferclass
StringBufferisanObjectlikeString.
StringBufferclassisalsofinallikeStringclass.
StringBufferobjectsaremutable(canbemodified)unlikeStringobjects.
ConstructorsandMethodsofStringBufferclass:-
publicStringBuffer();
Thedefaultconstructorreservesroomfor16characterswithoutreallocation.
publicStringBuffer(int);
Thisconstructoracceptaintegerargumentthatexplicitlysetsthesizeofthebuffer.
publicStringBuffer(String);
This constructor accept a String argument that sets the initial contents of the
StringBufferobjectandreservesroomfor16morecharacterswithoutreallocation.
publicsynchronizedintlength();
ReturnsthecurrentlengthoftheStringBuffer.
publicsynchronizedintcapacity();
Returnsthecurrentcapacity.Thecapacityistheamountofstorageavailablefornewly
insertedcharacters,beyondwhichanallocationwilloccur.
publicsynchronizedvoidensureCapacity(int);
Ensuresthatthecapacityisatleastequaltothespecifiedminimum.Ifwewanttopre-
allocateroomforacertainno.ofcharactersafteraStringBufferhasbeenconstructed,
wecan useensureCapacity()methodto set thesize ofthe buffer.This isusefulif we
know in advance that we will be appending a large number of small strings to a
StringBuffer.
publicsynchronizedvoidtrimToSize();
Thiswillremoveextrafreespace.NowCapacitywillbeequaltolength.
publicsynchronizedvoidsetLength(intnewLength);
Setsthelengthofthecharactersequence.ThenewLengthmustbenon-negative.When
weincrease thesizeof thebuffer,nullcharactersareadded tothe endoftheexisting
buffer. If we call setLength() with a value less then the current value returned by
length(),thenthecharactersstoredbeyondthenewlengthwillbelost.
publicsynchronizedcharcharAt(intindex);
Returnsthecharvalueinthissequenceatthespecifiedindex.
public synchronized void getChars(int srcBegin, int srcEnd, char[] dst, int
dstBegin)
Characters are copied from this sequence into the destination character array dst. The
first character to be copied is at index srcBegin; the last character to be copied is at
index srcEnd-1. The total number of characters to be coped is srcEnd-srcBegin. The
charactersarecopiedintothesubarrayofdststartingatindexdstBegin.
Note:Ensurethatthedestinationortargetarrayislargeenoughtoholdthenumberof
characterinthespecifiedsubstring.
publicsynchronizedvoidsetCharAt(intindex,charch);
Thecharacteratthespecifiedindexissettoch.IndexOutOfBoundsExceptionoccursif
indexinnegativeorgreaterthanorequaltolength().
publicsynchronizedStringBufferappend(Object);
Theappendmethodconcatenatesthestringrepresentationofanyothertypeofdatato
theendoftheinvokingStringBufferobject.
publicsynchronizedStringBufferdelete(intstart,intend);
Removescharactersfromindexstarttoindexend-1
publicsynchronizedStringBufferdeleteCharAt(intindex);
Removesthecharatthespecifiedposition
publicsynchronizedStringBufferreplace(intstart,intend,Stringstr);
Replaces the characters from index start to index end-1 with the characters in the
specifiedString.
publicsynchronizedStringsubstring(int);
ReturnsanewStringthatcontainsasubsequenceofcharactercurrentlycontainedinthis
charactersequence.Thesubstringbeginsatthespecifiedindexandextendstotheendof
thissequence.
publicsynchronizedStringsubstring(intstart,intend);
Returnsa new String thatcontains a subsequenceofcharacters currently containedin
thischaractersequence.Thesubstringbeginsatthespecifiedstartindexandextendsto
thecharacteratindexend-1.
publicsynchronizedStringBufferinsert(int,Object);
InsertoneStringintoanotherString.Itisoverloadedtoacceptvaluesofallthesimple
typesplusStringsandObjects.
publicintindexOf(String);
publicsynchronizedintindexOf(String,int);
publicintlastIndexOf(String);
publicsynchronizedintlastIndexOf(String,int);
publicsynchronizedStringBufferreverse();
ReversethecontentsoftheStringBuffer.
Example10.5:
1.importjava.util.Scanner;
2.classSortStr
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Scannersc=newScanner(System.in);
7.System.out.print(“Enterastring”);
9.StringBuffersb1=newStringBuffer(sc.next());
10.//Sorting
11.for(inti=0;i<sb1.length()-1;i++)
12.for(intj=i+1;j<sb1.length();j++)
13.if(sb1.charAt(i)>sb1.charAt(j))
14.{
15.chart=sb1.charAt(i);
16.sb1.setCharAt(i,sb1.charAt(j));
17.sb1.setCharAt(j,t);
18.}
19.System.out.println(sb1);
20.}
21.}
Output:EnterastringSHIVAM
AHIMSV
Example10.6:Programtocountno.ofwordsinagivensentence.
1.classWordCnt
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.Strings1=“MohanDasKaramChandGandhi”;
6.booleanflag=false;
7.intcnt=0;
8.for(inti=0;i<s1.length();i++)
9.{
10.if(s1.charAt(i)==‘‘)
11.flag=false;
12.else
13.{
14.if(flag==false)
15.{
16.flag=true;
17.cnt++;
18.}
19.}
20.}
21.System.out.print(“No.ofWords=”+cnt);
22.}
23.}
Output:No.ofWords=5
CHAPTER
∞11∞
(ExceptionHandling)
Introduction-
AnExceptionisaconditionthatiscausedbyaruntimeerrorintheprogramthat
breaksthenormalflowoftheprogram.Whenthejavainterpreterencountersanerrorsuch
asdividinganintegerbyzero,itcreatesanExceptionobjectandthrowsit.(i.e.,informus
thatanerrorisoccurred).
AJavaexception/errorisanobjectofclassExceptionoroneoftheirsub-classes
wheneverexceptionoccursattherun-time.Theexceptionobjectcontainsdetailsaboutthe
exceptionwhichcanbeaccessedusingthepublicmethodsprovidedforthispurpose.
Insomeolderlanguageswehavetouseif,gotoandreturncodesforerrorhandling.
Anexception isanabnormal condition that arisesin a codesequence at run
time.Inotherwords,anexceptionisaruntimeerror.Incomputerlanguagesthatdonot
support exception handling, errors must be checked and handled manually—
typicallythroughtheuseoferrorcodes,andsoon.
This approach is as cumbersome as it is troublesome. Java’s exception
handling avoids these problems and, in the process, brings run-time error
managementintotheobject-orientedworld.
Exception-HandlingFundamentals
AJavaexceptionisanobjectthatdescribesanexceptional(thatis,error)
conditionthathasoccurredinapieceofcode.Whenanexceptionalconditionarises,
anobjectrepresentingthatexceptioniscreatedandthrowninthemethodthatcaused
theerror.Thatmethodmaychoosetohandletheexceptionitself,orpassiton.
Eitherway,atsomepoint,theexceptioniscaughtandprocessed.Exceptions
canbe generatedby the Javarun-timesystem,or they canbe manuallygenerated by
yourcode.ExceptionsthrownbyJavarelatetofundamentalerrorsthatviolatethe
rules of the Java language or the constraints of the Java execution environment.
Manuallygeneratedexceptionsaretypicallyusedtoreportsomeerrorconditiontothe
callerofamethod.
Javaexceptionhandlingismanagedviafivekeywords:try,catch,throw,
throws,andfinally.Briefly,hereishowtheywork.Programstatementsthatyou
want to monitor for exceptions are contained within a try block. If an exception
occurswithinthetryblock,itisthrown.Yourcodecancatchthisexception(usingcatch)
and handle it in some rational manner. System-generated exceptions are automatically
thrownbytheJavaruntimesystem.Tomanuallythrowanexception,usethekeyword
throw.Anyexceptionthatisthrownoutofamethodmustbespeci0edassuchby
athrowsclause.
Anycodethatabsolutelymustbeexecutedafteratryblockcompletesisputina
finallyblock.
Thisisthegeneralformofanexception-handlingblock:
Thisisthegeneralformofanexceptionhandlingblock:
try{
//blockofcodetomonitorforerrors
}
catch(ExceptionType1exOb){
//exceptionhandlerforExceptionType1
}
//………
finally{
//blockofcodetobeexecutedaftertryblockends
}
ExceptionTypes
Allexceptiontypesaresubclassesofthebuilt-inclassThrowable.Thus,
Throwable is at the top of the exception class hierarchy. Immediately below
Throwablearetwosubclassesthatpartitionexceptionsintotwodistinctbranches.
OnebranchisheadedbyException.Thisclassisusedforexceptionalconditions
thatuserprogramsshouldcatch.Thisisalsotheclassthatyouwillsubclasstocreate
yourowncustomexceptiontypes.
There is an important subclass of Exception, called RuntimeException.
Exceptionsofthistypeareautomaticallydefinedfortheprogramsthatyouwrite
andincludethingssuchasdivisionbyzeroandinvalidarrayindexing.
The other branch is topped by Error, which defines exceptions that are not
expectedtobecaughtundernormalcircumstancesbyyourprogram.Exceptionsof
typeErrorareusedbytheJavarun-timesystemtoindicateerrorshavingtodo
withtherun-timeenvironment,itself.Stackoverflowisanexampleofsuchanerror.
ThischapterwillnotbedealingwithexceptionsoftypeError,becausetheseare
typicallycreatedinresponsetocatastrophicfailuresthatcannotusuallybehandledby
yourprogram.
Thetop-levelexceptionhierarchyisshownhere:
Example11.1
1.classErrorTest1
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.inta=5,b=2,c=2,d;
6.d=a/(b-c);//ArithmeticException(Dividebyzero)occurred
7.System.out.println(d);
8.System.out.println(“Thiswillnotbeprinted”);
9.}
10.}
Programwillterminateduringdivideoperationandwillnotruntheremainingstatements.
Example11.2
1.classA
2.{
3.voiddisplay()
4.{
5.–—
6.}
7.}
8.classErrorTest2
9.{
10.publicstaticvoidmain(Stringargs[])
11.{
12.Aa1=null;
13.a1.display();//NullPointerExceptionoccurred
14.}
15.}
In the above program NullPointerException will occur. The reference variable is not
initializedwithnew.Theprogramgetsterminatedinthiscasealso.
Example11.3
1.classErrorTest3
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.inta[]={10,20,30};
6.System.out.println(a[3]);//ArrayIndexOutOfBoundsException
occurred
7.}
8.}
Intheabovecasethelengthofarrayis3andtheindexisfrom0to2,soifweprinta[3]
then this is the 4th element which is not a valid index. This will generate an exception
error.InC/C++itisallowedbutnotinJava.
NOTE-
JDK 7 adds a new form of the try statement that supports automatic resource
management. This new form of try, called try-with-resources, is described in file
Chapterinthecontextofmanagingfilesbecausefilesaresomeofthemostcommonly
usedresources.
OthercasesofExceptions
1. Thefilewearetryingtoopenmaynotexist.
2. Wewanttocreateanewobjectbutnomemoryisavailable.
3. Theclassfilewewanttoloadmaybemissingorinthewrongformat.
4. The String, which we want to convert to a number, is having invalid
characterssothatitcannotbeconvertedtoanumber.
Iftheexceptionobjectisnotcaughtandhandledproperly,theinterpreterwilldisplayan
errormessageandwillterminatetheprogram.Ifwewanttocontinuewiththeexecution
withtheremainingcode,thenweshouldtrytocatchtheexceptionobjectthrownbythe
errorcondition.
Thistaskisknownasexceptionhandling.Thepurposeoftheexceptionhandling
mechanismistoprovideameanstodetectareportan“exceptionalcircumstance”sothat
theappropriateactioncanbetaken.Thismechanismsuggestsincorporationofaseparate
errorhandlingcodethatperformsthefollowingtasks:
1.Findtheproblem.(Exceptionoccur)
2.Informthatanerrorhasoccurred.(throwtheexception)
3.Receivetheerrorinformation.(catchtheexception)
4.Thecorrectiveaction.(handletheexception)
JavaExceptionhandlingismanagedviafivekeywords:
try,catch,throw,throwsandfinally.
Programstatementsthatwewanttomonitorforexceptionarecontainedwithina
tryblock,andwheneveranerroroccursthenitisthrowntothecatchblock.Ourcodecan
catchthisexception(usingcatch)andhandleitinsomerationalmanner.Systemgenerated
exceptionareautomaticallythrownbythejavaruntimesystem.
Tomanuallythrowanexception,usethekeywordthrow.Anyexceptionthatis
thrown out of a method must be specified as such by a throws clause. Any code that
absolutelymustbeexecutedbeforeamethodreturnsisputinafinallyblock.
The try block must be enclosed between braces even if there is only one
statement in it. There can be one or more catch statements and zero or one finally
statement. Both catch and finally blocks are optional but either one catch block or one
finallyblockismust.
ThecodeinthetryblockisexecutedlikeanyotherJavacode.Ifthecodeinside
thetryblockexecutessuccessfullythenthecontrolgoestofinallyblockifitispresentand
thentheexecutioncontinuesfromthestatementjustaftertheendoffinallyblock(i.e.
after the end of try statement) If the finally block is not present then the execution
continues from the statement just after the last catch block (i.e. after the end of try
statement).
If some run-time error occurs while executing the code in try block then JVM
throwsanExceptionError.ThismeansanobjectoftypeExceptionErrororoneofitssub-
classesiscreateddependingonthetypeoftherun-timeerror.Thisisthencomparedwith
theException/Errortypesofthecatchblocksintoptobottomorder.
If a matching catch block is found then the exception / error is handled i.e.
programwillnotterminate.Theexecutioncontinueswiththefirststatementinthecatch
block.Oncompletionofthecatchblock,executioncontinueswiththestatementjustafter
theendoftry&catchstatement.
At the most one catch block is executed irrespective of the number of catch
blocks.Ifexception/errordoesnotmatchwithexception/errortypeofanyofthecatch
blocks,thenwesaythatitisnothandled.
The execution will immediately return from try block. The code in the finally
blockwillbeexecutedeveniftheexception/errorisnothandled.
The exception / error will then be handled by outer try block if there is one
otherwiseitmustbehandledinthemethodwhichcalledthecurrentmethod.
Theexception/errormovesupthehierarchytillitishandledoritispassedto
JVMunhandledifnothandledeveninthemain()methodwhichisthefirstmethodfrom
whichtheexecutionstarts.
TheJVMthensimplyterminatestheprogramanddisplaystheexception/error
detailsonthemonitor/console.
HerewehaverepresentsomeExceptionwhichcanbeoccurattheexecutiontimeinthe
program.
Usingtryandcatch-
Although the default exception handler provided by the Java run-time system is
usefulfordebugging,youwillusuallywanttohandleanexceptionyourself.Doing
soprovidestwobene0ts.First,itallowsyouto0xtheerror.
Second,itpreventstheprogramfromautomaticallyterminating.Mostuserswould
beconfused(tosaytheleast)ifyourprogramstoppedrunningandprintedastack
tracewheneveranerroroccurred!Fortunately,itisquiteeasytopreventthis.
Toguardagainstandhandlearun-timeerror,simplyenclosethecodethatyouwantto
monitor inside a tryblock. Immediately following the tryblock, include a catch
clausethatspeci0estheexceptiontypethatyouwishtocatch.
Toillustratehoweasilythiscanbedone,thefollowingprogramincludesatryblock
andacatchclausethatprocessestheArithmeticExceptiongeneratedbythedivision-
by-zeroerror:
classExc2{
publicstaticvoidmain(Stringargs[])
{
intd,a;
try{//monitorablockofcode.
d=0;
a=42/d;
System.out.println(“Thiswillnotbeprinted.”);
}
catch(ArithmeticExceptione)
{
//catchdivide-by-zeroerror
System.out.println(“Divisionbyzero.”);
}
System.out.println(“Aftercatchstatement.”);
}
}
Thisprogramgeneratesthefollowingoutput:
Divisionbyzero.
Aftercatchstatement.
Notice that the call to println( ) inside the try block is never executed. Once an
exceptionisthrown,programcontroltransfersoutofthetryblockintothecatchblock.
Putdifferently,catchisnot“called,”soexecutionnever“returns”tothetryblock
fromacatch.
Thus,theline“Thiswillnotbeprinted.”isnotdisplayed.Oncethecatch
statement has executed, program control continues with the next line in the program
followingtheentiretry/catchmechanism.
A try and its catch statement form a unit. The scope of the catch clause is
restrictedtothosestatementsspecifiedbytheimmediatelyprecedingtrystatement.
Acatchstatementcannotcatchanexceptionthrownbyanothertrystatement
(exceptinthecaseofnestedtrystatements,describedshortly).Thestatementsthatare
protectedbytrymustbesurroundedbycurlybraces.(Thatis,theymustbewithina
block.)Youcannotusetryonasinglestatement.
Thegoalofmostwell-constructedcatchclausesshouldbetoresolvetheexceptional
conditionandthencontinueonasiftheerrorhadneverhappened.Forexample,in
thenextprogrameachiterationoftheforloopobtainstworandomintegers.
Thosetwointegersaredividedbyeachother, andtheresultisusedtodivide
thevalue12345.Thefinalresultisputintoa.Ifeitherdivisionoperationcausesa
divide-by-zeroerror,itiscaught,thevalueofaissettozero,andtheprogram
continues
//Handleanexceptionandmoveon.
importjava.util.Random;
classHandleError{
publicstaticvoidmain(Stringargs[]){
inta=0,b=0,c=0;
Randomr=newRandom();
for(inti=0;i<32000;i++){
try{
b=r.nextInt();
c=r.nextInt();
a=12345/(b/c);
}catch(ArithmeticExceptione){
System.out.println(“Divisionbyzero.”);
a=0;//setatozeroandcontinue
}
System.out.println(“a:”+a);
}
}}.
DisplayingaDescriptionofanException
ThrowableoverridesthetoString()method(de0nedbyObject)sothatitreturnsastring
containing a description of the exception. You can display this description in a
println()statementbysimplypassingtheexceptionasanargument.Forexample,
thecatchblockintheprecedingprogramcanberewrittenlikethis:
catch(ArithmeticExceptione)
{
System.out.println(“Exception:”+e);
a=0;//setatozeroandcontinue
}
Whenthisversionissubstitutedintheprogram,andtheprogramisrun,eachdivide-by-zeroerrordisplaysthe
followingmessage:
Exception:java.lang.ArithmeticException:/byzero
Whileitis of no particularvalueinthiscontext,theabilitytodisplayadescriptionof an exception is
valuablein other circumstances—particularlywhenyouare experimentingwithexceptions or whenyou are
debugging.
ExceptionType CauseoftheException
ArithmeticException ArithmeticErrorsuchas-Divisionby0
ArrayIndexOutOfBoundsException Outoflimitofarrayindexes
ArrayStoreException Storethewrongtypeofdatainanarray
FileNotFoundException Accessanon-existentfile
IOException Inabilitytoreadfromafile
NullPointerException Causedbyreferencinganullobject
NumberFormatException Conversionbetweenstringandnumberfails
OutOfMemoryException Notenoughmemorytoallocateanewobject
SecurityException An applets tries to perform an action not
allowedbythebrowser’ssecuritysetting
StackOverflowException TheSystemrunsoutofstackspace
StringIndexOutOfBoundsException Aprogramattempttoaccessanonexistentcharacterpositionina
string
Java’sBuilt-inExceptions
Insidethestandardpackagejava.lang,Javadefinesseveralexceptionclasses.Afew
havebeenusedbytheprecedingexamples.Themostgeneraloftheseexceptions
aresubclassesofthestandardtypeRuntimeException.
Aspreviouslyexplained,theseexceptionsneednotbeincludedinanymethod’sthrows
list. In the language of Java, these are called unchecked exceptions because the
compilerdoesnotchecktoseeifamethodhandlesorthrowstheseexceptions.The
uncheckedexceptionsdefinedinjava.langarelistedinTable-1.Table-2liststhose
exceptionsdefinedbyjava.langthatmustbeincludedinamethod’sthrowslistif that
methodcangenerateoneoftheseexceptionsanddoesnothandleititself.Theseare
calledcheckedexceptions.Javadefinesseveralothertypesofexceptionsthatrelatetoits
variousclasslibraries.
GeneralformofanExceptionhandling
(Exceptionhandlingmechanism)
Syntax:
------------
------------
try
{
statement;//generatesanexception
}
catch(Exception-typee)
{
statement;//processtheexception
}
------------
------------
MultiplecatchClauses
Insomecases,morethanoneexceptioncouldberaisedbyasinglepieceof
code.Tohandlethistypeofsituation,youcanspecifytwoormorecatchclauses,
eachcatchingadifferenttypeofexception.
Whenanexceptionisthrown,eachcatchstatementisinspectedinorder,and
the0rstonewhosetypematchesthatoftheexceptionisexecuted.Afteronecatch
statementexecutes,theothersarebypassed,andexecutioncontinuesafterthetry/
catchblock.Thefollowingexampletrapstwodifferentexceptiontypes:
//Demonstratemultiplecatchstatements.
classMultipleCatches{
publicstaticvoidmain(Stringargs[]){
try{
inta=args.length;
System.out.println(“a=”+a);
intb=42/a;
intc[]={1};
c[42]=99;
}catch(ArithmeticExceptione){
System.out.println(“Divideby0:”+e);
}catch(ArrayIndexOutOfBoundsExceptione){
System.out.println(“Arrayindexoob:”+e);
}
System.out.println(“Aftertry/catchblocks.”);
}
}
This program will cause a division-by-zero exception if it is started with no
command-line arguments, since a will equal zero. It will survive the division if you
provideacommandlineargument,settingatosomethinglargerthanzero.Butit
willcauseanArrayIndexOutOfBoundsException,sincetheintarraychasalength
of1,yettheprogramattemptstoassignavaluetoc[42].
Hereistheoutputgeneratedbyrunningitbothways:
C:\>javaMultipleCatches
a=0
Divideby0:java.lang.ArithmeticException:/byzero
Aftertry/catchblocks.
C:\>javaMultipleCatchesTestArg
a=1
Arrayindexoob:java.lang.ArrayIndexOutOfBoundsException:42Aftertry/catchblocks.
Whenyouusemultiplecatchstatements,itisimportanttorememberthat
exceptionsubclassesmustcomebeforeanyoftheirsuperclasses.Thisisbecausea
catchstatementthatusesasuperclasswillcatchexceptionsofthattypeplusanyofits
subclasses.
Thus,asubclass wouldnever bereached if itcame after itssuperclass.
Further, in Java, unreachable code is an error. For example, consider the following
program:
/*Thisprogramcontainsanerror.
Asubclassmustcomebeforeitssuperclassin
aseriesofcatchstatements.Ifnot,
unreachablecodewillbecreatedanda
compile-timeerrorwillresult.
*/
classSuperSubCatch{
publicstaticvoidmain(Stringargs[]){
try{
inta=0;
intb=42/a;
}catch(Exceptione){
System.out.println(“GenericExceptioncatch.”);
}
/*Thiscatchisneverreachedbecause
ArithmeticExceptionisasubclassofException.*/
catch(ArithmeticExceptione){//ERROR–unreachable
System.out.println(“Thisisneverreached.”);
}
}
}
Ifyoutrytocompilethisprogram,youwillreceiveanerrormessagestatingthatthe
second catch statement is unreachable because the exception has already been
caught. Since ArithmeticException is a subclass of Exception, the first catch
statementwillhandleallException-basederrors,includingArithmeticException.
Thismeansthatthesecondcatchstatementwillneverexecute.Tofixtheproblem,
reversetheorderofthecatchstatements.
NestedtryStatements
Thetrystatementcanbenested.Thatis,atrystatementcanbeinsidetheblockof
anothertry.Eachtimeatrystatementisentered,thecontextofthatexceptionis
pushedonthestack.
Ifaninnertrystatementdoesnothaveacatchhandlerforaparticularexception,the
stackisunwoundandthenexttrystatement’scatchhandlersareinspectedforamatch.
Thiscontinuesuntiloneofthecatchstatementssucceeds,oruntilallofthe
nestedtrystatementsareexhausted.Ifnocatchstatementmatches,thentheJavarun-
timesystemwillhandletheexception.
Hereisanexamplethatusesnestedtrystatements:
Multiplecatchstatement
Whentherearemorethanonecatchstatementthenitissaidtobeamultiplecatch
statement.
Examplemultiplecatchstatements
try
{
statement;//generateanexception
}
catch(Exception-type-1e)
{
statement1;//processexceptiontype1
}
catch(Exception-type-2e)
{
statement2;//processexceptiontype2
}
--
--
catch(Exception-type-ne)
{
statementn;//processexceptiontypen
}
Example11.4
1.classErrorTest4
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.inta=10,b=2,c=2,d;
6.System.out.println(“BeforeException“);
7.d=a/(b-c);
8.System.out.println(“AfterException“);
9.}
10.}
Output:
Herewearenotcachingtheexceptionsotheprogramwillterminate,afterdisplayingthe
message“BeforeException”.Nowwehavesolvedthisproblemusingexceptionhandling.
Example11.5
1.classErrorTest5
2.{
3.publicstaticvoidmain(String[]args)
4.{
5.inta=10,b=2,c=2,d;
6.try
7.{
8.System.out.println(“BeforeException”);
9.d=a/(b-c);
10.System.out.println(“ThisWillNotPrint”);
11.}
12.catch(ArithmeticExceptione)
13.{
14.System.out.println(“AfterException”);
15.System.out.println(“error:Divisionbyzero”);
16.}
17.}
18.}
Output:
AdvantagesofExceptionHandling-
Wecaneasilysaywheretheexception/errorwillbehandled.Exception/Errors
propagateupthecallstackatruntime-firstuptheenclosingtryblocksandthen
backtothecallingmethod-untilanexceptionhandlercatchthem.
The location of the exception / error is known exactly as entire stack trace is
availabletotheuser.Thisisveryhelpfulindebugging.
Programmergetsachancetorecoverfromtheerror/abnormalcondition.
Errorhandling codeis separatedfromthe normalprogram flowto increasethe
readabilityandmaintainability
With java there is no need to test if an exception / error condition happens.
Addingmoreerror/exceptionhandlersimplyrequiresaddingmorecatchclauses,
buttheoriginalprogramflowneednotbetouched.
HierarchyofExceptionClass-
Root class of all Exception / Error class is the throwable class, which is an
immediate subclass of the object class. Exceptions/Errors are also objects in
Java.SubclassesofExceptionhavethesuffixException.
Therearetwoimmediatesubclassoftheclassthrowable.
Error:-ThesubclassesofErrorclassarebasicallyusedforsignalingabnormal
systemconditionslike:
1. OutOfMemoryError signals that the Java VM has run out of memory and
thatthegarbagecollectorisunabletoclaimanyfreememory.
2. StackOverflowErrorsignalsastackoverflowintheinterpreter.
Theerrorsare,ingeneral,unrecoverableandshouldnotbehandled.
Exception:-The sub classes of Exception class are, in general recoverable. For
example,EOFExceptionsignalsthatafilewehaveopenedhasnomoredatafor
reading.FileNotFoundExceptionsignalsthatafilewewanttoopendoesnotexist
inthefilesystem.
ExampleoftheErrorhierarchy:
Exceptioncategorizedintwotypes
-CheckedException.
-UncheckedException.
CheckedException
If it is must to catch an exception then it is called a checked exception. The
programwillnotcompileifthereisapossibilityofoccurringcheckedexceptioninatry
blockanditisnothandled.
Thecompilerensuredthatifamethodcanthrowacheckedexception,directlyor
indirectly,thenthemethodmustexplicitlydealwithit.Themethodmusteithercatchthe
exceptionandtaketheappropriateaction,orpasstheexceptionontoitscaller.
Note:Exceptionandallof itssub-class(Excludingruntime-exceptionanditssubclass)
arecheckedandmustbecaught.
UncheckedException
Ifitisnotmusttocatchanexceptionthenitscalledanuncheckedexception.The
programwillcompileeveniftheuncheckedexceptionisnothandled.Ifanyunchecked
exception occurs in a program which is not handled then the program execution will
terminate at that point. But if exception is handled then program will not terminate
becauseofexception.
Note:-Errorandallofitssubclassareuncheckedexceptionandneednotbecaught.Run-
timeExceptionandallofitssubclassareuncheckedexceptionandneednotbecaught.All
userdefinedExceptionarechecked.
MethodsavailableinExceptionclass-
StringgetMessage() To obtain the error message associated with
exceptionorerror.
void
printStackTrace()
To print a stack trace showing where the
exception/erroroccurs.
StringtoString() To show the exception/error name along with the
messagereturnedbygetMessage().
Example11.6
1.classErrorTest6
2.{
3.publicstaticvoidmain(String[]arr)
4.{
5.try
6.{
7.inta=10,b=2,c=2,d;
8.System.out.println(“BeforeException”);
9.d=a/(b-c);
10.System.out.println(“ThisWillNotPrint”);
11.}
12.catch(ArithmeticExceptione)
13.{
14.System.out.println(“AfterException”);
15.System.out.println(“error:Divisionbyzero”);
16.System.out.println(e.getMessage());
17.System.out.println(e);//toString()iscalled.
18.e.printStackTrace();
19.}
20.}
21.}
Output:
BeforeException
AfterException
error:Divisionbyzero
/byZero
java.lang.ArithmeticException:/byzero
java.lang.ArithmeticException:/byzero
atErrorTest6.main(ErrorTest6.java:10)
Example11.7Multiplecatches
1.classErrorTest7
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.try
6.{
7.inta=args.length;
8.System.out.println(“BeforeException”);
9.intb=58/a;
10.intc[]={1};
11.c[47]=100;
12.System.out.println(“AfterException”);
13.}
14.catch(ArithmeticExceptione)
15.{
16.System.out.println(“Dividebyzero:”+e);
17.}
18.catch(ArrayIndexOutOfBoundsExceptione)
19.{
20.System.out.println(“ArrayIndexoob:”+e);
21.}
22.System.out.println(“Aftertry/catchblock”);
23.}
24.}
Output1:Whenweruntheaboveprogramas“javaErrorTest7”
BeforeException
Dividebyzero:java.lang.ArithmeticException:/byzero
Aftertry/catchblock
Output2:Whenweruntheaboveprogramas“javaErrorTest745”
BeforeException
ArrayIndexoob:java.lang.ArrayIndexOutOfBoundsException:47
Aftertry/catchblock
Nestedtrycatch
If we use try and catch statements in another try block then it is said to be a
nestedtrycatch.
Syntax
----------
try//outertry
{
-----
try//innertry
{
statement;
}
catch1(------)//innercatch
{
statement;
}
catch2(------)//innercatch
{
statement;
}
}
catch(-----)//outercatch
{
statement;
}
-------------
Example11.8Nestedtryandcatch-
1.classNested
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.try
6.{
7.inta=args.length;
8.intb=58/a;
9.System.out.println(“a=“+a);
10.try
11.{
12.if(a==1)
13.a=a/(a-a);
14.if(a==2)
15.{
16.intc[]={1};
17.c[42]=100;
18.}
19.}
20.catch(ArrayIndexOutOfBoundsExceptione)
21.{
22.System.out.println(“ArrayIndexoob“+e);
23.}
24.}
25.catch(ArithmeticExceptione)
26.{
27.System.out.println(e.getMessage());
28.}
29.}
30.}
OutputI:
Whenweruntheaboveprogramas“javaErrorTest8”/byzero
OutputII:
Whenweruntheaboveprogramas“javaErrorTest810”
a=1/byzero
OutputIII:
Whenweruntheaboveprogramas“javaErrorTest81020”a=2
ArrayIndexoobjava.lang.ArrayIndexOutOfBoundsException:42
finallyStatement
Java support another statement known as finally statement that can be used to
handle an exception that is not caught by any of the previous catch statement. finally
blockcanbeusedtohandleanyexceptiongeneratedwithinatryblock.Itwillexecutedin
all the cases whether error occurred or not. It may be added immediately after the try
blockorafterthelastcatchblockshownasfollows:
Syntax:
try
{
------
}
catch(…)
{
-------
}
catch(…)
{
-------
}
finally
{
--------
}
Example11.9finallystatement
1.classErrorTest9
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.inta[]={5,10};
6.intb=5;
7.try
8.{
9.intx=a[2]/b-a[1];
10.}
11.catch(ArithmeticExceptione)
12.{
13.System.out.println(“DivisionByZero”);
14.}
15.catch(ArrayIndexOutOfBoundsExceptione)
16.{
17.System.out.println(“ArrayIndexerror”);
18.}
19.catch(ArrayStoreExceptione)
20.{
21.System.out.println(“WrongDataType”);
22.}
23.finally//alwaysexecute
24.{
25.System.out.println(“AlwaysExecute”);
26.}
27.inty=a[1]/a[0];
28.System.out.println(“y=“+y);
29.}
30.}
Output:ArrayIndexerror
AlwaysExecute
y=2
throw
Sofar,weareonlybeencatchingexceptionthatarethrownbythejavarun-time
system.Howeveritspossibleforourprogramtothrowanexceptionexplicitly,usingthe
throwstatement,thegeneralformofthrowisshownhere:
throwThrowableinstance;
Here,ThrowableinstancemustbeanobjectoftypeThrowableorasubclassof
Throwable.Simpletypesuchas intorchar, aswell as non-Throwableclasses suchas
String and Object, cannot be used as exception. There are two ways we can obtain a
Throwableobject: usingaparameter intoa catch clause,or creatingone with thenew
operator
The flow of execution stops immediately after the throw statement; any
subsequentstatementarenotexecuted.Thenearestenclosingtryblockisinspectedtosee
ifithasacatchstatementthatmatchesthetypeoftheexception.Ifitdoesfindamatch,
control is transferred to that statement. If not then the next enclosing try statement is
inspected, and so on. If no matching catch is found, then the default exception handler
haltstheprogramprintsthestacktrace.
Herewehavetakenaprogramthatcreatesandthrowsanexception.Thehandler
thatcatchestheexceptionrethrowsittotheouterhandler.
Example11.10
1.classErrorTest10
2.{
3.intage;
4.voidsetAge(inta)
5.{
6.if(a>0)
7.age=a;
8.else
9.{
10.NullPointerExceptione=newNullPointerException(“InvalidAge”);
11.throwe;
12.//thrownewNullPointerException(“InvalidAge”);
13.}
14.}
15.publicstaticvoidmain(Stringargs[])
16.{
17.ErrorTest10a1=newErrorTest10();
18.try
19.{
20.a1.setAge(20);
21.a1.setAge(-10);
22.}
23.catch(NullPointerExceptione)
24.{
25.System.out.println(e.getMessage());
26.}
27.}
28.}
Output:
InvalidAge
throws
If a method is capable of causing an exception that it does not handle, it must
specify this behavior so that caller of the method can guard themselves against that
exception.Wedothisbyincludingathrowsclauseinthemethod’sdeclaration.Athrows
clauseliststhetypeofexceptionthatamethodmightthrow.
This is necessary for all checked exceptions. All exceptions that a method can
throw must be declared in the throws clause. If they are not, a compile-time error will
result. This is a general form of a method declaration that includes a throws
clause:
Syntax:
typemethod-name(parameterlist)throwsexception-list
{
//bodyofmethod
}
Here,exceptionlistisacomma-separatedlistoftheexceptionthatamethodcan
throw
Example11.11
0.importjava.io.*;
1.classErrorTest11
2.{
3.intage;
4.voidsetAge(inta)throwsIOException
5.{
6.if(a>0)
7.age=a;
8.else
9.{
10.IOExceptione=newIOException(“InvalidAge”);
11.throwe;
12.}
13.}
14.publicstaticvoidmain(Stringargs[])
15.{
16.ErrorTest11a1=newErrorTest11();
17.try
18.{
19.a1.setAge(20);
20.a1.setAge(-10);
21.}
22.catch(IOExceptione)
23.{
24.System.out.println(e.getMessage());
25.}
26.}
27.}
Output:
InvalidAge
Creatinguser-definedException/Errorsub-classes:
CreatingYourOwnExceptionSubclasses-
Thisisquiteeasytodo,justdefineasubclassofException/Errorclass.Oursub
classesdo not need toactually implement anything.The Exception/Error classdoes not
defineanymethodsofitsown.Itdoes,ofcourse,inheritmethodsprovidedbyThrowable
class.
Although Java’s built-in exceptions handle most common errors, you will probably
want to create your own exception types to handle situations specific to your
applications.Thisisquiteeasytodo:justdefineasubclassofException(which
is,ofcourse,asubclassofThrowable).
Yoursubclassesdon’tneedtoactuallyimplementanything—itistheirexistencein
thetypesystemthatallowsyoutousethemasexceptions.
TheExceptionclassdoesnotdefineanymethodsofitsown.Itdoes,ofcourse,inherit
those methods provided by Throwable. Thus, all exceptions, including those that you
create,havethemethodsdefinedbyThrowableavailabletothem.
Exceptiondefinesfourconstructors.Twosupportchainedexceptions,describedin
thenextsection.Theothertwoareshownhere:
Exception()
Exception(Stringmsg)
Thefirstformcreatesanexceptionthathasnodescription.Thesecondformlets
youspecifyadescriptionoftheexception.
Although specifying a descriptionwhen an exception is created is often useful,
sometimes it is better to override toString( ). Here’s why: The version of toString()
definedbyThrowable(andinheritedbyException)
first displays the name of the exception followed by a colon, which is then
followed by your description. By overriding toString( ), you can prevent the
exceptionnameandcolonfrombeingdisplayed.Thismakesforacleaneroutput,which
isdesirableinsomecases.
Example11.12
1.classAgeExceptionextendsException
2.{
3.AgeException(Stringmsg)
4.{
5.super(msg);
6.}
7.}
8.classErrorTest12
9.{
10.intage;
11.voidsetAge(inta)throwsInvalidAgeException
12.{
13.if(a>0)
14.age=a;
15.else
16.{
17.AgeExceptione=newAgeException(“InvalidAge”);
18.throwe;
19.}
20.}
21.publicstaticvoidmain(Stringargs[])
22.{
23.ErrorTest12a1=newErrorTest12();
24.try
25.{
26.a1.setAge(20);
27.a1.setAge(-10);
28.}
29.catch(AgeExceptione)
30.{
31.System.out.println(e.getMessage());
32.}
33.}
34.}
Output:
InvalidAge
ThefollowingexampledeclaresanewsubclassofExceptionandthenusesthat
subclass to signal an error condition in a method. It overrides the toString( )
method,allowingacarefullytailoreddescriptionoftheexceptiontobedisplayed.
ThisexampledefinesasubclassofExceptioncalledMyException.Thissubclassis
quite simple: It has only a constructor plus an overridden toString( ) method that
displaysthevalueoftheexception.
TheExceptionDemoclassdefinesamethodnamedcompute()thatthrowsa
MyExceptionobject.Theexceptionisthrownwhencompute()’sintegerparameter
is greater than 10. The main( ) method sets up an exception handler for
MyException,thencallscompute()withalegalvalue(lessthan10)andanillegal
onetoshowbothpathsthroughthecode.
Hereistheresult:
Calledcompute(1)
Normalexit
Calledcompute(20)
CaughtMyException[20]
ChainedExceptions:
Thechainedexceptionfeature allowsustoassociateanother exceptionwithan
exception.Thissecondexceptiondescribesthecauseofthefirstexception.Forexample,
imagine a situation in which a method throws an ArithmeticException because of an
attempttodividebyzero.However,theactualcauseoftheproblemwasthatanI/Oerror
occurred,whichcausedthedivisortobesetimproperly.
AlthoughthemethodmustcertainlythrowanArithmeticException,sincethatis
theerrorthatoccurredWemightalsowanttoletthecallingcodeknowthattheunderlying
causewasasI/Oerror.
Toallowchainedexceptions,Java2,version1.4addedtwoconstructorsandtwo
methodstoThrowableclass.Theconstructorsareshownhere:
Throwable(ThrowablecauseExc)
Throwable(Stringmsg,ThrowablecauseExc)
Inthefirstform,causeExcistheexceptionoccurred.Thesecondformallowsus
to specify a description at the same time that we specify a cause exception. These two
constructorshavealsobeenaddedtotheError,Exception,andRuntimeExceptionclasses.
The chained exception methods added to Throwable class are getCause() and
initCause()
ThrowablegetCause()
ThrowableinitCause(ThrowablecauseExc)
The getCause( ) method returns the exception that underlies the current
exception. If there is no underlying exception, null is returned. The initCause() method
associatescauseExcwiththeinvokingexceptionandreturnsareferencetotheexception.
Thus, we can associate a cause with an exception after the exception has created.
However,thecauseexceptioncanbesetonlyonce.
ThuswecancallinitCause()onlyonceforeachexceptionobject.Furthermore,if
thecauseexceptionwassetbyaconstructor,thenwecannotsetitagainusinginitCause()
method.Ingeneral,initCause()isusedtosetacauseforlegacyexceptionclasseswhich
do not support the two additional constructors described earlier. Most of Java’s built-in
exceptionsdonotdefinetheadditionalconstructors.Thus,wewilluseinitCause()ifwe
needtoaddanexceptionchaintotheseexceptions.
Chainedexceptionsarenotsomethingthateveryprogramwillneed.However,incases
inwhichknowledgeofanunderlyingcauseisuseful,theyofferanelegantsolution.
Example11.13
1.ClassErrorTest13
2.{
3.intage;
4.voidsetAge(inta)
5.{
6.if(a>0)
7.age=a;
8.else
9.{
10.NullPointerExceptione=newNullPointerException(“AdmissionFailed”);
11.e.initCause(newArithmeticException(“Ageisinvalid”));
12.throwe;
13.}
14.}
15.publicstaticvoidmain(Stringargs[])
16.{
17.ErrorTest13a1=newErrorTest13();
18.try
19.{
20.a1.setAge(20);
21.a1.setAge(-10);
22.}
23.catch(NullPointerExceptione)
24.{
25.System.out.println(e.getMessage());
26.System.out.println(e.getCause());
27.}
28.}
29.}
Output:
AdmissionFailed
AgeisInvalid
Inthisexample,thetop-levelexceptionisNullPointerException.Toitisaddeda
cause exception, ArithmeticException. When the exception is thrown out of
demoproc(),itiscaughtbymain().There,thetop-levelexceptionisdisplayed,
followedbytheunderlyingexception,whichisobtainedbycallinggetCause().
Chainedexceptions can be carriedon to whateverdepth isnecessary. Thus,the
causeexception can, itself, have a cause. Be aware that overly long chains of
exceptionsmayindicatepoordesign.Chainedexceptionsarenotsomethingthatevery
programwillneed.However,incasesinwhichknowledgeofanunderlyingcauseis
useful,theyofferanelegantsolution.
ThreeNewJDK7ExceptionFeatures(UPDATED)
JDK7addsthreeinterestingandusefulfeaturestotheexceptionsystem.Thefirst
automatestheprocessofreleasingaresource,suchasafile,whenitisnolonger
needed.
Itisbasedonanexpandedformofthetrystatementcalledtry-with-resources,and
isdescribedinupcomingChapterwhenfilesareintroduced.
Thesecondnewfeatureiscalledmulti-catch,andthethirdissometimesreferred
toasfinalrethrowormorepreciserethrow.Thesetwofeaturesaredescribedhere.
Themulti-catchfeatureallowstwoormoreexceptionstobecaughtbythesamecatch
clause.Itisnotuncommonfortwoormoreexceptionhandlerstousethesame
codesequenceeventhoughtheyrespondtodifferentexceptions.
Insteadofhavingtocatcheachexceptiontypeindividually,nowyoucanusea
singlecatchclausetohandlealloftheexceptionswithoutcodeduplication.
Touseamulti-catch,separateeach exceptiontype inthecatchclausewith theOR
operator.Eachmulti-catchparameterisimplicitlyfinal.(Youcanexplicitlyspecify
final,ifdesired,butitisnotnecessary.)
Because each multi-catch parameter is implicitlyfinal, it can’t be assigneda new
value.
Here is a catch statement that uses the multi-catch feature to catch both
ArithmeticExceptionandArrayIndexOutOfBoundsException:
catch(ArithmeticException|ArrayIndexOutOfBoundsExceptione){
Thefollowingprogramshowsthemulti-catchfeatureinaction:
//DemonstrateJDK7’smulti-catchfeature.
classMultiCatch{
publicstaticvoidmain(Stringargs[]){
inta=10,b=0;
intvals[]={1,2,3};
try{
intresult=a/b;//generateanArithmeticException
//vals[10]=19;//generateanArrayIndexOutOfBoundsException
//Thiscatchclausecatchesbothexceptions.
}catch(ArithmeticException|ArrayIndexOutOfBoundsExceptione){
System.out.println(“Exceptioncaught:”+e);
}
System.out.println(“Aftermulti-catch.”);
}}
The program will generate an ArithmeticException when the division by zero is
attempted. If you comment out the division statement and remove the comment
symbol from the next line, an ArrayIndexOutOfBoundsExceptionis generated. Both
exceptionsarecaughtbythesinglecatchstatement.
The more precise rethrow feature restricts the type of exceptions that can be
rethrowntoonlythosecheckedexceptionsthattheassociatedtryblockthrows,that
arenothandledbyaprecedingcatchclause,andthatareasubtypeorsupertypeof
theparameter.
Althoughthiscapabilitymightnotbeneededoften,itisnowavailableforuse.Forthe
morepreciserethrowfeaturetobeinforce,thecatchparametermustbeeither
effectivelyfinal,whichmeans thatit mustnot beassigned anewvalue insidethe
catchblock,orexplicitlydeclaredfinal.
UsingExceptions
Exception handling provides a powerful mechanism for controlling complex
programsthathavemanydynamicrun-timecharacteristics.Itisimportanttothink
of try, throw, and catch as clean ways to handle errors and unusual boundary
conditionsinyourprogram’slogic.Unlikesomeotherlanguagesinwhicherrorreturn
codesareusedtoindicatefailure,Javausesexceptions.Thus,whenamethodcan
fail,haveitthrowanexception.
This is a cleaner way to handle failure modes. One last point: Java’s exception-
handling statements should not be considered a general mechanism for nonlocal
branching.Ifyoudoso,itwillonlyconfuseyourcodeandmakeithardtomaintain.
TheoryQuestion:
1.Whatisanexception?
2.Howdowedefineatryblock?
3.Howdowedefineacatchblock?
4.Listsomeofthemostcommontypesofexceptionthatmightoccurin
java.GiveExample.
5.Isitessentialtocatchalltypesofexception?
6.Howmanycatchblockscanweusewithonetryblock.
7.Createatryblockthatislikelytogeneratethreetypesofexceptionand
thenincorporatenecessarycatchblocktocatchandhandlethemappropriately.
8.Whatisfinallyblock?Whenandhowisitused?Giveasuitableexample.
9.ExplainhowExceptionhandlingmechanismcanbeusedfordebugginga
program.
CHAPTER
∞12∞
(Multi-ThreadedProgramming)
Introduction-
A thread is a single flow of control within a program. Thread is very much
similartoaprocess.Infactthreadisalsocalledalight-weightprocess.
Threadv/sProcess:
Normally different processes occupy different memory space. When the CPU
shifts from one process to another process, the state of the currently running process is
savedand the stateof anotherprocess isrestored.No usefulwork isbeingdone during
stateswitch.ThecontextswitchtimeshouldbeaslessaspossibletomaximizetheCPU
utilization.
Threadsarealsolikeindependentprocessesbuttheysharethesamememoryand
state.Theseparatethreadsalsohaveseparatestatebutthestateisverysmallascompared
to process state. The state may contain just program counter and stack pointer. So
switchingfromonethreadtoanotherthreadtakesverylittletime.Thusthecontextswitch
timeforthreadsisverysmallascomparedtotheprocess.HenceCPUutilizationishighin
caseofmultiplethreadsascomparedtotheutilizationincaseofmultipleprocesses.
Multi-Threadedprogram:
Amulti-threadedprogramcontainstwoormorepartsthatcanrunconcurrently.
Eachpartofsuchaprogramiscalledathread,andeachthreaddefinesaseparatepathof
execution.Thus,multi-threadingisaspecializedformofmulti-tasking.
Forexample,aprogrammayhavethreethreads:
Onehandlingtheprinting.
Onehandlingtheediting.
OnedownloadingafilefromtheInternet.
AllthesethreadsmightberunningconcurrentlythusmaximizingtheCPUutilization.
Process-basedMulti-tasking:
Mostoftheoperatingsystemsallowustoruntwoormoreprogramsatthesame
time. It is referred to as process-bases multi-tasking. For example, we can run a Java
program and at the same time we may be editing a word document. The process-based
multi-taskingensuresthattherewillbesomeprogramtobeexecutedmostofthetimesoit
increasestheCPUutilization.
Inprocess-basedmulti-tasking,aprogramisthesmallestunitofcodethatcanbe
dispatchedbythescheduler.
Thread-basedmulti-tasking:
Thread is the smallest unit of execution in a thread-based multi-tasking
environment.Aprocesscanbedividedintoanumberofthreadsexecutingconcurrently.
Thisallowsustohandlemorethanonetaskconcurrentlyinasingleprogram.
Forexample, we canedit aworddocument andat the sametime printanother
document. Thread-based multi-tasking improves CPU utilization just like process-based
multi-tasking. But at the same time it effectively speeds up the execution of a single
programbyexecutingitsdifferentpartsconcurrentlyinseparatethreads.
Thusprocessbasedmulti-taskingdealswiththe“bigpicture”,andthread-based
multi-taskinghandlesthedetails.
TheJavaThreadModel:
TheJavarun-timesystemdependsonthreadsformanythings,andalltheclass
librariesaredesignedwithmulti-threadinginmind.Infact,Javausesthreadstoenablethe
entireenvironmenttobeasynchronous.Thishelpsreduceinefficiencybypreventingthe
wasteofCPUcycles.
Single-threaded systems use an approach called an event loop with polling. In
thismodel,asinglethreadofcontrolrunsinaninfiniteloop,pollingasingleeventqueue
todecidewhattodonext.Inasinglethreadedenvironment,whenathreadblocks(thatis,
suspends execution) because it is waiting for some resource, the entire program stops
running.
ThebenefitofJava’smulti-threadingisthatthemainloop/pollingmechanismis
eliminated.WhenathreadblocksinJavaprogram,onlythesinglethreadthatisblocked
pauses,allotherthreadscontinuetorun.
ThreadLifeCycle(ThreadStates):
Threadexistsinseveralstates.Athreadcanberunning.Itcanbereadytorunas
soonasitgetsCPUtime.Arunningthreadcanbesuspended,whichtemporarilysuspends
itsactivity.Asuspendedthreadcanthenberesumed,allowingittopickupwhereitleft
off.Athreadcan beblocked whenwaitingfor aresource. Atanytime,athread canbe
terminated, which halts its execution immediately. Once terminated a thread cannot be
resumed.
1.NewbornState:
Whenwecreateathreadobject,thethreadisbornandissaidtobeinnewborn
state.Thethreadisnotyetscheduledforrunning.
Atthisstate,wecandoonlyoneofthefollowingthingswithit:
1. Scheduleitforrunningusingstart()method.
2. Killitusingstop()method.
Ifscheduled,itmovestorunnablestate.Ifweattempttouseanyothermethodatthis
state,anexceptionwillbethrown.
2.RunnableState:
Therunnablestatemeansthatthethreadisreadyforexecutionandiswaitingfor
theavailabilityoftheprocessor.Thatis,thethreadhasjoinedthequeueofthreadsthatare
waitingforexecution.Ifallthreadsareofequalpriority,thentheyaregiventimeslotsfor
executioninroundrobinfashion.
Thethreadthatrelinquishescontroljoinsthequeueattheendandagainwaitsfor
its run. However, if we want a thread to relinquish control to another thread of equal
prioritybeforeitsturncomes,itcandosobyinvokingtheyield()method.
3.RunningState:
Running means that the processor has given its time to the thread for its
execution.Arunningthreadmayrelinquishitscontrolinoneofthefollowingsituations:
Itstime-sliceisover.
Itispre-emptedbyahigherprioritythread.
Ityieldsi.e.voluntarilyrelinquishescontrol.
Ithascompleteditsexecution.
Itisstoppedbysomeotherthread.
It has been suspended using suspend() method. A suspended thread can be
revivedbyusingtheresume()method.Thisapproachisusefulwhenwewantto
suspendathreadforsometimeduetocertainreason,butdonotwanttokillit.
It has been told to wait until some event occurs. This is done using the wait()
method.Thethreadcanbescheduledtorunagainusingthenotify()method.
ItisperformingsomeI/Ooperation.
4.BlockedState:
A thread is said to be blocked when it is prevented form entering into the
runnable state and subsequently the running state. This happens when the thread is
suspended,sleepingorwaitinginordertosatisfycertainrequirements.Ablockedthreadis
considered“notrunnable”butnotdeadandthereforefullyqualifiedtorunagain.
5.DeadState:
Every thread has a life cycle. A running thread ends its life when it has
completed executing its run() method. It has a natural death. However, we kill it by
sendingthestopmessagetoitatanystatethuscausingaprematuredeath.Athreadcanbe
killed as soon as it is born, or while it is running, or even when it is in “not runnable”
(blockedcondition).
ThreadPriorities:
Javaassignstoeachthreadaprioritythatdetermineshowthatthreadshouldbe
treated with respect to the others. Thread priorities are integers that specify the relative
priorityofonethreadtoanother.
Asanabsolutevalue,apriorityismeaningless;ahigherprioritythreaddoesnot
run any faster than a lower-priority thread if it is the only thread running. Instead, a
thread’spriorityisusedtodecidewhentoswitchfromonerunningthreadtonext.Thisis
called a context switch. The rules that determine when a context switch takes place are
simple:
Athreadcanvoluntarily(onitsown)relinquishcontrol.Thisisdonebyexplicitly
yielding,sleepingorblockingorpendingI/O.Inthisscenario,allotherthreads
are examined, and normally the highest-priority thread that is ready to run is
giventheCPU.
A thread can be pre-empted by a higher-priority thread. In this case, a lower
prioritythreadthatdoesnotyieldtheprocessorissimplypre-emptednomatter
whatitisdoing,byahigherprioritythread.Basically,assoonasahigher-priority
threadwantstorun,itdoes.Thisiscalledpreemptivemultitasking.
SomeOSsupportnon-preemptiveprioritybasedscheduling.Insuchcaseahigh
prioritythreadgetschanceonlywhenlowprioritythreadcompletes.
IncaseswheretwothreadswiththesamepriorityarecompetingforCPUcycles,
thesituationisabitcomplicated.ForOSsuchaswindows98,threadsofequal
prioritymustvoluntarily(ontheirown)yield(giveup)controltotheirpeers.If
theydonot,theotherthreadswillnotrun.
Note:- Problems can arise from the differences in the way that O.S.’s context-switch
threadsofequalpriority.
Synchronization:
Because multi-threading introduces as asynchronous behavior to our programs,
theremustbeawayforustoenforcesynchronizationwhenweneedit.Forexample,if
we want two threads to communicate and share a complicated data structure, such as a
linkedlist,weneedsomewaytoensurethattheydonotconflictwitheachother.
Thatis,wemustpreventonethreadfromwritingdatawhileanotherthreadisin
themiddleofreadingit.Javausesmonitorforinter-threadsynchronization.Wecanthink
of a monitor as a very small box that can hold only one thread. Once a thread enters a
monitorcanbeusedtoprotectasharedassetfrombeingmanipulatedbymorethanone
threadatatime.
Mostmulti-threadedsystemsexposeasobjectsthatourprogrammustexplicitly
acquireandlock.Javaprovidesacleanersolution.
Thereisnoclass“monitor”,instead,eachobjecthasitsownimplicitmonitorthat
isautomaticallyenteredwhenoneoftheobject’ssynchronizedmethodiscalled.Oncea
threadisinsideasynchronizedmethod,nootherthreadcancallanyothersynchronized
methodonthesameobject.Thisenablesustowriteveryclearandconcisemulti-threaded
code,becausesynchronizationsupportisbuiltintothelanguage.
Messaging:Whenprogrammingwithmostotherlanguages,wemustdependontheO.S.
toestablishcommunicationbetweenthreads.
This,ofcourse,addsoverhead.Bycontrast,Javaprovidesaclean,low-costway
for two or more threads to talk to each other, via calls to predefined methods that all
objectshave.Java’smessagingsystemallowsathreadtoentersynchronizedmethodonan
object,andthenwaitthereuntilsomeotherthreadexplicitlynotifiestocomeout.
TheThreadclassandtheRunnableinterface:
Java’smulti-threadingsystemisbuiltupontheThreadclass,itsmethods,andits
companioninterface,Runnable.Thisclassbelongstopackagejava.langandhencethereis
noneedofexplicitlyimportingit.
Threadencapsulatesathreadofexecution,sincewecannotdirectlyrefertotheinternal
stateofarunningthread,wewilldealwithitthroughitsproxy,theThreadinstancethat
spawned it. To create a new thread our program will either extend Thread class or
implement the Runnable interface. The Thread class defines several methods that help
managethreads:
StringgetName()
Returnsthisthread’sname
intgetPriority()
Returnsthisthread’spriority
booleanisAlive()
Testsifthisthreadisstillrunning
voidjoin()
Waitsforthisthreadtodie(terminate)
voidrun()
If this thread was constructed using a separate Runnable object, then that Runnable
object’srunmethodiscalled;otherwise,thismethoddoesnothingandreturns,ifthread
classisextendedandrun()methodisoverriddeninsub-classthentheoverriddenrun()
methodiscalled.
voidsetName(Stringname)
Changesthenameofthisthreadtobeequaltotheargumentname
staticvoidsleep(longmillis)throwsInterruptedException
Causes the currently executing thread to sleep (temporarily cease execution) for the
specifiednumberofmilliseconds.(1sec=1000ms)
staticvoidsleep(longmillis,intnanos)throwsInterruptedException
Causes the currently executing thread to sleep (cease execution) for the specified
numberofmillisecondsplusthespecifiednumberofnanoseconds.
voidstart()
Causesthisthreadtobeginexecution,theJavaVirtualMachinecallstherunmethodof
thisthread.
staticvoidyield()
Causes the currently executing thread object to temporarily pause and allow other
threadstoexecute.
staticThreadcurrentThread()
Returnsareferencetothecurrentlyexecutingthreadobject.
Themainthread:
WhenaJavaprogramstartsup,onethreadbeginsrunningimmediately.Thisis
usuallycalledthemainthreadofourprogram,becauseitistheonethatisexecutedwhen
ourprogrambegins.Themainthreadisthethreadfromwhichother“child”threadsare
created.
Althoughthemainthreadiscreatedautomaticallywhenourprogramisstarted,it
canbecontrolledthroughaThreadobject.Todoso,wemustobtainareferencetoitby
callingthemethodcurrentThread(),whichispublicstaticmemberofThreadclass.
Thismethodreturnsareferencetothethreadinwhichitiscalled.Oncewehave
referencetothemainmethod,wecancontrolitjustlikeanyotherthread.
Example12.1
The following example demonstrates how we can acquire reference of main thread and
thenaccessitspropertiesusingmethodsofThreadclass.
1.classCurrentThreadTest
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.Threadt=Thread.currentThread();
6.System.out.println(“Currentthread:”+t);
7.System.out.println(“Name:”+t.getName());
8.System.out.println(“Priority:”+t.getPriority());
9.t.setName(“MyThread”);
10.t.setPriority(Thread.MAX_PRIORITY);
11.System.out.println(“Afternameandprioritychange:”+t);
12.System.out.println(“Name:”+t.getName());
13.System.out.println(“Priority:”+t.getPriority());
14.for(intn=1;n<=5;n++)
15.{
16.System.out.println(n);
17.try
18.{
19.Thread.sleep(1000);
20.}
21.catch(InterruptedExceptione)
22.{
23.System.out.println(“Mainthreadinterrupted”);
24.}
25.}
26.}
27.}
Output:
Currentthread:Thread[main,5,main]
Name:main
Priority:5
Afternameandprioritychange:Thread[MyThread,10,main]
Name:MyThread
Priority:10
1
2
3
4
5
Note1:Thesleep()methodinThreadmightthrowanInterruptedException,whichisa
checked exception. This would happen if some other thread wanted to interrupt this
sleepingone.
Note2:Noticetheoutputproducedwhent(threadreference)isusedasanargumentto
println().Thiswilldisplayinorder:thenameofthethread,itspriority,andthenameofits
group.Itspriorityis5,whichisthedefaultvalue,andmainisalsothenameofthegroup
ofthreadtowhichthisthreadbelongs.Athreadgroupisadatastructurethatcontrolsthe
sateofacollectionofthreadsasawhole.
CreatingaThread:
Inthemost generalsense,we createathreadbyinstantiatingan objectoftype
Thread.Javaidentifiestwowaysinwhichthiscanbeaccomplished:
1. WecanimplementtheRunnableinterface
2. WecanextendstheThreadclass,itself.
ImplementingRunnable:
The easiest way to create a thread is to create a class that implements the
Runnable interface. To implement Runnable, a class need only implement a single
methodcalledrun().
publicvoidrun()
Insiderun()method,wewilldefinethecodethatconstitutesthenewthread.The
run()cancallothermethods,useotherclassesand declarevariables,justlikethemain
thread.
The only difference is that run( ) establishes the entry point for another,
concurrent thread of execution within our program. This thread will end when run( )
returns.
AfterwecreateaclassthatimplementsRunnable,wewillinstantiateanobjectof
typeThreadfromwithinthatclassusingoneofthefollowingconstructors:
Thread(RunnablethreadObj)
Thread(RunnablethreadObj,StringthreadName)
HerethreadObjistheobjectwhoserunmethodiscalledandthreadNameisthe
nameofthenewthread.Afterthenewthreadiscreated,itwillnotstartrunninguntilwe
callstart()method.
Thestart()methodputsthethreadinthereadyqueue(runnablestate).Whenever
thethreadgetsscheduleditsexecutionwillstartfromtherun()method.
Example12.2
1.classAimplementsRunnable
2.{
3.publicvoidrun()
4.{
5.for(inti=1;i<=5;i++)
6.{
7.System.out.println(“ChildThread:”+i);
8.}
9.System.out.println(“Exitingchildthread”);
10.}
11.}
12.classRunnableTest
13.{
14.publicstaticvoidmain(Stringargs[])
15.{
16.Aa1=newA();
17.Threadt1=newThread(a1,”DemoThread”);
18.t1.start();
19.System.out.println(“Mainthreadexiting”);
20.}
21.}
Output:
Mainthreadexiting
ChildThread:1
ChildThread:2
ChildThread:3
ChildThread:4
ChildThread:5
Exitingchildthread
Example12.3
1.classAimplementsRunnable
2.{
3.Threadt;
4.A()
5.{
6.t=newThread(this,“DemoThread”);
7.System.out.println(“Childthread:“+t);
8.t.start();
9.}
10.publicvoidrun()
11.{
12.for(inti=1;i<=5;i++)
13.{
14.System.out.println(“ChildThread:”+i);
15.try
16.{
17.Thread.sleep(500);
18.}
19.catch(InterruptedExceptione)
20.{
21.System.out.println(e);
22.}
23.}
24.System.out.println(“ExitingChildthread”);
25.}
26.}
27.classRunnableTest2
28.{
29.publicstaticvoidmain(Stringargs[])
30.{
31.Aa1=newA();
32.for(inti=1;i<=5;i++)
33.{
34.System.out.println(“MainThread:”+i);
35.try
36.{
37.Thread.sleep(1000);
38.}
39.catch(InterruptedExceptione)
40.{
41.System.out.println(“mainthreadinterrupted”);
42.}
43.}
44.System.out.println(“EndofMainthread”);
45.}
46.}
Output:
Childthread:Thread[DemoThread,5,main]
MainThread:1
ChildThread:1
ChildThread:2
MainThread:2
ChildThread:3
ChildThread:4
MainThread:3
ChildThread:5
ExitingChildthread
MainThread:4
MainThread:5
EndofMainthread
ExtendingThreadclass:
ThesecondwaytocreateathreadistocreateanewclassthatextendsThread,
andthentocreateaninstanceofthatclass.Theextendingclassmustoverridetherun()
method, which is the entry point for the new thread. It must also call start() to being
executionofthenewthread.
Example12.4
1.classAextendsThread
2.{
3.A()
4.{
5.super(“TestThread”);
6.System.out.println(“Childthread:”+this);
7.start();
8.}
9.publicvoidrun()
10.{
11.for(inti=1;i<=5;i++)
12.{
13.System.out.println(“ChildThread:”+i);
14.try
15.{
16.sleep(500);
17.}
18.catch(InterruptedExceptione)
19.{
20.System.out.println(“Childthreadinterrupted”);
21.}
22.}
23.System.out.println(“ExitingChildthread”);
24.}
25.}
26.classThreadTest
27.{
28.publicstaticvoidmain(Stringargs[])
29.{
30.newA();
31.for(inti=1;i<=5;i++)
32.{
33.System.out.println(“MainThread:“+i);
34.try
35.{
36.Thread.sleep(1000);
37.}
38.catch(InterruptedExceptione)
39.{
40.System.out.println(“Mainthreadinterrupted”);
41.}
42.}
43.System.out.println(“Mainthreadexiting”);
44.}
45.}
Output:
Childthread:Thread[TestingThread,5,main]
MainThread:1
ChildThread:1
ChildThread:2
MainThread:2
ChildThread:3
ChildThread:4
MainThread:3
ChildThread:5
ExitingChildthread
MainThread:4
MainThread:5
Mainthreadexiting
Note:-IfThreadisnotassignedanyname,itwillbesomethinglike:Thread-1,Thread-2,
Thread-3etc.
ChoosinganApproach:
The thread class defines several methods that can be overridden by a derived
class.Outofthesemethods,theonlyonethatmustoverriddenisrun().Thatis,ofcourse
thesamemethodrequiredwhenweimplementtheRunnableinterface.
ManyJavaprogrammersfeelthatclassesshouldbeextendedonlywhentheyare
beingenhancedormodifiedinsomeway.So,ifwewillnotbeoverridinganyofThread’s
othermethods,itisprobablybestsimplytoimplementRunnableinterface.
CreatingMultipleThreads:
Example12.5
1.classAimplementsRunnable
2.{
3.Stringname;
4.Threadt;
5.A(StringthreadName)
6.{
7.name=threadName;
8.t=newThread(this,name);
9.System.out.println(“Childthread:”+t);
10.t.start();
11.}
12.publicvoidrun()
13.{
14.for(inti=1;i<=5;i++)
15.{
16.System.out.println(t.getName()+“:”+i);
17.try
18.{
19.Thread.sleep(1000);
20.}
21.catch(InterruptedExceptione)
22.{
23.System.out.println(e);
24.}
25.}
26.System.out.println(name+“Exiting”);
27.}
28.}
29.classMultiThreadTest
30.{
31.publicstaticvoidmain(Stringargs[])
32.{
33.Aa1=newA(“One”);
34.Aa2=newA(“Two”);
35.Aa3=newA(“Three”);
36.try
37.{
38.Thread.sleep(10000);
39.}
40.catch(InterruptedExceptione)
41.{
42.System.out.println(“mainthreadinterrupted”);
43.}
44.System.out.println(“Mainthreadexiting”);
45.}
46.}
Output:
Childthread:Thread[One,5,main]
Childthread:Thread[Two,5,main]
Childthread:Thread[Three,5,main]
One:1
Two:1
Three:1
One:2
Two:2
Three:2
One:3
Two:3
Three:3
One:4
Two:4
Three:4
One:5
Two:5
Three:5
OneExiting
TwoExiting
ThreeExiting
Mainthreadexiting
ImposingsomeOrderingbyusingisAlive()andjoin()Methods:
Oftenwewillwantthemainthreadtofinishlast.Onewaytoachievethisisto
callsleep()withinmain.Thisisrathercrude(rough)way.Twowaysexisttodetermine
whetherathreadhasfinished.First,wecancallisAlive()on thethread.Thismethodis
definedbyThread,anditsgeneralformis:
finalbooleanisAlive()
The isAlive() method returns true if the thread upon which it is called is still
running.Itreturnsfalseotherwise.WhileisAlive()isoccasionallyuseful,themethodthat
wewillmorecommonlyusetowaitforathreadtofinishiscalledjoin(),shownhere:
finalvoidjoin()throwsInterruptedException
This method waits until the thread on which it is called terminates. Additional
formsofjoin()allowsustospecifyamaximumamountoftimethatwewanttowaitfor
thespecifiedthreadtoterminate.
Thefollowingexamplemakesuseofjoin()toensurethatthemainthreadisthe
lasttostop.ItalsodemonstratestheisAlive()method.
Example12.6
1.classAimplementsRunnable
2.{
3.Stringname;
4.Threadt;
5.A(StringthreadName)
5.{
6.name=threadName;
7.t=newThread(this,name);
8.System.out.println(“Childthread:”+t);
9.t.start();
10.}
11.publicvoidrun()
12.{
13.for(inti=1;i<=5;i++)
14.{
15.System.out.println(name+“:”+i);
16.try
17.{
18.Thread.sleep(1000);
19.}
20.catch(InterruptedExceptione)
21.{
22.System.out.println(e);
23.}
24.}
25.System.out.println(name+“Exiting”);
26.}
27.}
28.classDemoJoin
29.{
30.publicstaticvoidmain(Stringargs[])
31.{
32.Aob1=newA(“One”);
33.Aob2=newA(“Two”);
34.Aob3=newA(“Three”);
35.System.out.println(“ThreadOneisalive?:”+ob1.t.isAlive());
36.System.out.println(“ThreadTwoisalive?:”+ob2.t.isAlive());
37.System.out.println(“ThreadThreeisalive?:”+ob3.t.isAlive());
38.try
39.{
40.ob3.t.join();
41.ob2.t.join();
42.ob1.t.join();
43.}
44.catch(InterruptedExceptione)
45.{
46.System.out.println(“mainthreadinterrupted”);
47.}
48.System.out.println(“ThreadOneisalive?:”+ob1.t.isAlive());
49.System.out.println(“ThreadTwoisalive?:”+ob2.t.isAlive());
50.System.out.println(“ThreadThreeisalive?:”+ob3.t.isAlive());
51.System.out.println(“Mainthreadexiting”);
52.}
53.}
Output:
Childthread:Thread[One,5,main]
Childthread:Thread[Two,5,main]
Childthread:Thread[Three,5,main]
ThreadOneisalive?:true
ThreadTwoisalive?:true
ThreadThreeisalive?:true
One:1
Two:1
Three:1
One:2
Two:2
Three:2
One:3
Two:3
Three:3
One:4
Two:4
Three:4
One:5
Two:5
Three:5
OneExiting
TwoExiting
ThreeExiting
ThreadOneisalive?:false
ThreadTwoisalive?:false
ThreadThreeisalive?:false
Mainthreadexiting
ThreadPriorities:
Thread priorities are used by the thread scheduler to decide when each thread
should be allowed to run. Higher priority thread will be scheduled first as compared to
lowerprioritythread.Ahigherprioritythreadcanalsopreemptalower-priorityone.For
instance, when a lower-priority thread is running and a higher-priority thread resumes
fromsleepingorwaitingonI/O,forexample,itwillpreemptthelower-prioritythread.
Intheory,threadsofequalpriorityshouldgetequalaccesstotheCPU.Butjava
is designed to work in a wide range of environments. Some of those environment
implements multi-tasking fundamentally different than others? For safety, threads that
sharethesamepriorityshouldyieldcontrolonceinawhile.
Thisensuresthatallthreadshaveachancetorununderanon-preemptiveOSIn
practice, even in non-preemptive environments, most threads inevitably (certainly)
encounter some blocking situation, such as waiting for I/O. When this happens, the
blocked thread is suspended and other threads can run. For CPU intensive threads, we
shouldmakesurethatityieldscontroloccasionally,sothatotherthreadscanrun.
Tosetathread’spriority,usethesetPriority()method,whichisamemberofThread.Its
generalformis:
finalvoidsetPriority(intlevel)
The value of level must be within the range Thread.MIN_PRIORITY and
Thread.MAX_PRIORITY.Currently,thesevaluesare1and10,respectively.Toreturna
threadtodefaultpriority,specifyThread.NORM_PRIORITY,whichiscurrently5.These
prioritiesaredefinedasfinalvariableswithinThreadclass.
We can obtain the current priority setting by calling the getPriority() method of Thread
class,shownhere:
finalvoidgetPriority()
Implementations of Java have radically different behavior when it comes to
scheduling. The windows XP/98/NT/2000 versions work more or less as we would
expect.However,otherversions mayworkquitedifferently.Mostof theinconsistencies
arise when we have threads that are relying on preemptive behavior, instead of
cooperatively giving up CPU time. The safest way to obtain predictable, cross-platform
behaviorwithJavaistousethreadsthatvoluntarilygiveupcontroloftheCPU.
Thefollowingexampledemonstratestwothreadsatdifferentpriorities,whichdo
not run on a preemptive platform in the same way as they run on a non–preemptive
platform.
Example12.7
1.classClickerimplementsRunnable
2.{
3.longclick=0;
4.Threadt;
5.volatilebooleanrunning=true;
6.Clicker(intp)
7.{
8.t=newThread(this);
9.t.setPriority(p);
10.}
11.publicvoidrun()
12.{
13.while(running)
14.{
15.click++;
16.}
17.}
18.voidstop()
19.{
20.running=false;
21.}
22.voidstart()
23.{
24.t.start();
25.}
26.}
27.classHiLoPri
28.{
29.publicstaticvoidmain(Stringargs[])
30.{
31.Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
32.Clickerhi=newClicker(Thread.NORM_PRIORITY+1);
33.Clickerlo=newClicker(Thread.NORM_PRIORITY-1);
34.lo.start();hi.start();
35.try
36.{
37.Thread.sleep(10000);
38.}
39.catch(InterruptedExceptione)
40.{
41.System.out.println(e);
42.}
43.lo.stop();hi.stop();
44.try
45.{
46.hi.t.join();
47.lo.t.join();
48.}
49.catch(InterruptedExceptione)
50.{
51.System.out.println(e);
52.}
53.System.out.println(“Low:“+lo.click);
54.System.out.println(“High:“+hi.click);
55.}
56.}
Output:
Low:63660819
High:2086505403
Thehigherprioritythreadgetsmorethan98%oftheCPUtime.Butthreadsdid
context switch, even though neither voluntarily yielded the CPU nor blocked for I/O.
Whenthissameprogramisrununderanon-preemptivesystem,differentresultswillbe
obtained.
Note:-Variable running is preceded by the keyword volatile to ensure that the value of
runningisexaminedeachtimethefollowingloopiterates.
while(running)
{
click++;
}
Withouttheuseofvolatile,Javaisfreetooptimizetheloopinsuchawaythata
localcopyofrunningiscreated.Theuseofvolatilepreventstheoptimization,tellingJava
thatrunningmaychangeinwaysnotdirectlyapparentintheimmediatecode.
Synchronization:
Whentwoormorethreadsneedaccesstoasharedresource,theyneedsomeway
toensurethattheresourcewillbeusedbyonlyonethreadatatime.Theprocessbywhich
thisisachievediscalledsynchronization.
Keytosynchronizationistheconceptofthemonitor(alsocalledasemaphone).
Amonitorisanobjectthatisusedasamutuallyexclusivelock.Onlyonethreadcanown
amonitoratagiventime.
Whenathreadacquiresalock,itissaidto haveenteredthemonitor.Allother
threadsattemptingtoenterthelockedmonitorwillbesuspendeduntilthefirstthreadexits
themonitor.Theseotherthreadsaresaidtobewaitingforthemonitor.Athreadthatowns
amonitorcanreenterthe samemonitorifitsodesires. wecansynchronizeourcodein
eitheroftwoways:
(i)Usingsynchronizedmethods
(ii)Usingsynchronizedstatements
UsingSynchronizedMethod:
Synchronization is easy in Java, because all objects have their own implicit
monitor associated with them. To enter an object’s monitor, just call a method that has
been modified with the synchronized keyword. While a thread is inside a synchronized
method,allotherthreadsthattrytocallit(oranyothersynchronizedmethod)onthesame
instancehavetowait().Toexitthemonitorandrelinquishcontroloftheobjecttothenext
waitingthread,theownerofthemonitorsimplyreturnsfromthesynchronizedmethod.
Example12.8
Followingprogramillustratesthatoutputgeneratedbythreethreadsgetsmixed-upasthey
arerunningconcurrently.
1.classA
2.{
3.voiddisplay(Stringmsg)
4.{
5.System.out.print(“[”+msg);
6.try
7.{
8.Thread.sleep(1000);
9.}
10.catch(InterruptedExceptione)
11.{
12.System.out.println(e);
13.}
14.System.out.println(“]”);
15.}
16.}
17.classBimplementsRunnable
18.{
19.Aobj;
20.Stringmsg;
21.Threadt;
22.B(Aobj1,Stringm)
23.{
24.msg=m;
25.obj=obj1;
26.t=newThread(this);
27.t.start();
28.}
29.publicvoidrun()
30.{
31.obj.display(msg);
32.}
33.}
34.classSynch1
35.{
36.publicstaticvoidmain(Stringargs[])
37.{
38.Aa1=newA();
39.Bb1=newB(a1,“Hello”);
40.Bb2=newB(a1,“World”);
41.Bb3=newB(a1,“Matrix”);
42.}
43.}
Output:
[Hello[World[Matrix]
]
]
Aswecansee,bycallingsleep(),thecall()methodallowsexecutiontoswitchtoanother
thread.Thisresultsinthemixed-upoutputofthethreemessagestrings.Inthisprogram,
nothingexiststostopallthreethreadsfromcallingthesamemethod,onthesameobject,
atthesametime.
Thisisknownasaracecondition,becausethesethreethreadsareracingwitheachother
to complete the method. This example uses sleep() to make the effects repeatable and
obvious.Inmostsituations,araceconditionismoresubtleandlesspredictable,because
wecannotbesurewhenthecontextswitchwilloccur.Thiscancausea programtorun
rightonetimeandwrongthenexttime.
To do this, we simply need to precede method display()’s definition with the
keyword synchronized. This prevents either threads from entering the display() while
anotherthreadisusingit.
Example12.9
The problem of mixed-up is solved simply by declaring the method call() as a
synchronizedmethod.
1.classA
2.{
3.synchronizedvoiddisplay(Stringmsg)
4.{
5.System.out.print(“[”+msg);
6.try
7.{
8.Thread.sleep(1000);
9.}
10.catch(InterruptedExceptione)
11.{
12.System.out.println(e);
13.}
14.System.out.println(“]”);
15.}
16.}
17.classBimplementsRunnable
18.{
19.Aobj;
20.Stringmsg;
21.Threadt;
22.B(Aobj1,Stringm)
23.{
24.msg=m;
25.obj=obj1;
26.t=newThread(this);
27.t.start();
28.}
29.publicvoidrun()
30.{
31.obj.display(msg);
32.}
33.}
34.classSynch2
35.{
36.publicstaticvoidmain(Stringargs[])
37.{
38.Aa1=newA();
39.Bb1=newB(a1,“Hello”);
40.Bb2=newB(a1,“World”);
41.Bb3=newB(a1,“Matrix”);
42.}
43.}
Output:
[Hello]
[World]
[Matrix]
Note:-Onceathreadentersanysynchronizedmethodonaninstance,nootherthreadcan
enteranyothersynchronizedmethodonthesameinstance.However,non-synchronized
methodsonthatinstancewillcontinuetobecallable.
UsingSynchronizedStatement:
Whilecreatingsynchronizedmethodswithinclassesthatwecreateisaneasyand
effectivemeansofachievingsynchronization,itwillnotworkinallcases.Tounderstand
why,considerthefollowing.Imaginethatwewanttosynchronizeaccesstoobjectsofa
class that was not designed for multi-threaded access. That is, the class does not use
synchronizedmethods.Further,thisclasswasnotcreatedbywe,butbyathirdpart;and
wedonothaveaccesstothesourcecode.Thus,wecannotaddmodifiersynchronizedto
the appropriate methods within the class. How can access to an object of this class by
synchronized?
The solution is to put calls to the methods defined by this class inside a
synchronizedblock.Thegeneralformofthesynchronizedstatementis:
synchronized(object)
{
//statementstobesynchronized
}
Here, object is a reference to the object being synchronized. A synchronized
block ensures that a call to a method that is a member of object occurs only often the
currentthreadhassuccessfullyenteredobject’smonitor.
Example12.10
Alternativeversionoftheprecedingexample,usingasynchronizedblockwithintherun()
1.classA
2.{
3.voiddisplay(Stringmsg)
4.{
5.System.out.print(“[”+msg);
6.try
7.{
8.Thread.sleep(1000);
9.}
10.catch(InterruptedExceptione)
11.{
12.System.out.println(e);
13.}
14.System.out.println(“]”);
15.}
16.}
17.classBimplementsRunnable
18.{
19.Aobj;
20.Stringmsg;
21.Threadt;
22.B(Aobj1,Stringm)
23.{
24.msg=m;
25.obj=obj1;
26.t=newThread(this);
27.t.start();
28.}
29.publicvoidrun()
30.{
31.synchronized(obj)
32.{
33.obj.display(msg);
34.}
35.}
36.}
37.classSynch3
38.{
39.publicstaticvoidmain(Stringargs[])
40.{
41.Aa1=newA();
42.Bb1=newB(a1,“Hello”);
43.Bb2=newB(a1,“World”);
44.Bb3=newB(a1,“Matrix”);
45.}
46.}
Output:-
[Hello]
[World]
[Matrix]
MultipleThreadsInvokingsameMethodonDifferentObjects:
Example12.11
Threadscancallthesamesynchronizedinstancemethodondifferentobjectsofsameclass
concurrentlyaseachobjecthasadifferentlock.Thiswillagainleadtomixed-upoutput.
1.classA
2.{
3.synchronizedvoiddisplay(Stringmsg)
4.{
5.System.out.print(“[”+msg);
6.try
7.{
8.Thread.sleep(1000);
9.}
10.catch(InterruptedExceptione)
11.{
12.System.out.println(e);
13.}
14.System.out.println(“]”);
15.}
16.}
17.classBimplementsRunnable
18.{
19.Aobj;
20.Stringmsg;
21.Threadt;
22.B(Aobj1,Stringm)
23.{
24.msg=m;
25.obj=obj1;
26.t=newThread(this);
27.t.start();
28.}
29.publicvoidrun()
30.{
31.obj.display(msg);
32.}
33.}
34.classSynch4
35.{
36.publicstaticvoidmain(Stringargs[])
37.{
38.Aa1=newA();
39.Aa2=newA();
40.Aa3=newA();
41.Bb1=newB(a1,“Hello”);
42.Bb2=newB(a2,“World”);
43.Bb3=newB(a3,“Matrix”);
44.}
45.}
Output:
[Hello[World[Matrix]
]
]
UsingStaticSynchronizedMethod:
Example12.12
The output does not get mixed-up in the following example although we are calling
display() method on different objects. The reason is that method display() is static and
hencethelockisobtainedfortheclassAasawholeandnotontheindividualobjects.
1.classA
2.{
3.staticsynchronizedvoiddisplay(Stringmsg)
4.{
5.System.out.print(“[”+msg);
6.try
7.{
8.Thread.sleep(1000);
9.}
10.catch(InterruptedExceptione)
11.{
12.System.out.println(e);
13.}
14.System.out.println(“]”);
15.}
16.}
17.classBimplementsRunnable
18.{
19.Aobj;
20.Stringmsg;
21.Threadt;
22.B(Aobj1,Stringm)
23.{
24.msg=m;
25.obj=obj1;
26.t=newThread(this);
27.t.start();
28.}
29.publicvoidrun()
30.{
31.obj.display(msg);
32.}
33.}
34.classSynch5
35.{
36.publicstaticvoidmain(Stringargs[])
37.{
38.Aa1=newA();
39.Aa2=newA();
40.Aa3=newA();
41.Bb1=newB(a1,“Hello”);
42.Bb2=newB(a2,“World”);
43.Bb3=newB(a3,“Matrix”);
44.}
45.}
Output:-
[Hello]
[World]
[Matrix]
Inter-threadCommunication:
It is discussed earlier, multi-threading replaces event loop programming by
dividingourtasksintodiscreteandlogicalunits.Threadsalsoprovedasecondarybenefit:
theydoawaywithpolling.Pollingisusuallyimplementedbyaloopthatisusedtocheck
someconditionrepeatedly.Oncetheconditionistrue,appropriateactionistaken.
ThiswastestheCPUcycles.Forexample,considertheclassicqueuingproblem,
where one thread is producing some data and another is consuming it. To make the
problem more interacting, suppose that the producer has to wait until the consumer has
finished before it generates more data. In a polling system, the consumer would waste
many CPU cycles while it waited for the producer to produce. Once the producer was
finished, it would start polling, wasting more CPU cycles waiting for the consumer to
finish,andsoon.
To avoid polling, Java includes an elegant (smart) inter-process communication
mechanism via the wait(), notify(), and notifyAll() methods. These methods are
implementedasfinalmethodsinObjectclass,soallclasseshavethem.Allthreemethods
canbecalledonlyfromwithinasynchronizedcontext.Therearecertainrulesforusing
thesemethods.
Wait() tells the calling thread to give up the monitor and go to sleep until some other
threadentersthesamemonitorandcallsnotify().
Notify()wakesuponethread(normallyfirstthread)thatcalledwaitonthesameobject.
notifyAll()wakesupallthethreadsthatcalledwait()onthesameobject.Normallythe
highestprioritythreadwillrunfirst.
ThesemethodsaredeclaredwithinObjectclass,asshownhere:
finalvoidwait()throwsInterruptedException
finalvoidnotify()
finalvoidnotifyAll()
Example12.13
The following sample program incorrectly implements a simple form of the
producer/consumerproblem.Itconsistsfourclasses:Q,thequeuethatwearetryingto
synchronize;Producer,thethreadedobjectthatisproducingqueueentries;Consumer,the
threadedobjectthatisconsuminggqueueentries;andPC,thetinyclassthatcreatesthe
singQ,Producer,andConsumer.
1.classQ
2.{
3.intn;
4.synchronizedintget()
5.{
6.System.out.println(“Got:”+n);
7.returnn;
8.}
9.synchronizedvoidput(intn)
10.{
11.this.n=n;
12.System.out.println(“Put:”+n);
13.}
14.}
15.classProducerimplementsRunnable
16.{
17.Qq1;
18.Producer(Qq2)
19.{
20.q1=q2;
21.newThread(this,”Producer”).start();
22.}
23.publicvoidrun()
24.{
25.inti=0;
26.while(true)
27.{
28.q1.put(++i);
29.}
30.}
31.}
32.classConsumerimplementsRunnable
33.{
34.Qq1;
35.Consumer(Qq2){
37.q1=q2;
38.newThread(this,”Consumer”).start();
39.}
40.publicvoidrun()
41.{
42.while(true)
43.{
44.q1.get();
45.}
46.}
47.}
48.classPC
49.{
50.publicstaticvoidmain(Stringargs[])
51.{
52.Qq1=newQ();
53.newProducer(q1);
54.newConsumer(q1);
55.System.out.println(“PressControl-Ctostop”);
56.}
57.}
Althoughtheput()andget()methodsonQaresynchronized,nothingstopstheproducer
fromoverrunningtheconsumer,norwillanythingstoptheconsumerfromconsumingthe
samequeuevaluetwice.Thuswemaygeterroneousoutputasshownbelow:
Output:PressControl-Ctostop
Put:1
Put:2
Put:3
Put:4
Put:5
Put:6
Put:7
Got:7
Got:7
Got:7
Got:7
Got:7
Got:7
Got:7
Got:7
Put:8
Put:9
Put:10
Put:11
Put:12
Put:13
Put:14
Put:15
Got:15
Got:15
Got:15
Got:15
Got:15
Got:15
Got:15
Example12.14
TheproperwaytowritethisprograminJavaistouse wait()andnotify()to signalin
bothdirections,asshownhere:
1.classQ
2.{
3.intn;
4.booleanvalueSet=false;
5.synchronizedintget()
6.{
7.if(!valueSet)
8.{
9.try
10.{
11.wait();
12.}
13.catch(InterruptedExceptione)
14.{
15.System.out.println(e);
16.}
17.}
18.System.out.println(“Got:”+n);
19.valueSet=false;
20.notify();
21.returnn;
22.}
23.synchronizedvoidput(intn)
24.{
25.if(valueSet)
26.{
27.try
28.{
29.wait();
30.}
31.catch(InterruptedExceptione)
32.{
33.System.out.println(e);
34.}
35.}
36.this.n=n;
37.valueSet=true;
38.System.out.println(“Put:”+n);
39.notify();
40.}
41.}
42.classProducerimplementsRunnable
43.{
44.Qq1;
45.Producer(Qq2)
46.{
47.q1=q2;
48.newThread(this,“Producer”).start();
49.}
50.publicvoidrun()
51.{
52.inti=0;
53.while(true)
54.{
55.q1.put(++i);
56.}
57.}
58.}
59.classConsumerimplementsRunnable
60.{
61.Qq1;
62.Consumer(Qq2)
63.{
64.q1=q2;
65.newThread(this,“consumer”).start();
66.}
67.publicvoidrun()
68.{
69.while(true)
70.{
71.q1.get();
72.}
73.}
74.}
75.classPC2
76.{
77.publicstaticvoidmain(Stringargs[])
78.{
79.System.out.println(“PressControl-Ctostop”);
80.Qq1=newQ();
81.newProducer(q1);
82.newConsumer(q1);
83.}
84.}
Output:
PressControl-Ctostop
Put:1
Got:1
Put:2
Got:2
Put:3
Got:3
Put:4
Got:4
Put:5
Got:5
Deadlock:
Aspecialtypeoferrorthatweneedtoavoidrelatedspecificallytomulti-tasking
is deadlock, which occurs when two threads have a circular dependency on a pair of
synchronized objects. For example, suppose one thread enters the monitor on object X
and another thread enters the monitor on object Y. If the thread in X tries to call any
synchronizedmethodonY,itwillblockasexpected.However,ifthethreadinY,inturn
triestocallanysynchronizedmethodonX,thethreadwaitsforever,becausetoaccessX,
it would have to release its own lock on Y so that the first thread could complete.
Deadlockisadifficulterrortodebugfortworeasongs:
(i)Ingeneral,itoccursonlyrarelywhenthetwothreadstime-sliceinjust
therightway.
(ii)Itmayinvolvemorethantwothreadsandtwosynchronizedobjects.
Example12.15
1.classA
2.{
3.synchronizedvoidfoo(Bb1)
4.{
5.System.out.println(“Methodfoocalledandthenblocked”);
6.try
7.{
8.Thread.sleep(1000);
9.}
10.catch(InterruptedExceptione)
11.{
12.System.out.println(e.getMessage());
13.}
14.System.out.println(“Tryingtocallb1.last()”);
15.b1.last();
16.}
17.synchronizedvoidlast()
18.{
19.System.out.println(“Thiswillnotbeprinted”);
20.}
21.}
22.classB
23.{
24.synchronizedvoidbar(Aa1)
25.{
26.System.out.println(“Methodbarcalledandthenblocked”);
27.try
28.{
29.Thread.sleep(1000);
30.}
31.catch(InterruptedExceptione)
32.{
33.System.out.println(e.getMessage());
34.}
35.System.out.println(“Tryingtocalla1.last()”);
36.a1.last();
37.}
38.synchronizedvoidlast()
39.{
40.System.out.println(“Thiswillnotbeprinted”);
41.}
42.}
43classDeadLockimplementsRunnable
44.{
45.Aa1=newA();
46.Bb1=newB();
47.DeadLock()
48.{
49.Threadt=newThread(this);
50.t.start();
51.a1.foo(b1);
52.}
53.publicvoidrun()
54.{
55.b1.bar(a1);
56.}
57.publicstaticvoidmain(Stringargs[])
58.{
59.newDeadLock();
60.}\
61.}
Output:
Methodfoocalledandthenblocked
Methodbarcalledandthenblocked
Tryingtocallb1.last()
Tryingtocalla1.last()
Suspending,ResumingandStoppingThreadsinJava1.1andearlier:
PriortoJava2,suspend()andresume()aredefinedbyThreadclasstopauseand
restarttheexecutionofathread.Theyhavetheformshownbelow.
finalvoidsuspend()
finalvoidresume()
Example12.16:
1.classAimplementsRunnable
2.{
3.Stringname;
4.Threadt;
5.A(Stringthreadname)
6.{
7.name=threadname;
8.t=newThread(this,name);
9.System.out.println(“ChildThread:“+t);
10.t.start();
11.}
12.publicvoidrun()
13.{
14.for(inti=1;i<=30;i++)
15.{
16.System.out.println(name+“:“+i);
17.try
18.{
19.Thread.sleep(100);
20.}
21.catch(InterruptedExceptione)
22.{
23.System.out.println(e);
24.}
25.}
26.System.out.println(name+“exiting”);
27.}
28.}
29.classSuspendResume
30.{
31.publicstaticvoidmain(Stringargs[])
32.{
33.Aob1=newA(“One”);
34.Aob2=newA(“Two”);
35.try
36.{
37.Thread.sleep(1000);
38.ob1.t.suspend();
39.System.out.println(“SuspendingThreadone”);
40.Thread.sleep(1000);
41.ob1.t.resume();
42.System.out.println(“ResumingThreadone”);
43.ob2.t.suspend();
44.System.out.println(“SuspendingThreadtwo”);
45.Thread.sleep(1000);
46.ob2.t.resume();
47.System.out.println(“ResumingThreadtwo”);
48.}
49.catch(InterruptedExceptione)
50.{
51.System.out.println(e);
52.}
53.try
54.{
55.System.out.println(“Waitingforthreadstofinish”);
56.ob1.t.join();
57.ob2.t.join();
58.}
59.catch(InterruptedExceptione)
60.{
61.System.out.println(e);
62.}
63.}
64.}
Output:
Output:
ChildThread:Thread[One,5,main]
ChildThread:Thread[Two,5,main]
One:1
Two:1
Two:2
One:2
Two:3
One:3
Two:4
One:4
One:5
Two:5
Two:6
One:6
One:7
Two:7
Two:8
One:8
One:9
Two:9
Two:10
One:10
SuspendingThreadone
Two:11
Two:12
Two:13
Two:14
Two:15
Two:16
Two:17
Two:18
Two:19
Two:20
ResumingThreadone
SuspendingThreadtwo
One:11
One:12
One:13
One:14
One:15
One:16
One:17
One:18
One:19
One:20
ResumingThreadtwo
One:21
Two:21
One:22
Two:22
One:23
Two:23
One:24
Two:24
One:25
Two:25
One:26
Two:26
One:27
Two:27
One:28
Two:28
One:29
Two:29
One:30
Two:30
Oneexiting
Twoexiting
Waitingforthreadstofinish
Note:-The thread class also defines a method called stop( ) that stops a thread. Its
signatureisshownhere:
finalvoidstop()
Onceathreadhasbeenstopped,itcannotberestartedusingresume()method.
Suspending,ResumingandstoppingthreadsusingJava2
Example12.17:
1.classAimplementsRunnable
2.{
3.Stringname;
4.Threadt;
5.booleansuspendFlag;
6.A(Stringthreadname)
7.{
8.name=threadname;
9.t=newThread(this,name);
10.System.out.println(“ChildThread:“+t);
11.suspendFlag=false;
12.t.start();
13.}
14.voidmysuspend()
15.{
16.suspendFlag=true;
17.}
18.synchronizedvoidmyresume()
19.{
20.suspendFlag=false;
21.notify();
22.}
23.publicvoidrun()
24.{
25.for(inti=1;i<=15;i++)
26.{
27.System.out.println(name+“:“+i);
28.try
29.{
30.Thread.sleep(200);
31.}
32.catch(InterruptedExceptione)
33.{
34.System.out.println(e);
35.}
36.synchronized(this)
37.{
38.if(suspendFlag)
39.{
40.wait();
41.}
42.}
43.}
44.System.out.println(name+“exiting”);
45.}
46.}
47.classSuspendResume1
48.{
49.publicstaticvoidmain(Stringargs[])
50.{
51.Aob1=newA(“One”);
52.Aob2=newA(“Two”);
53.try
54.{
55.Thread.sleep(1000);
56.ob1.mysuspend();
57.System.out.println(“SuspendingThreadone”);
58.Thread.sleep(1000);
59.ob1.myresume();
60.System.out.println(“ResumingThreadone”);
61.ob2.mysuspend();
62.System.out.println(“SuspendingThreadtwo”);
63.Thread.sleep(1000);
64.ob2.myresume();
65.System.out.println(“ResumingThreadtwo”);
66.}
67.catch(InterruptedExceptione)
68.{
69.System.out.println(e);
70.}
71.try
72.{
73.System.out.println(“Waitingforthreadstofinish”);
74.ob1.t.join();
75.ob2.t.join();
76.}
77.catch(InterruptedExceptione)
78.{
79.System.out.println(e);
80.}
81.System.out.println(“mainexiting”);
82.}}
Output:
ChildThread:Thread[One,5,main]
ChildThread:Thread[Two,5,main]
One:1
Two:1
One:2
Two:2
One:3
Two:3
One:4
Two:4
One:5
Two:5
SuspendingThreadone
Two:6
Two:7
Two:8
Two:9
Two:10
ResumingThreadone
One:6
SuspendingThreadtwo
One:7
One:8
One:9
One:10
ResumingThreadtwo
Two:11
Waitingforthreadstofinish
One:11
Two:12
One:12
Two:13
One:13
Two:14
One:14
Two:15
One:15
Twoexiting
Oneexiting
mainexiting
CHAPTER
∞13∞
(Modifiers/Visibilitymodes)
Introduction-
ModifiersareJavakeywordsthatgivethecompilerinformationaboutthenature
ofcode,data,classesorinterfaces.Forexample,wehavebeenusingvisibilitymodifiers
public,private,protected,packagepublicetc.tospecifythevisibilityofclassmembers.
Besidevisibilitywehavealsousedthemodifierstatic,finalandabstract.
Forthepurposeofclearunderstanding,modifiercanbecategorizedas:
1.Accessibilitymodifiersfortop-levelclassesandinterfaces.
2.Memberaccessibility/visibilitymodifiersforclasses.
3.Memberaccessibility/visibilitymodifiersforinterfaces.
4.Othermodifiersfortop-levelclasses.
5.Othermodifiersfortop-levelinterfaces.
6.Othermodifiersforinterfacemembers.
7.Othermodifiersforclassmembers.
1.Accessibilitymodifiersfortop-levelclassesandinterfaces:
public
default(package)accessibility
2.Memberaccessibility/visibilitymodifiersforclasses:
Byspecifyingmemberaccessibilitymodifiersaclasscancontrolwhatinformationis
accessible to clients (i.e. other classes). These modifiers help a class to define a
contractsothatclientsknowexactlywhatservicesareofferedbytheclass.
Accessibility/visibilityofmemberscanbeoneothefollowing:
public
protected
default(alsocalledpackageaccessibility)
private
Note:-Memberaccessibilitymodifiersonlyhasmeaningiftheclass(oroneitssubclasses)
isaccessibletotheclient.Alsonotethatoneaccessibilitymodifierscanbespecifiedfora
member.
Thediscussionappliestobothinstanceandstaticmembersofclasses.
3.Memberaccessibility/visibilitymodifiersforinterfaces:
Theonlymemberaccessibility/visibilitymodifierthatcanbeusedwithdatamembers
andmethodsofaninterfaceispublic.
Thepublicisalsotheimplicitaccessibility/visibilitymodifierforinterfacemembers
i.e.themembersarealwaysimplicitlyassumedtobepublicevenifwedonotusethe
modifierpublic.
4.Othermodifiersfortop-levelclasses:
Besidevisibilitymodifiers,wecanalsousefollowingmodifiersbeforeatop-class:
(a)abstract
A class can be specified with the keyword abstract to indicate that it cannot be
instantiated. A class containing abstract method must be declared as abstract
otherwise it won’t compile. A class not containing abstract method can also be
declaredabstract.Suchaclasscanserveasabaseclassforanumberofsub-classes.
(b)final
Aclasscan be declaredfinal toindicate thatit cannotbeextended. Thefinal class
marksthelowerboundaryofitsimplementationinheritancehierarchy.Onlyaclass
whosedefinitioniscompletecanbedeclaredfinal.Aclasscannotbebothfinaland
abstractatthesametime.
Herearefewimportantcharacteristicsofthefinalclass.
Allthemethodsofafinalclassarealsofinali.e.theyhavetheconcreteimplementation
andcannotbeover-ridden.
Some type checks become faster with final classes. In fact, many type checks
become compile time checks and errors can be caught earlier. If the compiler
encounters a reference to a final class, it knows that the object referred to is
exactlyofthattype.
The compiler is able to perform certain code optimizations for final methods,
becausecertainassumptionscanbemadeaboutsuchmembers.
Whenanon-finalmethodisinvoked,theruntimesystemdeterminestheactual
classoftheobject,bindsthemethodinvocationtothecorrectimplementationof
themethodforthattype,andtheninvokestheimplementation.
In case of a final method we are sure that type sub-class can not override the
methodsothebindingisdoneatthecompiletimeasincaseofprivateandstatic
methods,whichwoulddefinitelyimprovetheperformance.
Incaseofafinalmethodthecompilermayreplaceaninvocationwiththeactual
bodyofthemethodlikeMacro.Thismechanismisknownas‘inlining’.InC++,
wehavetheoptionof declaringafunction asinline(although finaldecisionis
takenbythecompiler)butinJava,thecompilertakesthedecision.
5.Othermodifiersfortop-levelinterfaces:
(a)abstract
This is the only modifier other than visibility modifiers, which can be used with
interface.
Interfacesjustspecifythemethodprototypesandnotanyimplementation:theyare,
bytheirnature,implicitlyabstract.(i.e.theycannotbeinstantiated).Wecandeclare
aninterfaceasabstractbutitisredundantasinterfaceisalwaysabstract.
6.Othermodifiersforinterfacemembers:
Othermodifiersfordatamembers:
Besidevisibilitymodifierpublic,wecanalsousemodifiersstaticandfinal.Although
we can use these modifiers but it is redundant as all data members are implicitly
public,staticandfinal.
Othermodifiersformethods:
Besidevisibilitymodifierpublic,wecanalsousemodifierabstract.Althoughwecan
use abstract modifier but it is redundant as all methods are implicitly public, and
abstract.
7.Othermodifiersforclassmembers:-
Certain characteristics of fields and/or methods can be specified in their
declarationsbythefollowingkeywords:
1. static
2. final
3. abstract
4. synchronized
5. native
6. transient
7. volatile
A.staticmodifier:
Thestaticmembersbelongtotheclassinwhichtheyaredeclared,andarenotpartof
any instance of the class. Depending on the accessibility modifiers of the static
membersinaclass,clientcanaccessthesebyusingtheclassnameorthroughobject
referencesoftheclass.
staticvariables(alsocalledclassvariables):-
Thesevariablesonlyexistintheclasstheyaredefinedin.Whentheclassisloaded,
static variables are initialized to their default values, if no explicity initialization
expressioninspecified.
Thestaticmembervariablesareoftenusedwhentrackingglobalinformationabout
theinstances.
staticmethods:
Thesearealsoknownasclassmethods.Astaticmethodinaclasscandirectlyaccess
otherstaticmembersintheclass.Itcannotaccessinstance(i.e.non-static)members
oftheclass,asthereisnonotionofanobjectassociatedwithastaticmethod.
However,notethatastaticmethodinaclasscanalwaysuseareferenceofthe
class’stypetoaccessitsmembersregardlessofwhetherthesemembersarestaticor
not.A typical static method might perform some task on behalf of the whole class
and/orobjectsoftheclass.
Aninstanceinasubclasscannotoverrideastaticmethodinthesuperclass.The
compilerwillflagthiswithanerror(meansastaticmethodinsuperclasscannotbe
overriddenbynonstaticmethodsinsubclass).Astaticmethodisclassspecificand
notpartofanyobject,whileoverriding,methodsareinvokedonthebehalfofobjects
ofthesubclass.However,astaticmethodinasubclasscanhideastaticmethodinthe
superclass.
Methodsdeclaredasstatichaveseveralrestrictions:
Theycanonlycallotherstaticmethods.
Thecanonlyaccessstaticdatamembers.
Theycannotrefertothisorsuperinanyway
staticinitializationblock:
Ajavaclasscanhaveoneormorestaticinitializationblock.Thesyntaxofthestatic
initializationblockisasfollows:
static
{
code
}
A static initialization block can be though of as a static method, which is invoked
implicitly/automaticallyassoonastheclassisloaded.
Thestaticblockcanbeusefulinthefollowingsituations:
Dynamicinitializationofstaticvariables.
For performing one time activity at the time of loading class. For example,
loadingjdbcdriverclass.
Loading small database/configuration files in Hashtable, HashMap, Properties
etc.
B.finalmodifier:
Themodifierfinalcanbeusedwith
Localvariables
Instancevariables/datamembers
Staticvariables/datamembers
Instancemethods
finalvariables:
Afinalvariableisnormallyinitializedatthetimeofdeclarationanditsvaluecannot
be modified after assigning once. Here are few important points related to final
variables:
Afinalvariableisaconstant,despitebeingcalledavariable.Itsvaluecannotbe
changed once it has been initialized. This applies to instance, static and local
variables,includingparametersthataredeclaredfinal.
Thefinalistheonlymodifierapplicabletolocalvariablesorformalparameters.
Afinalvariableofaprimitivedatatypecannotchangeitsvalueonceithasbeen
initialized.
Afinalvariableofareferencetypecannotchangeitsreferencevalueonceithas
beeninitialized,butthestatoftheobjectitdenotescanstillbechanged.
Normallyafinalvariableisinitializedatthetimeofdeclarationbutitisnotmust.
Sucha final variableis also calledblank final variable,and must beinitialized
oncebeforeitisbeingused.
The final static variables are commonly used to define named constants, for
exampleInteger.MAX_VALUE,whichisthemaximumintvalue.
Localfinalvariables:-
Example13.1
The following example illustrates that local final variable can be left blank as
discussedabovebutmustbeinitializedbeforefirstuse.Thevariablexisinitialized
justbeforedisplayingitsvalueonthemonitor.
1.classFinalTest1//makeuseofblankfinal
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.finalintx;//initializationatdeclarationtimenotmust
6.x=50;
7.System.out.println(x);
8.}
9.}
Output:50
Example13.2
Thefollowingwillnotcompileasfinalvariableisinitializedtwice.
classFinalTest2//makeuseofblankfinal
1.{
2.publicstaticvoidmain(Stringargs[])
3.{
4.finalintx;
5.x=50;
6.System.out.println(x);
7.x=60;
8.}
9.}
Instancefinalvariables:-
Aninstancefinalvariablecanbeleftblankbutmustbeinitializedbeforeobtaininga
referenceofanobjectoftheclasscontainingfinalvariable.Soifwedonotinitialize
at the time of declaration then the other places at which final variables can be
initializedare:
Constructor
Initializationblock
Example13.3
The following program will not compile, as final variable is not initialized. The
conceptofinitializationbydefaultvalueisnotapplicabletofinalvariablesasthey
cannotbemodifiedafterinitialization.
1.classFinalTest3//makeuseofblankfinal
2.{
3.finalintx;//Nodefaultinitializationforfinalinstancevariables
4.}
5.classMyClass
6.{
7.publicstaticvoidmain(Stringargs[])
8.{
9.FinalTest3f=newFinalTest3();
10.System.out.println(f.x);
11.}
12.}
Output:
(Compiletimeerror):variablexmightnothavebeeninitialized.
Example13.4
The following program will also not compile, as final variable is initialized after
obtainingareference.
1.classFinalTest4
2.{
3.finalintx;
4.}
5.classMyClass
6.{
7.publicstaticvoidmain(Stringargs[])
8.{
9.FinalTest4f=newFinalTest4();
10.f.x=10;
11.System.out.println(f.x);
12.}
13.}
Example13.5
The following example illustrates that a blank final instance variable can be
initializedintheconstructor.
1.classFinalTest5
2.{
3.finalintx;
4.publicstaticvoidmain(Stringargs[])
5.{
6.FinalTest5f=newFinalTest5();
7.System.out.println(f.x);
8.}
9.FinalTest5()
10.{
11.x=10;
12.}
13.}
Output:
10
Example13.6
Thefollowingprogramillustratesthatablankfinalvariablecanbeinitializedwitha
dynamicvalueandcanbereferredwiththiskeyword.Sodifferentobjectsofthesame
classcanhavedifferentvaluesofthefinalvariable.
1.classFinalTest6
2.{
3.finalintx;
4.FinalTest6(intx1)
5.{
6.x=x1;
7.}
8.publicstaticvoidmain(Stringargs[])
9.{
10.FinalTest6f1=newFinalTest6(10);
11.FinalTest6f2=newFinalTest6(20);
12.System.out.println(f1.x);
13.System.out.println(f2.x);
14.}
15.}
Output:
10
20
Initializationblock:-
A java class can have one or more initialization blocks. The syntax of the
initializationblockisasfollows:
{
code
}
A initialization block can be thought if as a constructor, which is invoked
implicitly/automaticallyassoonastheobjectiscreate.Infactifaclasscontains
initializationblocksthemtheyareexecutedintheorderofdefinitionfromtopto
bottombeforeanyconstructor.
Example13.7:
1.classFinalTest7
2.{
3.finalintx;
4.publicstaticvoidmain(Stringargs[])
5.{
6.FinalTest7f=newFinalTest7();
7.System.out.println(f.x);
8.}
9.{
10.x=20;
11.}
12.}
Theinitializationblockcanbeusefulinthefollowingsituations:
Dynamicinitializationofinstancevariables.
For defining code which is common to all constructors. This will increase the
codereusabilityandreducemaintenance.
Astaticfinalvariables:
A static final variables can be left blank, but must be initialized before class is
availabletotheprogram.Soifwedonotinitializeatthetimeofdeclarationthenthe
onlyplaceatwhichstaticfinalvariablecanbeinitializedis:
staticInitializationblock
Example13.8
Thefollowingexampleillustratesthattheblankstaticfinalvariablecanbeinitialized
inthestaticblock.
1.classFinalTest8
2.{
3.staticfinalintx;
4.publicstaticvoidmain(Stringargs[])
5.{
6.System.out.println(FinalTest8.x);
7.}
8.static
9.{
10.x=20;
11.}
12.}
Output:
20
finalmethods:-
Afinalmethodinaclassiscomplete(i.e.hasanimplementation)andcannotbe
overridden in any subclass. Subclasses are thus restricted in changing the
behaviorofthemethod.
The compiler is able to perform certain code optimizations for final methods,
because certain assumptions can be made about such members. When a non-
staticmethodisinvoked,theruntimesystemdeterminestheactualclassofthe
object,bindsthemethodinvocationtothecorrectimplementationofthemethod
forthattype,andtheninvokestheimplementation.
Incaseofafinalmethodwearesurethatsub-classcannotoverridethemethod
so the binding is done at the compile time as in case of private and static
methods,whichwoulddefinitelyimprovestheperformance.
Incaseofafinalmethodthecompilermayreplaceaninvocationwiththeactual
bodyofthemethodlikeMacro.Thismechanismisknownas‘inlining’.InC++,
wehavetheoptionof declaringafunction asinline(although finaldecisionis
takenbythecompiler)butinJava,thecompilertakesthedecision.
C.abstractmodifier:-
Theabstractmodifier canbe usedonlywith instancemethods.An abstractmethod
doesnothavean implementation,thatis,nomethodbody isdefinedforanabstact
method,onlythemethodprototypeisprovidedintheclassdefinition.
Itsclassisalsoabstract(i.e.,incomplete)andmustbeexplicitlydeclaredasabstract.
Subclasses of an abstract class must then provide the method implementation;
otherwise,theyarealsoabstract.
Herearesomeimportantpointsrelatedtoabstractmethods:
An abstract method cannot be declared private. This is obvious as we can not
overrideanprivatemethod,whileincaseofanabstractmethodbodyisalways
providedinthesub-classbyover-ridingtheabstractmethod.
Onlyaninstancemethodcanbedeclaredabstractsincestaticmethodscannotbe
overridden, declaring an abstract static method would make no sense and will
resultincompilationerror.
Afinalmethodcannotbeabstractandvice-versa.
Thekeywordabstractcannotbecombinedwithanynon-accessibilitymodifiers
formethods.
Methods specified in an interface are implicitly abstract, as only the method
prototypesaredefinedinaninterface.
D.synchronizedmodifier:-
Thesynchronizedkeywordcanbeusedwithmethodsandcodeblocks.Severalthread
canexecutesimultaneouslyinaprogram.Theymighttrytoexecuteseveralmethods
onthesameobjectsimultaneouslyinaprogram.Theymighttrytoexecuteseveral
methodsonthesameobjectsimultaneously.Ifitisdesiredthatonlyonethreadata
timecanexecuteamethodintheobject,themethodscanbedeclaredsynchronized.
Theirexecutionisthemutuallyexclusiveamongallthreads.
Atany given time,at mostonethread canbe executing asynchronized methodon
any given time, at most one thread can be executing a synchronized method on an
object.Thisdiscussionalsoappliestostaticsynchronizedmethodsofaclass.
Note-Thesynchronizedmodifierdoesnotapplytoclassesormembervariables.
E.nativemodifier:-
The native modifier can refer only to methods. Like the abstract keyword, native
indicatesthatthebodyofamethodistobefoundelsewhere.Thebodyofanative
methodisentirelyoutsidetheJVM,inalibrary.Nativecodeiswritteninanon-java
language,typically Cor C++,and compiledfor asingle targetmachine type.Thus
Java’s platform independence is violated. People who port Java to new platforms
implement extensive native code to support GUI components, network
communication,andabroadrangeofotherplatform-specificfunctionality.However,
itisrarefortheapplicationandappletprogrammerstoneedtowritenativecode.
F.transientmodifier:-
Objects can be stored using serialization. Serialization transforms objects into an
outputformatthatisconduciveforstoringobjects.Objectscanlaterberetrievedin
thesamestateaswhentheywereserialized,meaningthatallfieldsincludedinthe
serializationwillhavethesamevaluesasatthetimeofserialization.Suchobjectsas
saidtobepersistent.
Afieldcanbespecifiedastransientintheclassdeclaration,indicatingthatitsvalue
shouldnotbesavedwhenobjectsoftheclassarewrittentopersistentstorage.class
ExperimentimplementsSerializable-
{
transientintcurrentTemperature;//transient
doublemass;//persistentvalue
}
Specifying the transient modifier for static variables is redundant and therefore,
discouraged. The static variables are not part of the persistent state of a serialized
object.
G.volatilemodifier
During execution, compiled code might cache the value of fields for efficiency
reasons.Sincemultiplethreadscanaccessthesamefield,itisvitalthatcachingisnot
allowedtocauseinconsistencieswhenreadingandwritingthevalueinthefield.The
volatile modifier can be used to inform the compiler that it should not attempt to
performoptimizationonthefield,whichcouldcauseunpredictableresultswhenthe
fieldisaccessedbymultiplethreads.
CHAPTER
∞14∞
(WrapperClass)
Introduction-
Theprimitivedatatypesinjavaarenotobjects.Ifwewanttousethesedatatypes
asobjects,thenwewillhavetousewrapperclassesforeachoftheseprimitivedatatypes
providedinjava.langpackage.
Therearemanybuilt-inclasses,whichcannothandleprimitivedatatypesasthey
deal only with objects. One such class is Vector, which is used to store a collection of
objects.WecannotusetheVectorclasstodirectlystorethecollectionofelementsofa
primitivedatatyped.Butwecandosobystoringtheobjectsofwrapperclasses,which
correspondtotheprimitivedatatypes.
TheJavahaswrapper classcorrespondingtoeachof theprimitivedatatypeas
showninthefollowingtable:
PrimitiveDataType WrapperClass
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Numberclass:
TheabstractclassNumberdefinessuper-classthatisimplementedbytheclasses
that wrap the numeric type byte, short, int, long, float, and double. Number class has
abstract methods that return the value of the object in each of the different number
formats.Thesemethodsare:
bytebyteValue()
Returnsthevalueofthespecifiednumberasabyte.
shortshortValue()
Returnsthevalueofthespecifiednumberasashort.
abstractintintValue()
Returnsthevalueofthespecifiednumberasanint.
abstractlonglongValue()
Returnsthevalueofthespecifiednumberasalong.
abstractfloatfloatValue()
Returnsthevalueofthespecifiednumberasafloat.
abstractdoubledoubleValue()
Returnsthevalueofthespecifiednumberasadouble.
Note- The values returned by byteValue(), shortValue(), intValue(),longValue(),
floatValue()anddoubleValue()methodsmayinvolveroundingortruncation.
Example14.1
The following example demonstrates how rounding and truncation takes place when
invokingmethodsofclassNumber.
1.classWrapper
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.IntegeriObj=newInteger(128);
6.System.out.println(iObj.byteValue());//truncation
7.LonglObj=newLong(123456789123456789L);
8.System.out.println(lObj);
9.System.out.println(lObj.doubleValue());
10.FloatfObj=newFloat(3.99f);
11.System.out.println(fObj.intValue());truncation
12.}
13.}
Output:
-128
123456789123456789
1.23456789123456784E17
3
Converting Primitive Numbers to Objects using Constructors of Wrappers Classes and
ConvertingNumericObjectsbacktoPrimitiveNumbers:-
Example14.2
Thefollowingexampledemonstrateshowprimitivescanbewrappedinobjectsandhow
theycanbeconvertedbacktoprimitives.
1.classConvert
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.System.out.println(“Convertingprimitivenumberstoobjects“+“usingconstructors”);
7.byteb=105;
8.BytebObj=newByte(b);
9.System.out.println(bObj);//toString()
10.shorts=2015;
11.ShortsObj=newShort(s)
12.System.out.println(sObj);
13.inti=32717;
14.IntegeriObj=newInteger(i);
15.System.out.println(iObj);
16.longl=234543335565675L
17.LonglObj=newLong(l);
18.System.out.println(lObj);
19.floatf=3.1415f;
20.FloatfObj=newFloat(f);
21.System.out.println(fObj);
22.doubled=3.1415;
23.DoubledObj=newDouble(d);
24.System.out.println(dObj);
25.System.out.println(“Convertingnumericobjectstoprimitivenumbers”);
26.byteb1=bObj.byteValue();
27.shorts1=sObj.shortValue();
28.inti1=iObj.intValue();
29.longl1=lObj.longValue();
30.floatf1=fObj.floatValue();
31.doubled1=dObj.doubleValue();
32.System.out.println(b1);
33.System.out.println(s1);
34.System.out.println(i1);
35.System.out.println(l1);
36.System.out.println(f1);
37.System.out.println(d1);
38}
39.}
Output:
Convertingprimitivenumberstoobjectsusingconstructor
105
2015
32717
234543335565675
3.1415
3.1415
Convertingobjecttoprimitivenumbers
105
2015
32717
234543335565675
3.1415
3.1415
Converting Primitive Numbers to Strings using toString() static method of the
correspondingWrapperClass
Example14.3:
1.classConvertPrimitiveToString
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.System.out.println(“ConvertingprimitivenumberstoString“+
6.“usingtoString()staticmethodofcorrespondingwrapperclass:”);
7.byteb=105;
8.Stringstr=Byte.toString(b);
9.System.out.println(str);
10.shorts=303;
11.str=Short.toString(s);
12.System.out.println(str);
13.inti=100;
14.str=Integer.toString(i);
15.System.out.println(str);
16.longl=454444444444l;
17.str=Long.toString(l);
18.System.out.println(str);
19.floatf=3.444f;
20.str=Float.toString(f);
21.System.out.println(str);
22.doubled=3.44444;
23.str=Double.toString(d);
24.System.out.println(str);
25.}
26}
Output:
Converting primitive numbers to String using toString() static method of
correspondingwrapperclass:
105
303
100
454444444444
3.444
3.44444
ConvertingNumericObjectstoStringsusingtoString()methodofthecorresponding
WrapperClass:-
Example14.4
1.classObjectToStringDemo
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.System.out.println(“ConvertingobjectnumberstoStringsusing”+
“toString()methodofcorrespondingwrapperclass:”);
7.byteb=103;
8.BytebObj=newByte(b);
9.Stringstr=bObj.toString();
10.System.out.println(str);
11.shorts=203;
12.ShortsObj=newShort(s);
13.str=sObj.toString();
14.System.out.println(str);
15.IntegeriObj=newInteger(32000);
16.str=iObj.toString();
17.System.out.println(str);
18.str=newLong(4544444444444l).toString();
19.System.out.println(str);
20.str=newFloat(3.1444f).toString();
21.System.out.println(str);
22.str=newDouble(4.1444).toString();
23.System.out.println(str);
24.}
25.}
Output:
ConvertingobjectnumberstoStringsusingtoString()methodofcorresponding
wrapperclass:
103
203
32000
4544444444444
3.1444
4.1444
Converting String Objects(Numeric Strings) to Numberic Objects using the static
valueOf()methodofthecorrespondingWrapperClass
Example14.5
1.classStringToNumericObjectDemo
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.Stringstr=”30”;
6.Stringstr2=”30.333”;
7.BytebObj=Byte.valueOf(str);
8.System.out.println(bObj);
9.//BytebObj1=newByte(str2);//NumberFormatException
10.ShortsObj=Short.valueOf(str);
11.System.out.println(sObj);
12.IntegeriObj=Integer.valueOf(str);
13.System.out.println(iObj);
14.LonglObj=Long.valueOf(“344324232432”);
15.System.out.println(lObj);
16.FloatfObj=Float.valueOf(“3.333”);
17.System.out.println(fObj);
18.DoubledObj=Double.valueOf(str2);
19.System.out.println(dObj);
20.}
21.}
Output:
30
30
30
3.44324232432
3.33
30.333
Note:-All of the valueOf() methods throw “NumberFormatException” if the string does
notcontainaparsablenumber.
ConvertingstringObjects(NumericStrings)toNumericObjectsusingConstructor
ofthecorrespondingWrapperClass
Example14.6
1.classStringToNumericObjectDemo1
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.Stringstr=newString(“30”);
6.//Stringstr=”30”;
7.Stringstr2=newString(“30.333”);
8.BytebObj=newByte(str);
9.System.out.println(bObj);
10.//BytebObj=newByte(str2);//NumberFormatException
11.ShortsObj=newShort(str);
12.System.out.println(sObj);
13.IntegeriObj=newInteger(str);
14.System.out.println(iObj);
15.LonglObj=newLong(str);
16.System.out.println(lObj);
17.FloatfObj=newFloat(str);
18.System.out.println(fObj);
19.DoubledObj=newDouble(str);
20.System.out.println(dObj);
21.}
22.}
Output:
30
30
30
30
30.333
30.333
Note:- The Above constructor throw “NumberFormatException” if the string does not
containaparsablenumber.
Converting String Objects (Numeric Strings) to Primitive Numbers using parsing
methodsofthecorrespondingWrapperClass
Example14.7:
1.classStringToPrimitiveDemo
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.Stringstr=newString(“30”);
6.//Stringstr=”30”;
7Stringstr2=newString(“30.333”);
8.byteb=Byte.parseByte(str);
9.System.out.println(b);
10.//byteb1=Byte.parseByte(str2);//NumberFormatException
11.shorts=Short.parseShort(str);
12.System.out.println(s);
13.inti=Integer.parseInt(str);
14.System.out.println(i);
15.longl=Long.parseLong(str);
16.System.out.println(l);
17.floatf=Float.parseFloat(str2);
18.System.out.println(f);
19.doubled=Double.parseDouble(str2);
20.System.out.println(d);
21.}
22.}
Output:
30
30
30
30
30.333
30.333
Note:-parseXXXXX() methods throw “NumberFormatException” if the string does not
containaparsablenumber.
ConstantsdefinedinclassesDoubleandFloat:
MAX_VALUE
MIN_VALUE
NaN
NEGATIVE_INFINITY
POSITIVE_INFINITY
TYPE(Theclassinstancerepresentingtheprimitivetypedouble/float)
SIZE(Thenumberofbitsusedtorepresentadoublevalue).SinceJ2SDK1.5.
OtherMethodsinFloatClass:
1.staticintcompare(floatf1,floatf2)
2.Comparesthetwospecifiedfloatvalues
3.intcompareTo(FloatanotherFloat)
4.ComparestwoFloatobjectsnumerically.
5.booleanequals(Objectobj)
6.Comparesthisobjectagainstthespecifiedobject
7.inthashCode()
8.Returnsahashcodeforthisfloatobject.
9.booleanisInfinite()
10.Returns true if this Float value is infinitely large in magnitude, false
otherwise.
11.staticbooleanisInfinite(floatv)
12.Returnstrueifthespecifiednumberisinfinitelylargeinmagnitude,false
otherwise.
13.booleanisNaN()
14.Returns true if this float value is a Not-a-Number (NaN) value, false
otherwise.
15.staticBooleanisNaN(floatv)
16.ReturnstrueifthespecifiednumberisaNot-a-Number(NaN)value,false
otherwise.
OthermethodsindoubleClass:
MethodsinDoubleclassarealmostsameasmethodsoffloatClass,withuseof
doubleanddoublewordsinsteadoffloatandFloatwordsintheprevioustable.
ConstantsdefinedinclassesByte,Short,IntegerandLong:
MIN_VALUE
MAX_VALUE
TYPE(Theclassinstancerepresentingtheprimitivetypebyte/short/int/long)
SIZE(Thenumberofbitsusedtorepresentabyte/short/int/longvalueintwo’s
complementbinaryform.)SinceJ2SDK1.5.
OtherMethodsinByteClass:
intcomparesTo(ByteanotherByte)
ComparestwoByteobjectsnumerically.
staticBytedecode(Stringnm)
Returns a Byte object that contains the value specified by the string nm. Accepts
decimal,hexadecimal,andoctalnumbersgivenbythefollowinggrammer:
DecodableString:
[-]DecimalNumerical
[-]0xHexDigits
[-]0XHexDigits
[-]#HexDigits
[-]0OctalDigits
booleanequals(Objectobj)
Comparesthisobjecttothespecifiedobject.
inthashCode()
ReturnsahashcodeforthisByte.
OtherMethodsinShortClass:
MethodsinShortclassaresameasmethodsofByteclass,withtheuseofshortandShort
wordsinsteadofbyteandBytewordsintheabovetable.
OtherMethodsinIntegerClass:
Some methods are same as Byte or Short class’s methods. Some other methods are
describedbelow:
staticStringtoBinaryString(inti)
Returns a string representation of the integer argument as an unsigned
integerinbase2.
staticStringtoHexString(inti)
Returns a string representation of the integer argument as an unsigned
integerinbase16.
staticStringtoOctalString(inti)
Returns a string representation of the integer argument as an unsigned
integerinbase8.
OtherMethodsinLongClass:
MethodsinLongclassarealmostsameasmethodsofIntegerClass.
CharacterClass:
Thecharacterclasswrapsavalueoftheprimitivetypecharinanobject.
Constructor:
Character(charvalue)
ConstructsanewlyallocatedCharacterobjectthatrepresentsthespecifiedchar
value.
Example:CharacterchObj=newCharacter(‘A’);
Methods:
SomeofthemethodsofCharacterclassaredescribedinthefollowingtable:
charcharValue()
ReturnsthevalueofthisCharacterobject.
staticbooleanisDefined(charch)
DeterminesifthespecifiedcharacterinUnicode.
staticbooleanisDigit(charch)
Determinesifthespecifiedcharacterisadigit.
staticbooleanisJavaIdentifierPart(charch)
DeterminesifthespecifiedcharactermaybepartofaJavaidentifierasotherthanthe
firstcharacter.
staticbooleanisJavaIdentifierStart(charch)
Determines if the specified character is permissible as the first character in a Java
identifier.
staticbooleanisLetter(charch)
Determinesifthespecifiedcharacterisaletter.
staticbooleanisLetterorDigit(charch)
DeterminesifthespecifiedcharacterisaletterorDigit.
staticbooleanisLowerCase(charch)
Determinesifthespecifiedcharacterisalowercasecharacter.
staticbooleanisSpaceChar(charch)
DeterminesifthespecifiedcharacterisaUnicodespacecharacter.
staticbooleanisTitleCase(charch)
Determinesifthespecifiedcharacterisatitlecasecharacter.
staticbooleanisUpperCase(charch)
Determinesifthespecifiedcharacterisauppercasecharacter.
staticbooleanisWhitespace(charch)
DeterminesifthespecifiedcharacterisawhitespaceaccordingtoJava.
staticchartoLowerCase(charch)
Convertsthecharacterargumenttolowercase.
staticchartoUpperCase(charch)
Convertsthecharacterargumenttouppercase.
staticchartoTitleCase(charch)
ConvertsthecharacterargumenttoTitlecase.
intcompareTo(CharacteranotherCharacter)
ComparestwoCharacterobjectsnumerically.
inthashcode()
ReturnsahashcodeforthisCharacter.
booleanequals(Objectobj)
Comparesthisobjectagainstthespecifiedobject.
Boolean Class: The Boolean class wraps a value of the primitive type Boolean in an
object.
Constructors:
Boolean(Booleanvalue)
AllocatesaBooleanobjectrepresentingthevalueargument.
Boolean(Strings)
AllocatesaBooleanobjectrepresentingthevaluetrueifthestringargumentisnotnull
andisequal,ignoringcase,tothestring“true”.
MethodsofBooleanClass:
booleanbooleanValue()
ReturnsthevalueofthisBooleanobjectasaBooleanprimitive.
intcompareTo(Booleanb)
ComparesthisBooleaninstancewithanother.
booleanequals(Objectobj)
Returns true if and only if the argument is not a null and is a Boolean object that
representsthesamebooleanvalueasthisobject.
staticBooleangetBoolean(Stringname)
Returns true if and only if the system property named by the argument exists and is
equaltothestring“true”.
inthashCode()
ReturnsahashcodeforthisBooleanobject.
staticbooleanparseBoolean(Strings)
Parsesthestringargumentasaboolean.
StringtoString()
ReturnsaStringobjectrepresentingthisBoolean’svalue.
staticStringtoString(booleanb)
ReturnsaStringobjectrepresentingthespecifiedboolean.
staticBooleanvalueOf(booleanb)
ReturnsaBooleaninstancerepresentingthespecifiedbooleanvalue.
staticBooleanvalueOf(Strings)
ReturnsaBooleanwithavaluerepresentedthespecifiedString.
CHAPTER
∞15∞
(Input/OutputinJava)
Introduction-
Streams-
JavaprogramsperformI/Othroughstreams.Astreamisanabstractionthateither
producesorconsumesinformation.AstreamislinkedtoaphysicaldevicebytheJavaI/O
system.
All streams behave in the same manner, even if the actual physical devices to
whichtheyarelinkeddiffer.Thus,thesameI/Oclassesandmethodscanbeappliedtoany
typeofdevice.
This means an input stream can abstract many different kinds of input: from a
disk file, a keyboard or a network socket. Likewise an output stream may refer to the
console,adiskfile,oranetworkconnection.
Streamsareacleanwaytodealwithinput/outputwithout havingeverypartof
ourcodeunderstandthedifferencebetweenakeyboardandanetwork,forexample.Java
implementsstreamswithinclasshierarchiesdefinedinthejava.iopackage.
(RelationshipofJavaProgramwithI/ODevices)
Theconceptof sendingdatafromonestream toanother(like onepipefeeding
intoanotherpipe)hasmadestreamsinJavaapowerfultoolforfileprocessing.Wecan
buildacomplexfileprocessingsequenceusingaseriesofsimplestreamoperations.
This feature can be used to filter data along the pipeline of streams so that we
obtaindata in adesired format.Forexample, wecanuse onestreamto getraw data in
binaryformatandthenuseanotherstreaminseriestoconvertitintointegers.
InputandOutputStreams:-
Java streams are classified into two basic types: normally input streams and
outputstreams.Aninputstreamextracts(i.e.reads)datafromthesourceandsendsitto
theprogram.
The program connects and opens an input stream on the data source and then
readsthedataserially.Similarly,theprogramconnectsandopensanoutputstreamtothe
destinationplaceofdataandwritesdataoutserially.Inboththecases,theprogramdoes
notknowthedetailsofendpoints(i.e.sourceanddestination).
ByteStreamsandCharacterStreams-
Java2definestwotypesofstreams:ByteandCharacter.Bytestreamsprovidea
convenient means for handling input and output of bytes. Byte streams are used, for
example, when reading or writing binary data. Character streams provide a convenient
meansforhandlinginputandoutputofcharacter.
They use Unicode and therefore, can be internationalized. Also in some cases,
characterstreamsaremoreefficientthanbytestreams.TheoriginalversionofJava(Java
1.0)didnotincludecharacterstreamsandthis,allI/Owasbyteoriented.
CharacterstreamswereaddedbyJava1.1andcertainbyteorientedclassesand
methodsweredeprecated.
Note:Atthelowestlevel,allI/Oisstillbyteoriented.Thecharacter-basedstreamssimply
provideaconvenientandefficientmeansforhandlingcharacters.
Thesetwogroupsmaybefurtherclassifiedbaseontheirpurposes.ByteStream
andCharacterStreamclassescontainspecializedclassestodealwithinputandoutput
operationsindependentlyonvarioustypesofdevices.
Wecanalsocross-groupthestreamsbasedonthetypeofsourceordestination
theyreadfromorwriteto.Thesource(ordestinationmaybememory,afileorapipe.
(ClassificationofJavaStreamClasses)
OverviewofByteStreamClasses:-
Bytestreamclassesaredefinedbyusingtwoclasshierarchies.Atthetoparetwo
abstractclasses:
(1)InputStreamand(2)OutputStream
Each of these abstract classes have several concrete subclasses, that handle the
differences between various devices, such as disk files, network connections and even
memorybuffers.
InputStreamclasses
InputStreamclassesthatareusedtoread8-bitbytesincludeasuperclassknown
asInputStreamandanumberofsub-classesforsupportingvariousinputrelatedfunctions.
HierarchyofInputStreamClasses.
HierarchyofInputStreamClasses.
TheInputStreamclass:-
The super class InputStream is an abstract class, which defines methods for
performinginputfunctionssuchas:
Readingbytes.
Closingstream.
Markingpositionsinstreams.
Skippingaheadinastream.
Findingthenumberofbytesinastream.
MethodsofInputStreamclass:
intavailable()
Givesthenumberofbytesavailableintheinput(mustbeoverriddenbythesubclasses).
TheavailablemethodforclassInputStreamalwaysreturns0.
voidclose()
Closesthisinputstreamandreleasesanysystemresourcesassociatedwiththestream.
TheclosemethodofInputStreamdoesnothing.
voidmark(intreadlimit)
Marksthecurrentpositioninthisinputstream.ThemarkmethodofInputStreamdoes
nothing.
booleanmarkSupported()
Tests if this input stream supports the mark and reset methods. The markSupported
methodofInputStreamreturnfalse.
abstractintread()
Reads the next byte of data from the input stream. A subclass must provide an
implementationofthismethod.
intread(byte[]b)
Readssomenumberofbytesfromtheinputstreamandstoresthemintothebufferarray
b.Thenumberofbytesactuallyreadisreturnedasaninteger.
intread(byte[]b,intoffset,intlen)
Readssomenumberofbytesfromtheinputstreamandstoresthemintothebufferarray
bstartingfrompositionspecifiedbytheparameteroff.Thenuberofbytesactuallyread
isreturnedasaninteger.
voidreset()
Repositionsthisstreamtothepositionatthepositionatthetimethemarkmethodwas
last called on this input stream. The reset method of InputStream does nothing and
alwaysthrowsIOException.
longskip(longn)
Skips over and discards upto n bytes of data from this input stream and returns the
numberofbytesactuallyskipped.
TheDataInputInterface:
TheDataInputisaninterface,whichdefinesmethodsforreadingprimitivesfrom
anInputStream.
MethodsofDataInputInterface:
booleanreadBoolean()
Readsoneinputbyteandreturnstrueifthatbyteisnon-zeroandfalseifthatbyteis
zero.
bytereadByte()
Readsandreturnsonebyteinput.
charreadChar()
Readsaninputcharacterandreturnsitsvalue.
doublereadDouble()
Readseightinputbytesandreturnsadoublevalue.
floatreadfloat()
Readsfourinputbytesandreturnsadoublevalue.
voidreadFully(byte[]b)
Readssomebytesfromaninputstreamandstoresthem inabufferarray b.This
methodthrowsEOFExceptionifthisstreamreachestheendbeforereadingallthe
bytes.
voidreadFully(byte[]b,intoff,intlen)
Readslenbytesfromaninputstreamandstorestheminabufferarraybstartingat
thepositionspecifiedbytheoff.ThismethodthrowsEOFExceptionifthisstream
reachestheendbeforereadingallthebytes.
intreadInt()
Readsfourinputbytesandreturnsanintvalue.
StringreadLine()
Readsthenextlinefromtheinputstream.
longreadLong()
Readseightinputbytesandreturnsalongvalue.
shortreadShort()
Readstwoinputbytesandreturnsashortvalue
StrigreadUTF()
ReadsinastringthathasbeenencodedusingamodifiedUTF-8format.
intskipBytes(intn)
Makesanattempttoskipovernbytesofdatafromtheinputstream,discardingthe
skippedbytes.Theactualnumberofbytesskippedisreturned.
SummaryofInputStreamClasses:-
AFilterInputStreamcontainssomeotherinputstream,whichitusesasitsbasic
source of data possibly transforming the data along the way providing additional
functionality.
The class FilterInputStream itself simply overrides all methods of InputStream
with versions that pass all requests to the contained input stream. Sub-classes of
FilterInputStream may further override some of these methods and may also provide
additionalmethodsandfields.
Note that the class DataInputStream extends FilterInputStream and implements
the interface DataInput. Therefore, the DataInputStream extends FilterInputStream and
implements the mewthods described in DataInput in addition to using methods of
InputStreamclass.
InputStreamclassessummary:
InputStream Thisabstractclassisthesuperclassofallclassesrepresentinganinputstream
ofbytes.
BufferedInputStream AbufferedInputStreamaddsfunctionalitytoanotherinputstream-namely,the
abilitytobuffertheinputandtosupportthemarkandresetmethod.
ByteArrayInputStream A ByteArrayInputStream contains an internal buffer that contain bytes that
maybereadfromthestream.
DataInputStream ADataInputStreamletsanapplicationreadtheprimitiveJavadatatypesfrom
anunderlyinginputstreamfromamachine-independentway.
FileInputStream AFileInputStreamcontainsinputbytesfromafileinafilesystem.
FilterInputStream A FilterInputStream contains some other input stream, which it uses as its
basicsourceofdata,possiblytransferringthedataalongthewayorproviding
additionalfunctionality.
PipedInputStream APipedInputStreamshouldbeconnectedtoapipedoutputstream,thepiped
input stream then provides whatever data bytes are written to piped output
stream.
PushbackInputStream APushbackInputStreamaddsfunctionalitytoanotherinputstream,namelythe
abilityto“pushback”or“unread”onebyte.
SequenceInputStream ASequenceInputStreamrepresentsthelogicalconcentrationofanotherstream.
ObjectInputStream AnObjectInputStreamdeserializsprimitivedataandobjectspreviouslywritten
usinganObjectOutputStream.
OutputStreamclasses-
OutputstreamclassesarederivedfromthebaseclassOutputStream,whichisan
abstract class and have a number of sub-classes for supporting various output related
functions.
TheOutputStreamclass:-
The super class OutputStream is an abstract class, which defines methods for
performingoutputfunctionssuchas:
Writingbytes
Closingstreams
Flushingstreams
(HierarchyofOutputStreamClasses)
Oops!!Let’sseefollowinggoodqualitypicture-
MethodsofOutputStreamClass:-
voidclose()
Closesthisoutputstreamandreleasesanystreamresourcesassociatedwiththis
stream.
voidflush()
Flushesthisoutputstreamandforcesanybufferedoutputbytestobewrittenout.
voidwrite(byte[]b)
Writesb.lengthbytesfromthespecifiedbytearraytoitsoutputstream.
voidwrite(byte[]b,intoff,intlen)
Writeslenbytesfromthespecifiedbytearraystartingatoffsetofftoitsoutput
stream.
abstractvoidwrite(intb)
Writesthespecifiedbytetoitsoutputstream.
TheDataOutputInterface:-
TheDataOutputisaninterface,whichdefinesmethodsforwritingprimitivesto
anOutputStream.
MethodsofDataOutputInterface:
voidwriteBoolean(booleanv)
Writesabooleanvaluetoitsoutputstream.
voidwriteByte(intv)
Writestotheoutputstreamtheeightlow-orderbitsoftheargumentv.
voidwriteBytes(strings)
Writesthestringtotheoutputstream.Foreverycharacterinthestrings,takeninorder,
onebyteiswrittentotheoutputstream.
voidwriteChar(intv)
Writesacharactervalue,whichiscomprisedoftwobytes,totheoutputstream.
voidwriteChars(strings)
Writeseverycharacterinthestrings,totheoutputstreamintheorderofeightbytes,to
theoutputstream.
voidwriteDouble(doublev)
Writesadoublevalue,whichiscomprisedofeightbytes,totheoutputstream.
voidwriteFloat(floatv)
Writesafloatvalue,whichiscomprisedoffourbytes,totheoutputstream.
voidwriteInt(intv)
Writesaintvalue,whichiscomprisedoffourbytes,totheoutputstream.
voidwriteLong(longv)
Writesalongvalue,whichiscomprisedofeightbytes,totheoutputstream.
voidwriteShort(intv)
Writesashortvalue,whichiscomprisedoftwobytes,totheoutputstream.
voidwriteUTF(Stringstr)
Writestwobytesoflengthinformationtotheoutputstream,followedbythemodified
UTF-8representationofeverycharacterinthestrings.
SummaryofOutputStreamClasses:-
The DataOutputStream is a counter part of DataInputStream. The
DataOutputStream class implements the methods described in DataOutput interface in
additiontousingmethodsofOutputStreamclass.
OutputStreamClassesSummary:-
OutputStream This abstract class is the super class of all classes
representinganoutputstreamofbytes.
BufferedOutputStream Theclassimplementsabufferedoutputstream.
ByteArrayOutputStream Theclassimplementsanoutputstreaminwhichthedata
iswrittenintoabytearray.
DataOutputStream A data output stream lets an application write primitive
Javadatatypestoanoutputstreaminaportableway.
FileOutputStream Afileoutputstreamisanoutputstreamforwritingdatato
aFile.
PipedOutputStream Apipedoutputstreamcanbeconnectedtoapipedinput
streamtocreateacommunicationspipe.
FilterOutputStream AFilterOutputStreamcontainssomeotheroutputstreams,
whichitusesasitsdestination,possiblytransformingthe
data along the way or providing the additional
functionality.
PrintStream APrintStreamaddsfunctionalitytoanotheroutputstream,
namelytheabilitytoprintrepresentationsofvariousdata
valuesconveniently.
OverviewofCharacterStreamClasses-
Characterstreamsaredefinedbyusingtwoclasshierarchies.Atthetoparetwo
abstract classes: Reader and Writer. These abstract classes handle Unicode character
streams.
TheJavahas severalconcrete subclasses ofeachof these. Theabstract Reader
and Writer classes define several key methods that the other stream classes implement.
Twoofthemostimportantmethodsareread()andwrite(),whichreadandwritecharacters
ofdata,respectively.Thesemethodsareoverriddenbyderivedstreamclasses.
Readerstreamclasses:-
Readerstreamclassesaredesignedtoreadcharacterformthefiles.Readerclass
is the base class for all other classes in this group. These classes are functionally very
similar to the input stream classes, except input streams use bytes as their fundamental
unitofinformation,whilereaderstreamsusecharacters.
The Reader class contains methods that are identical to those available in the
InputStream class. Therefore, Reader classes can perform almost all the functions
implementedbytheinputstreamclasses.
(HierarchyofReaderstreamClass)
TheReaderClass:-
ReaderisanabstractclassthatdefinesJava’smodelofstreamingcharacterinput.
AllofthemethodsinthisclasswillthrowanIOException.
MethodsofReaderClass:-
abstractvoidclose()
Closesthestream.Onceastreamhasbeenclosed,furtherread(),ready(),mark(),
or reset() invocations will throw an IOException. Closing a previously closed
stream,however,hasnoeffect.
voidmark()
Marks the present position in the stream. Subsequently calls to reset() will
attempt to reposition the stream to this point. Not all character input streams
supportthemark()operation.
booleanmarkSupported()
Tellswhetherthisstreamsupportsthemark()operation
intread()
Reads a single character and returns the integer representation of the next
available character from the invoking input stream. -1 is returned when end of
fileisencountered.
intread(char[]buffer)
Attemptstoreaduptobufferlengthcharactersintobufferandreturnstheactual
numberofcharactersthataresuccessfullyread.-1isreturnedwhenendoffileis
encountered.Thesubclassesofthereadermustimplementthis.
abstractintread(char[]buffer,intoffset,intnumChar)
Attemptstoreadup tonumCharcharbufferstartingatbufrfer[offset],returning
thenumberof charactersthataresuccessfullyread.-1isreturned whenendof
fileisencountered.Thesubclassesofthereadermustimplementthis.
booleanready()
Tellswhetherthisstreamisreadytoberead.Returnstrueifthenextinputrequest
willnotwait,otherwiseitreturnsafalse.
voidreset()
Resetthestream.Thismethodisnotsupportedbyallcharacterinputstreams.
longskip(longn)
Skips up to n characters and returns the number of characters skipped. This
throwsIllegalArgumentExceptionifnis–ve.
SummaryofReaderClasses:-
Reader Abstractclassforreadingcharacterstreams
BufferedReader Readtextfromacharacter-inputstream,bufferingcharacters
soastoprovidefortheefficientreadingofcharacters,arrays
andlines.
CharArrayReader Thisclassimplementsacharacterbufferthatcanbeusedasa
character-inputstream.
FileReader Convenienceclassforreadingcharacterfiles.
FilterReader Abstractclassforreadingfiltercharacterstreams.
InputStreamReader An InputStreamReader is a bridge from byte streams to
character stream: It reads bytes and decodes them into
charactersusingaspecifiedcharset.
PipedReader Pipedcharacterinputstream.
PushbackReader Acharacterstreamreaderthatallowscharacterstobepushed
backintothestream.
StringReader Acharacterstreamwhosesourceisastring.
WriterStreamClass:-
WriterStreamClassesaredesignedtowritecharactertofiles/outputdevices.The
writerclassisanabstractclass,whichactsasabaseclassforalltheotherwriterstream
class.
The base class provides support for all output operations by defining methods
thatareidenticalinthoseinOutputStreamclass.
The Writer class contains methods that are identical to those available in the
OutputStream class. Therefore, Writer classes can perform almost all the functions
implementedbytheoutputstreamclasses.
(HierarchyofWriterStreamClasses)
TheWriterClass:-
Writerisanabstractclassthatdefinesstreamingcharacteroutput.Allofthemethodsin
thisclassreturnavoidvalueandthrowanIOExceptioninthecaseoferrors.
MethodsofWriterclass:
abstractvoidclose()
Closesthestreamflushesitfirst.
abstractvoidflush()
Flushesthestream.
voidwrite(char[]cbuf)
Writesanarrayofcharacters.
abstractvoidwrite(char[]cbuf,intoff,intlen)
Writesa portion of anarray of characters beginningfrom specified offset.The
subclassesmustimplementthismethod.
voidwrite(intc)
Writesasinglecharactertotheinvokingoutputstream.Notethattheparameteris
an int, which allows you to call write with expressions without having to cast
thembacktochar.
voidwrite(Stringstr)
Writesastring.
voidwrite(Stringstr,intoff,intlen)
Writestheportionofthestringbeginningatthespecifiedoffset.
SummaryofWriterClass-
Writer Abstractclassforwritingtocharacterstreams.
BufferedWriter Writestexttoacharacter-outputstream,bufferingcharacters
soastoprovidefortheefficientwritingofsinglecharacters,
arrays,andstrings.
CharArrayWriter Thisclassimplementsacharacterbufferthatcanbeusedas
aWriter.
FileWriter Convenienceclassforwritingcharacterfiles.
FilterWriter Abstractclassforwritingfilteredcharacterstreams.
OutputStreamWriter AnOutputStreamWriterisabridgefromcharacterstreamsto
bytestreams:Characterswrittentoitareencodedintobytes
usingaspecifiedcharset.
PipedWriter Pipedcharacter-outputstreams.
PrintWriter Print formatted representations of objects to a text-output
stream.
StringWriter Acharacterstreamthatcollectsitsoutputinastringbuffer,
whichcanthenbeusedtoconstructastring.
FileClass-
Althoughmostiftheclassesdefinedbyjava.iooperateonstreams,theFileclass
doesnot.Itdealsdirectlywithfilesandthefilesystem.Thatis,thefileclassdoesnot
specifyhowinformationisretrievedfromorstoredinfiles.Itdescribesthepropertiesofa
itself.
Afileobjectisusedtoobtainormanipulatetheinformationassociatedwitha
diskfile,suchasthepermissions,time,dateanddirectorypath,andtonavigatesub-
directoryhierarchies.
Althoughtherearesevererestrictionontheirusewithinappletsforsecurityreasons,files
arestillacentralresourceforstoringpersistentandsharedinformation.
AdirectoryinJavaistreatedsimplyasafilewithoneadditionalproperty–alist
offilenamesthatcanbeexaminedbythelist()method.
publicFile(String);
publicFile(String,String);
publicFile(File,String);
publicFile(URI);
ThisconstructorwasaddedbyJava2,version1.4
publicStringgetName();
Returnsthenameofthefileordirectory
publicStringgetParent();
Returnstheparentdirectoryofthefilefromthepathspecifiedduringobjectcreation,or
nullifthispathnamedoesnotnameaparentdirectory.
publicStringgetPath();
Returnstherelativepath.
publicbooleanisAbsolute();
Testswhetherthisabstractpathnameisabsolute.
publicStringgetAbsolutePath();
Returnstheabsolute(complete)pathstartingfromroot.
publicbooleancanRead();
Testswhethertheapplicationcanreadthefiledenotedbythisabstractpathname.
publicbooleancanWrite();
Testswhethertheapplicationcanmodifythefiledenotedbythisabstract
pathname.
publicbooleanexists();
Testswhetherthefileordirectorydenotedbythisabstractpathnameexists.
publicbooleanisDirectory();
Testswhetherthefiledenotedbythisabstractpathnameisadirectory.
publicbooleanisFile();
Testswhetherthefiledenotedbythisabstractpathnameisnormalfile.
publicbooleanisHidden();
Testswhetherthefilenamedbythisabstractpathnameisahiddenfile.
publiclonglastModified();
Returnsthetimethatthefiledenotedbythisabstractpathnamewaslast
modified.
publiclonglength();
Returnsthelengthofthefiledenotedbythisabstractpathname.
publicbooleancreateNewFile()throwsjava.io.IOException;
Automaticallycreatesanew,emptyfilenamedbythisabstractpathnameifand
onlyifafilewiththisnamedoesnotyetexist.
publicbooleandelete();
Deletesthefileordirectorydenotedbythisabstractpathname.
publicString[]list();
Returnsanarrayofstringsnamingthefilesanddirectoriesinthedirectory
denotedbythisabstractpathname.ReturnsnullifFileobjectcorrespondstoa
file.
publicbooleanmkdir();
Createsthedirectorynamedbythisabstractpathname.
publicbooleanmkdirs();
Createsthedirectorynamedbythisabstractpathnameincludinganynecessary
butnonexistentparentdirectories.
publicbooleansetLastModified(long);
Setsthelastmodifiedtimeofthefileordirectorynamedbythisabstract
pathname.
publicbooleansetReadOnly();
Marksthefileordirectorynamedbythisabstractpathnamesothatonly
readoperationsareallowed.
publicbooleansetWritable(boolean);
publicbooleansetReadable(boolean);
publicbooleancanExecute();
publiclonggetTotalSpace();
publiclonggetFreeSpace();
publiclonggetUsableSpace();
booleanrenameTo(File);
Renamethefiledenotedbythisabstractpathname.
Examples-
Filef1=newFile(“/”);
Filef2=newFile(“/”,”autoexec.bat”);
Filef3=newFile(f1,”autoexec.bat”);
Note:
Java does the right thing With path separators between UNIX and Windows
conventions.Ifyouuseaforwardslash(/)onawindowsversionofjava,thepathwillstill
resolvecorrectly.
Remember,ifyouareusingthewindowsconvention(\)withastring.TheJava
conventionistousetheUNIX–andURLstyleforwardslashforpathseparators.
File defines many methods that obtain the standard properties of a File object.
TheFileclasshowever,isnotsymmetrical.Bythis,wemeanthattherearemainmethods
that allow you to examine the properties of a simple file object, but no corresponding
functionexiststochangetheseattributes.
Example15.1:
FollowingexampledemonstratesseveralmethodsoftheclassFile
1.importjava.io.*;
2.classFileTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.Filef=newFile(“/javaprog/ch15/15.1/FileTest.java”);
7.if(!f.exists())
8.f.createNewFile();
9.System.out.println(“Length=”+f.length()+”bytes”);
10.System.out.println(“Name=”+f.getName());
11.System.out.println(“Parent=”+f.getParent());
12.System.out.println(“Path=”+f.getPath());
13.System.out.println(“AbsolutePath=”+f.getAbsolutePath());
14.System.out.println(f.exists()?“Exists”:“Doesnotexist”);
15.System.out.println(f.isFile()?“isfile”:“notafile”);
16.System.out.println(f.canRead()?“isreadable”:“notreadable”);
17.System.out.println(f.canWrite()?“iswritable”:“notwritable”);
18.System.out.println(f.isDirectory()?“isdirectory”:“notadirectory”);
19.System.out.println(f.isHidden()?“ishidden”:“nothidden”);
20.System.out.println(f.isAbsolute()?“isabsolute”:“isnotabsolute”);
21.System.out.println(“Filelastmodified:”+f.lastModified());
22.//f.delete();
23.Filef3=newFile(“C:/tally72”);
24.Stringnm[]=f3.list();
25.System.out.println(“ListofFiles&Sub-Directoriesofc:/tally72”);
26.for(inti=0;i<nm.length;i++)
27.{
28.System.out.print(nm[i]);
29.Filef4=newFile(“c:/tally72/”+nm[i]);
30.if(f4.isFile()==true)
31.System.out.println(”ItisaFile”);
32.else
33.System.out.println(”ItisaDirectory”);
34.}
35.Filef5=newFile(“zzz”);
36.f5.mkdir();
37.Filef6=newFile(“yyy/aaa”);
38.f6.mkdirs();
39.}
40.}
Output:
Length=1782bytes
Name=FileTest.java
Parent=\javaprog\ch15\15.1
Path=\javaprog\ch15\15.1\FileTest.java
AbsolutePath=C:\javaprog\ch15\15.1\FileTest.java
Exists
isfile
isreadable
iswritable
notadirectory
nothidden
isnotabsolute
Filelastmodified:1236824168000
ListofFiles&Sub-Directoriesofc:/tally72
TALLY.REWItisaFile
Tally.iniItisaFile
sentinel.sysItisaFile
sentinel.vxdItisaFile
spnsrv9x.exeItisaFile
spnsrvnt.exeItisaFile
stat.slkItisaFile
tally72.exeItisaFile
tallylic9xserver.exeItisaFile
tallylicserver.exeItisaFile
tallysav.datItisaFile
tallywin.datItisaFile
tally.impItisaFile
DataItisaDirectory
FileInputStream-
Itisadirectsub-classoftheInputStreamclass.Toopenafileforreading,you
simplycreateanobjectofFileInputStreamclass,specifyingthenameofthefile(directly
ofindirectly)asanargumenttotheconstructor.
publicFileInputStream(String)throwsFileNotFoundException;
CreatesaFileInputStreambyopeningaconnectiontoanactualfile,thefile
namedbythepathnamefilePathinthefilesystem.
publicFileInputStream(File)throwsFileNotFoundException;
CreatesaFileInputStreambyopeningaconnectiontoanactualfile,thefile
namedbytheFileobjectfileinthefilesystem.
publicnativeintread()throwsIOException;
publicintread(byte[])throwsIOException;
publicintread(byte[],int,int)throwsIOException;
publicnativelongskip(long)throwsIOException;
publicnativeintavailable()throwsIOException;
publicvoidclose()throwsIOException;
FileOutputStream-
It is direct sub-class of the OutputStream class. To open a file for writing, we
simplycreateanobjectofFileOutputStreamclass,specifyingthenameofthefile(directly
orindirectly)asanargumenttotheconstructor.
publicFileOutputStream(String)throwsFileNotFoundException;
Createsanoutputfilestreamtowritetothefilewiththespecifiedname.
publicFileOutputStream(String,boolean)
throwsjava.io.FileNotFoundException;
Createanoutputfilestreamtowritetothefilewiththespecifiedname.
publicFileOutputStream(File)throwsFileNotFoundException;
Creates a file output stream to write to the file represented by the specified File
object.
publicFileOutputStream(File,boolean)throwsFileNotFoundException;
CreatesafileoutputstreamtowritetothefilerepresentedbythespecifiedFile
object.
publicnativevoidwrite(int)throwsjava.io.IOException;
publicvoidwrite(byte[])throwsjava.io.IOException;
publicvoidwrite(byte[],int,int)throwsjava.io.IOException;
publicvoidclose()throwsjava.io.IOException;
Example15.2
1.importjava.io.*;
2.classFileRead
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.FileInputStreamfin=null;
7.inta;
8.try
9.{
10.fin=newFileInputStream(args[0]);
11.System.out.println(“No.ofcharacterstoread=”+fin.available());
12.fin.skip(3);
13.a=fin.read();
14.while(a!=-1)
15.{
16.System.out.print((char)a);
17.a=fin.read();
18.}
19.System.out.println(“No.ofcharacterstoread=”+fin.available());
20.fin.close();
21.}
22.catch(ArrayIndexOutOfBoundsExceptione)
23.{
24.System.out.println(e);
25.}
26.catch(FileNotFoundExceptione)
27.{
28.System.out.println(e);
29.}
30.catch(IOExceptione)
31.{
32.System.out.println(e);
33.}
34.}
35.}
Output:
javaFileReadA.txt
No.ofcharacterstoread=20
MatrixComputers
No.ofcharacterstoread=0
Example15.3:
1.importjava.io.*;
2.classFileCopy
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.FileInputStreamfin=null;
7.FileOutputStreamfout=null;
8.fin=newFileInputStream(args[0]);
9.fout=newFileOutputStream(args[1]);
10.inta;
11.a=fin.read();
12.while(a!=-1)
13.{
14.fout.write(a);
15.a=fin.read();
16.}
17.fin.close();fout.close();
18.}
19.}
Example15.4
1.importjava.io.*;
2.classCopyFile
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.intn;
7.FileInputStreamfin=newFileInputStream(“A.txt”);
8.FileOutputStreamfout=newFileOutputStream(“B.txt”);
9.byteb[]=newbyte[10];
10.n=fin.read(b);
11.while(n!=-1)
12.{
13.fout.write(b,0,n);
14.n=fin.read(b);
15.}
16.fin.close();
17.fout.close();
18.}
19.}
FileReader-
TheFileReaderclasscreatesaReaderthatyoucanusetoreadthecontentsofa
file.Itstwomostcommonlyusedconstructorsare:
FileReader(Filefile)-
CreatesaFileReaderstreamtoreadfromthespecifiedfile.
FileReader(StringfileName)-
CreatesaFileReaderstreamtoreadfromthespecifiedfile.
Note: Either of the constructors can throw a FileNotFoundException if the file dies not
exist,isadirectoryratherthanaregularfile,orforsomeotherreasoncannotbeopened
forreading.
FileWriter
TheFileWriterclasscreatesawriterthatyoucanuseto writetoafile.Itstwo
mostcommonlyusedconstructorsare:
Constructors:-
FileWriter(Filefile)
ConstructorsaFileWriterobjecttowritetothespecifiedfile.
FileWriter(StringfileName)
ConstructorsaFileWriterobjecttowritetothespecifiedfile.
FileWriter(Filefile,booleanappend)
ConstructorsaFileWriterobjecttowritetothespecifiedfileintheappendmode.
FileWriter(Sringfilename,booleanappend)
ConstructorsaFileWriterobjecttowritetothespecifiedfileinthe appendmode.If
firsttwoconstructorsareusedthenalwaysanewfileiscreated.Iffilewiththespecified
nameexists,itgetsdestroyed.Ifthelasttwoconstructorsareusedandappendflagisfalse
thentheybehavelikefirsttwoconstructors.
Iftheappendflagistruethenfileisopenedintheappendmodei.e.iffilealready
existsthenfilepointerisplacedattheendofthefileandiffiledoesnotexistthennewfile
iscreated.
Note:
TheseconstructorscanthrowanIOExceptionifthefileexistsbutisadirectory
ratherthanaregularfile,doesnotexistbutcannotbecreated,orcannotbeopenedforany
otherreason.
Forexample,whenyouattempttoopenaread-onlyfile,anIOExceptionwillbe
thrown.
Example15.5
1.importjava.io.*;
2.classFileCopy
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.FileReaderfin=null;
7.FileWriterfout=null;
8.fin=newFileReader(args[0]);
9.fout=newFileWriter(args[1]);
10.inta;
11.a=fin.read();
12.while(a!=-1)
13.{
14.fout.write((char)a);
15.a=fin.read();
16.}
17.fin.close();
18.fout.close();
19.}
20.}
RandomAccessFile-
RandomAccessFile encapsulates a random-access file. The RandomAccessFile
enablesustoreadandwritebytes,textandprimitivedatatypesfrom/tolocationinafile
(when used with appropriate access permissions). It is not derived from InputStream.
Instead, it implements the interfaces DataInput and DataOutput, which define the basic
I/Omethods.Italsosupportspositioningrequests-thatis,youcanpositionthefilepointer
anywherewithinthefile
Themodeargumentspecifiestheaccessmodeinwhichthefileistobeopened.
Thepermittedvaluesandtheirmeaningsare:
ValueMeaning
“r”Openforreadingonly.Invokinganyofthewritemethodsofthe
resultingobjectwillcauseanIOExceptiontobethrown.
“rw”Openforreadingandwriting.Ifthefiledoesnotalreadyexistthenan
attemptwillbemadetocreateit.
“rws”Openforreadingandwriting,aswith“rw”,andalsorequirethat
everyupdatetothefile’scontentormetadatabewrittensynchronouslytothe
underlyingstoragedevice.
“rwd”Openforreadingandwriting,aswith“rw”.Andalsorequirethat
everyupdatetothefile’scontent(data)bewrittensynchronouslytotheunderlying
storagedevice.
MethodsofRandomAccessFileclass:-
BesidemethodsoftheDataInputandDataOutputinterfaces,someofthecommonlyused
methodsofthisclassare:
publicRandomAccessFile(String,String)throwsjava.io.FileNotFoundException;
Createsarandomaccessfilestreamtoreadfrom,andoptionallytowriteto,thefile
specifiedname.
publicRandomAccessFile(File,String)throwsFileNotFoundException;
Createsarandomaccessfilestreamtoreadfrom,andoptionallytowriteto,thefile
specifiedbytheFileargument.
publicnativeintread()throwsjava.io.IOException;
publicintread(byte[],int,int)throwsjava.io.IOException;
publicintread(byte[])throwsjava.io.IOException;
publicintskipBytes(int)throwsjava.io.IOException;
publicnativevoidwrite(int)throwsjava.io.IOException;
publicvoidwrite(byte[])throwsjava.io.IOException;
publicvoidwrite(byte[],int,int)throwsjava.io.IOException;
publicnativelonggetFilePointer()throwsjava.io.IOException;
Returnstheoffsetfromthebeginningofthefile,inbytes,atwhichthenextreadorwrite
occurs.
publicnativevoidseek(long)throwsjava.io.IOException;
Here,newPosspecitiesthenewposition,inbytesofthefilepointerfromthebeginning
ofthefile.Afteracalltoseek(),thenextreadorwriteoperationwilloccuratthenew
fileposition.
publicnativelonglength()throwsjava.io.IOException;
publicnativevoidsetLength(long)throwsjava.io.IOException;
Setsthelengthofthisfile.Thismethodcanbeusedtolengthenorshortenafile.Ifthe
fileislengthened,theaddedportionisundefined.
publicvoidclose()throwsjava.io.IOException;
publicfinalbooleanreadBoolean()throwsjava.io.IOException;
publicfinalbytereadByte()throwsjava.io.IOException;
publicfinalintreadUnsignedByte()throwsjava.io.IOException;
publicfinalshortreadShort()throwsjava.io.IOException;
publicfinalintreadUnsignedShort()throwsjava.io.IOException;
publicfinalcharreadChar()throwsjava.io.IOException;
publicfinalintreadInt()throwsjava.io.IOException;
publicfinallongreadLong()throwsjava.io.IOException;
publicfinalfloatreadFloat()throwsjava.io.IOException;
publicfinaldoublereadDouble()throwsjava.io.IOException;
publicfinaljava.lang.StringreadLine()throwsjava.io.IOException;
publicfinaljava.lang.StringreadUTF()throwsjava.io.IOException;
publicfinalvoidwriteBoolean(boolean)throwsjava.io.IOException;
publicfinalvoidwriteByte(int)throwsjava.io.IOException;
publicfinalvoidwriteShort(int)throwsjava.io.IOException;
publicfinalvoidwriteChar(int)throwsjava.io.IOException;
publicfinalvoidwriteInt(int)throwsjava.io.IOException;
publicfinalvoidwriteLong(long)throwsjava.io.IOException;
publicfinalvoidwriteFloat(float)throwsjava.io.IOException;
publicfinalvoidwriteDouble(double)throwsjava.io.IOException;
publicfinalvoidwriteBytes(java.lang.String)throwsjava.io.IOException;
publicfinalvoidwriteChars(java.lang.String)throwsjava.io.IOException;
publicfinalvoidwriteUTF(java.lang.String)throwsjava.io.IOException;
Example15.6
1.importjava.io.*;
2.classRandomIO
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.RandomAccessFilefile=null;
7.try
8.{
9.file=newRandomAccessFile(“rand.dat”,“rw”);
10.file.writeChar(‘X’);
11.file.writeInt(1999);
12.file.writeDouble(222.44);
13.System.out.println(“FilepointerPos:”+file.getFilePointer());
14.file.seek(0);
15.System.out.println(file.readChar());
16.System.out.println(file.readInt());
17.System.out.println(file.readDouble());
18.System.out.println(“FilepointerPos:”+file.getFilePointer());
19.file.seek(2);
20.System.out.println(“FilepointerPos:”+file.getFilePointer());
21.System.out.println(file.readInt());
22.file.seek(file.length());
23.file.writeBoolean(false);
24.file.seek(14);
25.System.out.println(file.readBoolean());
26.System.out.println(“FilepointerPos:”+file.getFilePointer());
27.System.out.println(file.readInt());//EOFExpecption
28.}
29.catch(EOFExceptione)
30.{
31.System.out.println(“Tryingtoreadafterendoffile”);
32.}
33.finally
34.{
35.file.close();
36.}
37.
38.}
39.}
Output:
FilepointerPos:14
X
1999
222.44
FilepointerPos:14
FilepointerPos:2
1999
false
FilepointerPos:15
Tryingtoreadafterendoffile
Note:AnEOFExceptionoccursifattemptismadetoreadafterendoffile.
ByteArrayInputStream
AByteArrayInputStreamcontainsaninternalbufferthatcontainbytesthatmay
bereadfromthestream.ByteArrayInputStreamisanimplementationofaninputstream
thatusesabytearrayasthesource.
Thisclasshas twoconstructors,eachofwhich requiresabyte arraytoprovide
thedatasource.
AByteArrayInputStreamimplementbothmark()andreset()methods.However,
ifmark()hasnotbeencalled,thenreset()setsthestreampointertothestarofthestream.
publicByteArrayInputStream(byte[]);
publicByteArrayInputStream(byte[],int,int);
publicsynchronizedintread();
publicsynchronizedintread(byte[],int,int);
publicsynchronizedlongskip(long);
publicsynchronizedintavailable();
publicbooleanmarkSupported();
publicvoidmark(int);
publicsynchronizedvoidreset();
publicvoidclose()throwsIOException;
Example15.7:
1.importjava.io.*;
2.classByteArrayInputStreamTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.Strings1=“abcdefghijk”;
7.byteb[]=s1.getBytes();
8.ByteArrayInputStreamb1=newByteArrayInputStream(b);
9.inta;
10.while((a=b1.read())!=-1)
11.{
12.System.out.print((char)Character.toUpperCase(a));
13.}
14.b1.close();
15.}
16.}
Output:ABCDEFGHIJK
ByteArrayOutputStream-
Theclass implementsanoutput streamin which thedata iswritteninto abyte
array.ByteArrayOutputStreamisanimplementationofanoutputstreamthatusesabyte
arrayasthedestination.
The buffer is hold in the protected buf field of ByteArrayOutputStream. The
buffer size will be increased automatically, if needed. The number if bytes hold by the
bufferiscontainedintheprotectedcountfieldofByteArrayOutputStream.
publicjava.io.ByteArrayOutputStream();
Createsanewbytearrayoutputstream.Thebuffercapacityisinitially32bytes,though
itssizeincreasesifnecessary.
publicjava.io.ByteArrayOutputStream(int);
Createsanewbytearrayoutputstream,withabuffercapacityofthespecifiedsize,in
bytes.
publicsynchronizedvoidwrite(int);
publicsynchronizedvoidwrite(byte[],int,int);
publicsynchronizedvoidwriteTo(java.io.OutputStream)throws
java.io.IOException;
publicsynchronizedvoidreset();
publicsynchronizedbyte[]toByteArray();
publicsynchronizedintsize();
publicsynchronizedjava.lang.StringtoString();
publicsynchronizedjava.lang.StringtoString(java.lang.String)throws
java.io.UnsupportedEncodingException;
publicsynchronizedjava.lang.StringtoString(int);
publicvoidclose()throwsjava.io.IOException;
Example15.8
1.importjava.io.*;
2.classByteArrayOutputStreamTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.ByteArrayOutputStreamb1=newByteArrayOutputStream();
7.b1.write(‘a’);
8.Strings1=“abcdefghijk”;
9.bytearr1[]=s1.getBytes();
10.b1.write(arr1);
11.System.out.println(b1);//toString()
12.//Displayusingforloop
13.bytearr2[]=b1.toByteArray();
14.for(inti=0;i<arr2.length;i++)
15.{
16.System.out.print((char)arr2[i]);
17.}
18.System.out.println();
19.//Displayusingforeachloop
20.for(inti:arr2)
21.{
22.System.out.print((char)i);
23.}
24.b1.close();
25.}
26.}
Output:
aabcdefghijk
aabcdefghijk
aabcdefghijk
CharArrayReader-
TheCharArrayReader isan implementationof areader streamthatuses achar
arrayasthesource.Thisclasshastwoconstructors,eachofwhichrequiresachararrayto
providethedatasource.
Constructors:
CharArrayReader(char[]buf)
CratesaCharArrayReaderfromthespecifiedarrayofchars.
CharArrayReader(char[]buf,intoffset,intlength)
CratesaCharArrayReaderfromthespecifiedarrayofchars.Theresultingreaderwill
startreadingatthegivenoffset.Thetotalnumberofcharvaluesthatcanbereadfromthis
readerwillbeeitherlengthorbuf.length.
Example15.9
1.importjava.io.*;
2.classCharArrayReaderTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.Stringtmp=“abcdefghijklmnopqrstuvwxyz”;
7.intlength=tmp.length();
8.charc[]=newchar[length];
9.tmp.getChars(0,length,c,0);
10.CharArrayReaderinput1=newCharArrayReader(c);
11.CharArrayReaderinput2=newCharArrayReader(c,0,5);
12.inti;
13.while((i=input1.read())!=-1)
14.{
15.System.out.print((char)i);
16.}
17.System.out.println();
18.while((i=input2.read())!=-1)
19.{
20.System.out.print((char)i);
21.}
22.}
23.}
Output:
abcdefghijklmnopqrstuvwxyz
abcde
CharArrayWriter
CharArrayWriterisanimplementationof awriterstreamthatuses achararray
bufferasthedestination.
Constructors:
CharArrayWriter()
CharArrayWriter(intinitialSize)
Inthefirstform,abufferwithadefaultsizeiscreated.Inthesecond,abufferis
createdwiththesizeequaltothatspecifiedbytheparameterinitialSize.
The buffer is hold in the buf field of CharArrayWriter. The buffer size will be
increasedautomatically,ifneeded.Thenumberifcharacterheldbythebufferiscontained
inthecountfieldofCharArrayWriter.Bothbufandcountareprotectedfields.
Example15.10
1.importjava.io.*;
2.classCharArrayWriterTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.CharArrayWriterf=newCharArrayWriter();
7.Strings=“Thisshouldendupinthearray”;
8.charbuf[]=newchar[s.length()];
9.s.getChars(0,s.length(),buf,0);
10.f.write(buf);
11.System.out.println(f.toString());
12.charc[]=f.toCharArray();
13.for(inti=0;i<c.length;i++)
14.{
15.System.out.print(c[i]);
16.}
17.FileWriterf2=newFileWriter(“test.txt”);
18.f.writeTo(f2);
19.f2.close();
20.f.reset();
21.System.out.println();
22.System.out.println(“Afterreset:”+f.toString());
23.for(inti=0;i<3;i++)
24.f.write(‘A’);
25.System.out.println(f.toString());
26.}
27.}
Output:
Thisshouldendupinthearray
Thisshouldendupinthearray
Afterreset:
AAA
PushbackInputStream-
A PushbackInputStream adds functionality to another input stream, namely the
ability to “pushback” or “unread” one byte. One of the use of buffering is the
implementationofpushback.
Pushbackisusedonaninputstreamtoallowabytetobereadandthenreturned
to the stream. Beyond the familiar methods of the InputStream class,
PushbackInputStreamprovidesunread()method,shownhere:
publicjava.io.PushbackInputStream(java.io.InputStream,int);
CreatesaPushbackInputStreamwithapushbackbufferofthespecifiedsize,andsaves
itsargument,theinputstreamin,forlateruse.Thisallowsmultiplebytestobereturned
totheinputstream.
publicjava.io.PushbackInputStream(java.io.InputStream);
CreatesaPushbackInputStreamandsavesitsargument,theinputstreamin,forlateruse.
Thisallowsonebytetobereturnedtotheinputstream.
publicintread()throwsjava.io.IOException;
publicintread(byte[],int,int)throwsjava.io.IOException;
publicvoidunread(int)throwsjava.io.IOException;
Pushbackabytebycopyingittothefrontofthepushbackbuffer
publicvoidunread(byte[],int,int)throwsjava.io.IOException;
Pushbackaportionofanarrayofbytesbycopyingittothefrontofthepushback
buffer.
publicvoidunread(byte[])throwsjava.io.IOException;
Pushbackanarrayofbytesbycopyingittothefrontofthepushbackbuffer.
publicintavailable()throwsjava.io.IOException;
publiclongskip(long)throwsjava.io.IOException;
publicbooleanmarkSupported();
PushbackInputStreamhasthesideeffectofinvalidatingthemark()orreset()methodsof
theInputStreamusedtocreateit.UsemarkSupported()methodtocheckanystreamon
whichyouaregoingtousemark()/reset().
publicsynchronizedvoidmark(int);
publicsynchronizedvoidreset()throwsjava.io.IOException;
publicsynchronizedvoidclose()throwsjava.io.IOException;
Example15.11:
1.importjava.io.*;
2.classPushbackInputStreamTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.FileInputStreamfin=newFileInputStream(“A.txt”);
7.PushbackInputStreamp1=newPushbackInputStream(fin);
8.intch=p1.read();
9.System.out.println((char)ch);
10.ch=p1.read();
11.System.out.println((char)ch);
12.ch=p1.read();
13.System.out.println((char)ch);
14.p1.unread(ch);//orp1.unread(‘z’);
15.ch=p1.read();
16.System.out.println((char)ch);
17.}
18.}
Output:A.txtcontains“MatrixComputers”
m
a
t
t
PushbackReader
Acharacterstreamreaderthatallowscharacterstobepushedbackintothe
stream.
PushbackReader class allows one or more character to be returned to the input stream.
Thisallowsyoutolookaheadintheinputstream.
publicjava.io.PushbackReader(java.io.Reader,int);
Creates a pushback reader with a pushback buffer of the given size.
PushbackReader class provides unread() method, which returns one or more
characterstothemyokinginputstream.
publicjava.io.PushbackReader(java.io.Reader);
Createsapushbackreaderwithaon-characterpushbackbuffer.
publicintread()throwsjava.io.IOException;
publicintread(char[],int,int)throwsjava.io.IOException;
publicvoidunread(int)throwsjava.io.IOException;
Pushbackasinglecharacter.
publicvoidunread(char[],int,int)throwsjava.io.IOException;
Pushbackaportionofanarrayofcharactersbycopyingittothefrontofthe
pushbackbuffer.
publicvoidunread(char[])throwsjava.io.IOException;
Pushbackanarraybycopyingittothefrontofthepushbackbuffer.
publicbooleanready()throwsjava.io.IOException;
publicvoidmark(int)throwsjava.io.IOException;
publicvoidreset()throwsjava.io.IOException;
publicbooleanmarkSupported();
publicvoidclose()throwsjava.io.IOException;
publiclongskip(long)throwsjava.io.IOException;
Note:-AnIOExceptionwillbethrownifthereisanattempttoreturnacharacterwhenthe
pushbackbufferisfull.
Example15.12:
1.importjava.io.*;
2.classPushbackReaderTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.FileReaderfr=newFileReader(“A.txt”);
7.PushbackReaderpr=newPushbackReader(fr);
8.intch=pr.read();
9.System.out.println((char)ch);
10.ch=pr.read();
11.System.out.println((char)ch);
12.ch=pr.read();
13.System.out.println((char)ch);
14.pr.unread(ch);
15.ch=pr.read();
16.System.out.println((char)ch);
17.}
18.}
Output:m
a
t
t
SequenceInputStream:-
TheSequenceInputStreamclassisabytestreamthatallowsyoutoconcatenate
multipleInputStreams.TheconstructionofasequenceInputStreamisdifferentfromany
otherInputStream.ASequenceInputStreamconstructoruseseitherapairofInputStream
classesoranEnumerationofInputStreamclassesasitsargument:
SequenceInputStream(InputStreamis1,InputStreamis2)
Initializes a newly created SequenceInputStream by remembering the two
arguments,whichwillbereadinorder,firstis1andthenis2,toprovidethebytestobe
readfromthisSequenceInputStream.
SequenceInputStream(Enumeratione)
InitializesanewlycreatedSequenceInputStreambyrememberingtheargument,
whichmustbeanEnumerationthatproducesobjectswhoserun-timetypeisInputStream.
Operationally, the class fulfills read requests from the first InputStream until it
runs out and then switches over to the second one. In the case of Enumeration, it will
continuethroughalloftheInputStreamsuntilendofthelastoneisreached.
Example15.13InthefollowingexamplegivethefilenamesasCommandlinearguments:
1.importjava.io.*;
2.classSequenceInputStreamTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.FileInputStreamf1=newFileInputStream(args[0]);
7.FileInputStreamf2=newFileInputStream(args[1]);
8.FileOutputStreamf3=newFileOutputStream(args[2]);
9.SequenceInputStreamsis=newSequenceInputStream(f1,f2);
10.intc;
11.while((c=sis.read())!=-1)
12.{
13.f3.write(c);
14.}
15.f3.close();f1.close();f2.close();
16.}
17.}
Output:
javaSequenceInputStreamTestA.txtB.txtC.txt
PrintStream:-
It is a byte stream class, which extends the FilterOutputStream. A PrintStream
addsfunctionalitytoanotheroutputstream,namelytheabilitytoprintrepresentationsof
variousdatavaluesconveniently.
Optionally,aPrintStreamcanbecreatedsoastoflushautomatically;thismeans
that the flush method is automatically invoked after a byte array is written, one of the
printlnmethodsisinvoked,oranewlinecharacterorbyte(‘\n’)iswritten.
All characters printed by a PrintStream are converted are converted into bytes
usingtheplatform’s defaultcharacterencoding andthenwrittentothe OutputStreamor
Filespecifiedintheconstructor.
PrintStream supports the print() and println() methods for all types, including
object.Ifanargumentisnotasimpletype,thePrintStreammethodswillcalltheobject’s
toString()methodandthenprinttheresult.
Constructors:
PrintStream(Filefile)
Createsanewprintstream,withoutautomaticlineflushing,withthespecifiedfile.
PrintStream(StringfileName)
Creates a new print stream, without automatic line flushing, with the specified
filename.
PrintStream(OutputStreamout)
Createsanewprintstream,commentedtothespecifiedOutputStream.
PrintStream(OutputStreamout,boleanautoFlush)
Createsanewprintstream,connectedtothespecifiedOutputStream.
Example15.14
1.importjava.io.*;
2.classPrintStreamTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.PrintStreamps=newPrintStream(System.out,true);
7.ps.println(“Thisisastring”);
8.inti=-7;
9.ps.println(i);
10.doubled=4.5e-7;
11.ps.println(d);
12.}
13.}
Output:
Thisisastring
-7
4.5E-7
Example15.15
1.importjava.io.*;
2.classPrintStreamTest2
3.{
4.publicstaticvoidmain(Stringargv[])throwsIOException
5.{
6.FileOutputStreamfout=newFileOutputStream(“test.dat”);
7.PrintStreamps=newPrintStream(fout,true);
8.ps.println(“Thisisastring”);
9.inti=-7;
10.ps.println(i);
11.doubled=4.5e-7;
12.ps.println(d);
13.}
14.}
PrintWriter:-
AlthoughusingSystem.outtowritetotheconsoleisstillpermissibleunderJava,
itsuseisrecommendedmostlyfordebuggingpurposeorforsampleprograms.
For real-world programs, the recommended method of writing to the console
whenusingjavaisthroughaPrintWriterstream.PrintWriterisoneofthecharacter-based
classes.Usingacharacter-basedclassforconsoleoutputmakesiteasiertointernationalize
yourprogram.
Constructors:-
PrintWriter(Filefile)
Creates a new PrintWriter, without automatic line flushing, for writing to the
specifiedfile.
PrintWriter(StringfileName)
Creates a new PrintWriter, without automatic line flushing, for writing to the
specifiedfile.
PrintWriter(OutputStreamout)
Creates a new PrintWriter, without automatic line flushing, for writing to the
specifiedOutputStream.
PrintWriter(OutputStreamout,booleanautoFlush)
CreatesanewPrintWriterforwritingtothespecifiedOutputStream.
PrintWriter(Writerout)
Creates a new PrintWriter, without automatic line flushing, for writing to the
specifiedWriter.
PrintWriter(Writerout,BooleanautoFlush)
CreatesanewPrintWriterforwritingtothespecifiedWriter.
Themostcommonlyusedconstructoris:
PrintWriter(OutputStreamos,booleanflushOnNewLine)
Here, os is an object of type OutputStream, and flushOnNewLine controls
whether Java flushes the output stream every time a println() method is called. If
flushOnNewLine is true, flushing automatically takes place. If false, flushing is not
automatic.
PrintWritersupportprint()andprintln()methodsforalltypesincludingobjects.
If an argument is not a simple type, the PrintWriter methods call the object’s toString()
methodandthenprinttheresult.
To write the console by using a PrintWriter, specify System.out for the output
streamandflushthestreamaftereachnewlime.Forexample,thislineofcodecreatesa
PrintWriterthatisconnectedtoconsoleoutput.
PrintWriterpw=newPrintWriter(System.out,true)
Example15.16
1.importjava.io.*;
2.classPrintWriterTest
3.{
4.publicstaticvoidmain(Stringargv[])throwsIOException
5.{
6.PrintWriterpw=newPrintWriter(System.out,true);
7.pw.println(“Thisisastring”);
8.inti=-7;
9.pw.println(i);
10.doubled=4.5e-7;
11.pw.println(d);
12.}
13.}
Output:
Thisisastring
-7
4.5E-7
Example15.17
1.importjava.io.*;
2.classPrintWriterTest1
3.{
4.publicstaticvoidmain(Stringargv[])throwsIOException
5.{
6.FileWriterfout=newFileWriter(“test.dat”);
7.PrintWriterpw=newPrintWriter(fout,true);
8.pw.println(“Thisisastring”);
9.inti=-7;
10.pw.println(i);
11.doubled=4.5e-7;
12.pw.println(d);
13.}
14.}
Example15.18
1.importjava.io.*;
2.classPrintWriterTest2
3.{
4.publicstaticvoidmain(Stringargv[])throwsIOException
5.{
6.PrintWriterpw=newPrintWriter(“test.dat”);
7.pw.println(“Thisisastring”);
8.inti=-7;
9.pw.println(i);
10.doubled=4.5e-7;
11.pw.println(d);
12.pw.close();
13.}
14.}
PipedInputStreamandPipedOutputStream:-
A piped output stream can be connected to a piped input stream to create a
communications pipe. The piped output stream is the sending end of the pipe. A piped
inputstream should beconnected toa piped outputstream; the pipedinput streamthen
provideswhateverdatabytesarewrittentothepipedoutputstream.
Typically,dataisreadfromaPipedInputStreamobjectbyonethreadanddatais
writtentothecorrespondingPipedOutputStreambysomeotherthread.Attemptingtouse
bothobjectsfromasinglethreadisnotrecommendedasitmaydeadlockthethread.The
piped input stream contains a buffer, decoupling read operations from write operations,
withinlimits.
Constructors:-
PipedInputStream()
CreatesaPipedInputStreamsothatitisnotyetconnected.
PipedInputStream(PipedInputStreamsrc)
CreatesaPipedInputStreamsothatitisconnectedtotheoutputstreamsrc.
PipedOutputStream()
CreatesaPipedoutputstreamthatisnotyetconnectedtoapipedinputstream.
PipedOutputStream(PipedInputStreamsnc)
Createsapipedoutputstreamconnectedtothespecifiedpipedinputstream.
Example15.19
1.importjava.io.*;
2.classTextGeneratorextendsThread
3.{
4.OutputStreamout;
5.TextGenerator(OutputStreamout)
6.{
7.this.out=out;
8.}
9.publicvoidrun()
10.{
11.try
12.{
13.try
14.{
15.for(byteb=65;b<=90;b++)
16.out.write(b);
17.}
18.finally
19.{
20.out.close();
21.}
22.}
23.catch(IOExceptione)
24.{
25.System.out.println(e);
26.}
27.}
28.}
29.classPipe
30.{
31.publicstaticvoidmain(Stringargs[])throwsIOException
32.{
33.PipedOutputStreamout=newPipedOutputStream();
34.PipedInputStreamin=newPipedInputStream(out);
35.TextGeneratordata=newTextGenerator(out);
36.data.start();
37.intch;
38.while((ch=in.read())!=-1)
39.System.out.print((char)ch);
40.}
41.}
Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
PipedReaderandPipedWriter:-
TheirfunctionalityissameasthatofPipedInputStreamandPipedOutputStream
withtheonlydifferencethattheyarecharacterstreams.
Constructors:-
PipedReader()
CreatesaPipedReadersothatitisnotyetconnected.
PipedReader(PipedWritersrc)
CreatesaPipedReadersothatitisconnectedtothepipedwritersrc.
PipedWriter()
CreatesaPipedwriterthatisnotyetconnectedtoapipedreader.
PipedWriter(PipedReadersnk)
Createsapipedwriterconnectedtothespecifiedpipedreader.
Example15.20
1.importjava.io.*;
2.classTextGeneratorextendsThread
3.{
4.Writerout;
5.TextGenerator(Writerout)
6.{
7.this.out=out;
8.}
9.publicvoidrun()
10.{
11.try
12.{
13.try
14.{
15.for(charc=‘a’;c<=‘z’;c++)
16.out.write(c);
17.}
18.finally
19.{
20.try
21.{
22.Thread.sleep(2000);
23.}
24.catch(Exceptione){}
25.System.out.println(“aaaaaaaaaaaaa”);
26.if(true)
27.return;//IOException:pipeBroken
28.out.close();//IOException:Writeenddead
29.}//OKifthreadfinishesafterclosingthepipe
30.}
31.catch(IOExceptione){System.out.println(e);}
32.}
33.}
34.classPipe2
35.{
36.publicstaticvoidmain(Stringargv[])throwsIOException
37.{
38.PrintStreamps=newPrintStream(System.out);
39.PipedWriterout=newPipedWriter();
40.PipedReaderin=newPipedReader(out);
41.TextGeneratordata=newTextGenerator(out);
42.data.start();intch;
43.while((ch=in.read())!=-1)
44.System.out.print((char)ch);
45.}
46.}
Output:
abcdefghijklmnopqrstuvwxyzaaaaaaaaaaaaa
Exceptioninthread“main”java.io.IOException:Pipebroken
atjava.io.PipedReader.read(UnknownSource)
atPipe2.main(Pipe2.java:43)
TheFilteredByteStreams:-
The filtered streams are simply wrappers around underlying input or output
streamsthattransparentlyprovidesomeextendedleveloffunctionality.typicalextensions
are buffering, zip/unzip etc. The filtered byte streams are FilterInputStream,
FilterOutputStream.Theirconstructorsare:
FilterInputStream(InputStreamin)
CreatesaFilterInputStreambyassigningtheargumentintothefieldthis.insoas
torememberitforlateruse.
FilterOutputStream(OutputStreamout)
Creates an output Stream filter built on top of the specified underlying output
stream.
ThemethodsprovidedintheseclassesareidenticaltothoseinInputStreamand
OutputStream.
BufferedByteStreams:-
Forthebyte-orientedstreams,abufferedstreamextendsafilteredstreamclassby
attachingamemorybuffertotheI/Ostreams.ThisbufferallowsJavatodoI/Ooperations
onmorethanabyteattime,henceincreasingperformance.
Because, the buffer is available, skipping, marking, and resetting of the stream
become possible. The buffered byte stream classes are BufferedInputStream and
BufferedOutputStream.PushbackInputStreamalsoimplementsabufferedstream.
TheBufferedInputStream:-
Buffering I/O is a very common performance optimization. Java’s
BufferedInputStreamclassallowsyouto“wrap”anyInputStreamintoabufferedstream
andachievethisperformanceimprovement.
BufferedInputStreamhastwoconstructors:
BufferedInputStream(InputStreamin)
creates a BufferedInputStream and saves its argument, the input stream in, for
lateruse.aninternalbufferarrayiscreatedandstoredinbuf.
BufferedInputStream(InputStreamin,intsize)
Creates a BufferdInputStream with the specified buffer size, and saves its
argument,theinputstreamin,forlateruse.
Buffering an input stream also provides the foundation required to support
moving backward in the available buffer. Beyond the read() and skip() methods
implementedinanyInputStream,BufferedInputStreamalsosupportsmark()andreset()
methods.thissupportisreflectedbyBufferedInputStream.markSupported()returningtrue.
Example15.21
1.importjava.io.*;
2.classBufferedInputStreamTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.FileInputStreamfin=newFileInputStream(“A.txt”);
7.BufferedInputStreamb1=newBufferedInputStream(fin);
8.for(inti=1;i<=10;i++)
9.{
10.System.out.print((char)b1.read());
11.}
12.System.out.println();
13.if(b1.markSupported())
14.{
15.b1.mark(500);
16.for(inti=1;i<=10;i++)
17.{
18.System.out.print((char)b1.read());
19.}
20.System.out.println();
21.b1.reset();
22.for(inti=1;i<=10;i++)
23.{
24.System.out.print((char)b1.read());
25.}
26.}
27.else
28.System.out.println(“Markingoptionisnotavailabel”);
29.b1.close();
30.fin.close();
31.}
32.}
Output:
matrixRes
earchAnd
earchAnd
Note:
mark(32)preservesthemarkforthenext32bytesread(whichisenoughforall
entityreference).Useofmarkisrestrictedtoaccesswithinthebuffer.Thismeansthatyou
canonlyspecifyaparametertomark()thatissmallerthanthebuffersizeofthestream.
BufferedOutputStream:-
Unlikebufferedinput,bufferingoutputdoesnotprovideadditionalfunctionality.
Itisusedonlytoimproveperformance.
Herearethetwoavailableconstructors:
BufferedOutputStream(OutputStreamout)
Creates a new buffered output stream to write data to the specified underlying
outputstream.itusesabufferofsize512bytes.
BufferedOutputStream(OutputStreamout,intsize)
Creates a new buffered output stream to write data to the specified underlying
outputstreamwiththespecifiedbuffersize.
Example15.22
1.importjava.io.*;
2.classBufferedOutputStreamTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.BufferedOutputStreamf=newBufferedOutputStream(System.out,100);
7.bytebuf[]=“Thiswillnotbedisplayedwithoutflush()\n”.getBytes();
8.f.write(buf);
9.f.write(buf);
10.System.out.println(“testing…”);
11.f.write(buf);
12.//f.flush();or
13.//f.close();
14.}
15.}
Output:
testing…
Thiswillnotbedisplayedwithoutflush()
Thiswillnotbedisplayedwithoutflush()
Thiswillnotbedisplayedwithoutflush()
BufferedReader:-
The BufferedReader improves performance by buffering input. It has two
constructors:
BufferedReader(Readerin)
Createsabufferingcharacter-inputstreamthatusesadefault-sizedinputbuffer.
BufferedReader(Readerin,intsz)
Createsabufferingcharacter-inputstreamthatusesaninputbufferofthespecifiedsize.
Example15.23
1.importjava.io.*;
2.classBufferedReaderTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.FileReaderfr=newFileReader(“A.txt”);
7.BufferedReaderb1=newBufferedReader(fr);
8.for(inti=1;i<=10;i++)
9.{
10.System.out.print((char)b1.read());
11.}
12.System.out.println();
13.if(b1.markSupported())
14.{
15.b1.mark(5);
16.for(inti=1;i<=10;i++)
17.{
18.System.out.print((char)b1.read());
19.}
20.System.out.println();
21.b1.reset();
22.for(inti=1;i<=10;i++)
23.{
24.System.out.print((char)b1.read());
25.}
26.}
27.else
28.System.out.println(“Markingoptionisnotavailabel”);
29.b1.close();
30.fr.close();
31.}
32.}
Output:
matrixRes
earchAnd
earchAnd
BufferedWriter:
UsingaBufferedWriteranincreaseperformancebyreducingthenumberoftimes
dataisactuallyphysicallywrittentotheoutputstream.
Constructors:
BufferedWriter(Writerout)
Createsabufferedcharacter-outputstreamthatusesadefault-sizedoutputbuffer.
BufferedWriter(Writerout,intsz)
Createsabufferedcharacter-outputstreamthatusesanoutputbufferofthegiven
size.
Example15.24
1.importjava.io.*;
2.classBufferedWriterTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.BufferedWriterf=newBufferedWriter(newPrintWriter(System.out));
7.Strings=“Thiswillnotbedisplayedwithoutflush()\n”;
8.charbuf[]=newchar[s.length()];
9.s.getChars(0,s.length(),buf,0);
10.f.write(buf);
11.f.write(buf);
12.System.out.println(“testing…”);
13.f.write(buf);
14.//f.flush();
15.//f.close();
16.}
17.}
Output:
testing…
HandlingPrimitiveDataTypesUsingByteStreams:-
Thebasicinputandoutput streamprovideread/write methodsthatcan onlybe
usedforreading/writingbytesorcharacters.
Ifwewanttoread/writetheprimitivedatatypessuchasintegersanddouble,we
canusefilterclassesaswrappersonexistinginputandoutputstreamstofilterdatainthe
originalstream.
The two filter classes used for creating “data streams” for handling primitive
types are DataInputStream and DataOutputStream. These classes use the concept of
multipleinheritanceasshownbelowandimplementallthemethodscontainedinboththe
parentclassandtheinterface.
Adatastreamforinputfromafilecanbecreatedasfollows:
FileInputStreamfis=newFileInputStream(infile);
DataInputStreamdis=newDataInputStream(fis);
Thesestatementsbasicallywrapdisonfisanduseitasa“filter”.Similarlythefollowing
statementscreatetheoutputdatastreamdosandwrapitovertheoutputfilestreamfos.
FileOutputStreamfos=newFileOutputStream(outfile);
DataOutputStreamdos=newDataOutputStream(fos);
Example15.25
Thefollowingprogramdemonstratesthereadingandwritingofprimitivedata.
1.importjava.io.*;
2.classReadWritePrimitive
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.Fileprimitive=newFile(“prim.dat”);
7.FileOutputStreamfos=newFileOutputStream(primitive);
8.DataOutputStreamdos=newDataOutputStream(fos);
9.dos.writeInt(1999);
10.dos.writeDouble(222.44);
11.dos.writeBoolean(false);
12.dos.writeChar(‘X’);
13.dos.close();
14.fos.close();
15.FileInputStreamfis=newFileInputStream(primitive);
16.DataInputStreamdis=newDataInputStream(fis);
17.System.out.println(dis.readInt());
18.System.out.println(dis.readDouble());
19.System.out.println(dis.readBoolean());
20.System.out.println(dis.readChar());
21.dis.close();
22.fis.close();
23.}
24.}
Output:
1999
222.44
false
X
Pre-definedStreams:-
Systemclasscontainsthreepre-definedstreamvariables-in,out,anderr.Thesefieldsare
declaredaspublicand staticwithinSystemclass.Thismeansthattheycanbeusedby
anyotherpartofyourprogramandwithoutreferencetoaspecificobject.
System.out refers to the standard output stream. By default, this is the console.
System.outisanobjectoftypePrintStream.
System.in refers to standard input, which is the keyboard by default. System.in is an
objectoftypeInputStream.
System.err refers to standard error stream, which also is the console by default.
System.errisanobjectoftypePrintStream.
Thesearebytestreams,eventhoughtheytypicallyareusedtoreadandwritecharacters
fromandtotheconsole.Youcanwrapthesewithincharacter-basedstreams,ifdesired.
InputStreamReader:
An InputStreamReader is a bridge from byte streams to character streams; it
readsbytesanddecodesthemintocharacterusingaspecifiedcharset.Thecharsetthatit
usesmaybespecifiedexplicitly,ortheplatform’sdefaultcharsetmaybeaccepted.
Constructors:
InputStreamReader(InputStreamin)
CreateanInputStreamReaderthatusesthedefaultcharset.
InputStreamReader(InputStreamin,StringcharsetName)
CreateanInputStreamReaderthatusesthenamedcharset.
Example15.26
1.importjava.io.*;
2.classInputStreamReaderTest
3.{
4.publicstaticvoidmain(Stringargv[])throwsIOException
5.{
6.charc;
7.InputStreamReaderis=newInputStreamReader(System.in);
8.System.out.println(“Entercharacters,‘q’toquit”);
9.c=(char)is.read();
10.while(c!=‘q’)
11.{
12.System.out.print(c);
13.c=(char)is.read();
14.}
15.}
16.}
Output:
Entercharacters,‘q’toquit
abcd
abcd
q
Example15.27
Previousexampleismodifiedtomakeuseofbufferingtoimproveperformance.
1.importjava.io.*;
2.classBufferedReaderTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.charc;
7.BufferedReaderbr=newBufferedReader(newInputStreamReader
(System.in));
8.System.out.println(“Entercharacters,‘q’toquit”);
9.c=(char)br.read();
10.while(c!=‘q’)
11.{
12.System.out.print(c);
13.c=(char)br.read();
14.}
15.}
16.}
Output:
Entercharacters,‘q’toquit
abcd
abcd
q
Example15.28
TheInputStreamReaderdoesnotprovidereadLine()method,henceInputStreamReaderis
linkedtoBufferedReaderthatprovidesthereadLine()method.
1.importjava.io.*;
2.classBufferedReaderTest1
3.{
4.publicstaticvoidmain(Stringargv[])throwsIOException
5.{
6.BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
7.System.out.println(“Enter‘stop’toquit”);
8.Stringstr=br.readLine();
9.while(!str.equals(“stop”))
10.{
11.System.out.println(“YourName:”+str);
12.str=br.readLine();
13.}
14.}
15.}
Output:
Enter‘stop’toquit
HarryFeat
YourName:HarryFeat
stop
OutputStreamWriter:
An OutputStreamWriter is a bridge from character streams to byte streams:
characterswrittentoitareencodedintobytesusingaspecifiedcharset.Thecharsetthatit
usesmaybespecifiedexplicity,ortheplatform’sdefaultcharsetmaybeaccepted.
Constructors:
OutputStreamWriter(OutputStreamout)
CreateanOutputStreamthatusesthedefaultcharacterencoding.
OutputStreamWriter(OutputStreamout,StringcharsetName)
CreateanOutputStreamthatusesthenamedcharset.
ReadingConsoleInput:
InJava1.0theonlywaytoperformconsoleinputwastouseabytestream,and
oldercodethatusesthisapproachpersists.
Today,usingabytestreamtoreadconsoleinputisstilltechnicallypossible,but
doing so may require the use of a deprecated method, and this approach is not
recommended.
In Java, console input is accomplished by reading from System.in. To obtain a
character-based stream that is attached to console, you wrap System.in in a
InputStreamReaderobject,whichcanbefurtherwrappedinaBufferedReaderobject,to
improveperformance.
Example15.29
ThisexampledemonstratesthatwecanreaddirectlyfromSystem.in.
1.importjava.io.*;
2.classReadFromConsole
3.{
4.publicstaticvoidmain(Stringarg[])throwsIOException
5.{
6.charc;
7.System.out.println(“Entercharacters,‘q’toquit”);
8.c=(char)System.in.read();
9.while(c!=‘q’)
10.{
11.System.out.print(c);
12.c=(char)System.in.read();
13.}
14.}
15.}
Output:
Entercharacters,‘q’toquit
abcd
abcd
xyzq
xyz
The proper way of reading from console is to wrap the System.in in
InputStreamReaderandtofurtherwrapittoBufferedReadertoimproveperformanceand
to input one line at a time. The appropriate examples have already been covered in the
earliersectionrelatedtoInputStreamReaderclass.
WritingConsoleOutput:
Console output is most easily accomplished with print() and println(). These
methodsaredefinedbytheclassPrintStream(whichisthetypeoftheobjectreferenced
by System.out).Even though System.out is a byte stream, using it for simple program
outputisstillacceptable.
However, a character-based alternative is the right choice.Because PrintStream is an
output stream derived from OutputStream, it also implements the low-level method
write(). Thus, write() can be used to write to the console. The simplest form of write()
definedbyPrintStreamis:
voidwrite(intbyteval)
Thismethodwritestothestream,thebytespecifiedbybyteval.Althoughbyteval
isdeclaredasaninteger,onlythelow-ordereightbitsarewritten.
Example15.30
1.importjava.io.*;
2.classWriteTest
3.{
4.publicstaticvoidmain(Stringargv[])throwsIOException
5.{
6.intb;
7.b=‘A’;
8.System.out.write(b);
9.//System.out.flush();toflush
10.System.out.write(‘\n’);//toflush
11.}
12.}
Output:
A
Note:-
You will not often use write() to perform console output, because print() and
println()aresubstantiallyeasiertouse.
Serialization:
Serializationistheprocessofwritingthestateofanobjecttoabytestream.This
isusefulwhenyouwanttostorethestateofanobjecttoabytestream.Thisisalsouseful
whenyouwanttosavethestateofyourprogramtoapersistentstoragearea,suchasfile.
Atalatertime,youmayrestoretheseobjectsbyusingtheprocessofdeserialization.
SerializationisalsoneededtoimplementRMI.RMIallowsajavaobjectonone
machineto invokea methodofa javaobject ona differentmachine.An objectmay be
suppliedasanargumenttotheremotemethod.Thesendingmachineserializestheobject
andtranslatesit.Thereceivingmachinedeserializesit.
If you attempt to serialize an object at the top of an object graph, all of the other
referencedobjectsarerecursivelylocatedandserialized.
Similarly, during the process of deserialization, all of these objects and their
references are correctly stored. Variables that are declared as transient or static are not
savedbytheserializationfacilities.
Externalizableinterface:
TheJavafacilitiesforserializationanddeserializationhavebeendesignedsothat
muchoftheworktosaveandrestorethestateofanobjectoccursautomatically.
However,therearecasesinwhichtheprogrammermayneedtohavecontrolover
these processes. For example, it may be desirable to use compression or encryption
techniques. The externalizable interface is designed for these situations. The objects of
classimplementingExternalizableinterfacecanalsobeserializedanddeserialized.
Butthe controliswith theuser i.e.user can decidewhich partto serializeand
deserialize.TheserializationcodeiswritteninreadExternal()methodanddeserialization
codeiswritteninwriteExternal()method.
MethodsinExternalizableinterface:
voidreadExternal(ObjectInputin)
TheobjectimplementsthereadExternalmethodtorestoreitscontentsbycalling
themethodsofDataInputforprimitivetypesandreadObjectforobject,stringsandarrays.
voidwriteExternal(ObjectOutputout)
TheobjectimplementsthewriteExternalmethodtosaveitscontentsbycalling
the methods of DataOutput for its primitive values or calling writeObject method of
ObjectOutputforobjects,stringsandarrays.
ObjectOutputInterface:
TheObjectOutputinterfaceextendstheDataOutputinterfaceandsupportsobject
serialization. Beside methods defined in DataOutput interface, objectOutput interface
defineonlymethod.
VoidwriteObject(Objectobject)
Thisiscalledtoserializeanobject.AllmethodsofObjectOutputinterfacewill
throwanIOExceptiononerrorconditions.
ObjectOutputStream:
The ObjectOutputStream class extends the OutputStream class and implements the
ObjectOutputinterface.Itisresponsibleforwritingobjectstoastream.
Constructor:
ObjectOutputStream(OutputStreamout)
Creates an ObjectOutputStream that writes to the specified OutputStream. The
argumentoutistheoutputstreamtowhichserializedobjectswillbewritten.
Methodtowriteobject:
voidwriteObject(Objectobj)
Writeanobjecttotheunderlyingstorageorstream.
ObjectInputInterface:-
The ObjectInput interface extends the DataInput interface. It supports object
serialization.BesidemethodsdefinedinDataInputinterface,ObjectInputinterfacedefines
onlyonemethod:
ObjectreadObject()
Thisiscalledtodeserializeanobject.
ObjectInputStream:
The ObjectInputStream class extends the InputStream class and implement the
ObjectInputinterface.ObjectInputStreamisresponsibleforreadingobjectfromastream.
Constructor:
ObjectInputStream(InputStreamin)
Creates an ObjectInputStream that reads from the specified InputStream. The
argumentin,istheinputstreamfromwhichserializedobjectsshouldberead.
Themethodfordeserializingis:
ObjectreadObject()
ReadanobjectfromtheObjectInputStream.
Example15.31
1.importjava.io.*;
2.classSerializationTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.try
7.{
8.MyClassobject1=newMyClass(“Hello”,123,1.3e3);
9.MyClassobject2=newMyClass(“Hello1”,1,2);
10.System.out.println(object1);
11.System.out.println(object2);
12.FileOutputStreamfos=newFileOutputStream(“serial.dat”);
13.ObjectOutputStreamoos=newObjectOutputStream(fos);
14.oos.writeObject(object1);
15.oos.writeObject(object2);
16.oos.flush();
17.oos.close();
18.}
19.catch(Exceptione)
20.{
21.System.out.println(e);
22.}
23.try
24.{
25.MyClassobject3,object4;
26.FileInputStreamfis=newFileInputStream(“serial.dat”);
27.ObjectInputStreamois=newObjectInputStream(fis);
28.object3=(MyClass)ois.readObject();
29.object4=(MyClass)ois.readObject();
30.ois.close();
31.System.out.println(“Afterdeserialization”);
32.System.out.println(object3);
33.System.out.println(object4);
34.}
35.catch(Exceptione)
36.{
37.System.out.println(e);
38.}
39.}
40.}
41.classMyClassimplementsSerializable
42.{
43.Strings;
44.inti=100;
45.doubled;
46.MyClass(Strings,inti,doubled)
47.{
48.this.s=s;
49.this.i=i;
50.this.d=d;
51.}
52.publicStringtoString()
53.{
54.return“s=“+s+”;i=“+i+”;d=”+d;
55.}
56.}
Output:
s=Hello;i=123;d=1300.0
s=Hello1;i=1;d=2.0
Afterdeserialization
s=Hello;i=123;d=1300.0
s=Hello1;i=1;d=2.0
Note:wecansavemorethanoneobjectofthesametypeinafileandcanalsosaveobject
ofdifferenttypesinthesamefile.
Example15.32
Thisexampledemonstratesthatthetransientandstaticvariablesarenotpersistedduring
serialization.
1.importjava.io.*;
2.classSerializationTest2
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.try
7.{
8.MyClassobject1=newMyClass(“Hello”,123,1.3e3);
9.MyClassobject3=newMyClass(“Hello1”,1,2);
10.object3.x=200;
11.Aobject5=newA();
12.System.out.println(object1);
13.System.out.println(object3);
14.System.out.println(object5);
15.FileOutputStreamfos=newFileOutputStream(“serial.dat”);
16.ObjectOutputStreamoos=newObjectOutputStream(fos);
17.oos.writeObject(object1);
18.oos.writeObject(object3);
19.oos.writeObject(object5);
20.object3.x=400;
21.oos.flush();
22.oos.close();
23.}
24.catch(Exceptione)
25.{
26.System.out.println(e);
27.}
28.try
29.{
30.MyClassobject2,object4;
31.Aobject6;
32.FileInputStreamfis=newFileInputStream(“serial.dat”);
33.ObjectInputStreamois=newObjectInputStream(fis);
34.object2=(MyClass)ois.readObject();
35.object4=(MyClass)ois.readObject();
36.object6=(A)ois.readObject();
37.ois.close();
38.fis.close();
39.System.out.println(“Afterdeserialization”);
40.System.out.println(object2);
41.System.out.println(object4);
42.System.out.println(object6);
43.}
44.catch(Exceptione)
45.{
46.System.out.println(e);
47.}
48.}
49.}
50.classMyClassimplementsSerializable
51.{
52.Strings;
53.transientprivateinti=100;
54.publicstaticintx=10;
55.doubled;
56.MyClass(Strings,inti,doubled)
57.{
58.this.s=s;
59.this.i=i;
60.this.d=d;
61.x=100;
62.}
63.publicStringtoString()
64.{
65.return“s=”+s+“;i=“+i+”;d=”+d+”;x=“+x;
66.}
67.}
68.classAimplementsSerializable
69.{
70.publicStringtoString()
71.{
72.return“ClassA”;
73.}
74.}
Example15.33
UsingExternalizable
1.importjava.io.*;
2.classSerializationTest1
3.{
4.publicstaticvoidmain(Stringargs[])throwsIOException
5.{
6.try
7.{
8.MyClassobject1=newMyClass(“Hello”,99,123.45);
9.System.out.println(object1);
10.FileOutputStreamfos=newFileOutputStream(“serial.dat”);
11.ObjectOutputStreamoos=newObjectOutputStream(fos);
12.System.out.println(“beforewritingobject”);
13.oos.writeObject(object1);
14.System.out.println(“afterwritingobject”);
15.oos.flush();
16.oos.close();
17.}
18.catch(Exceptione)
19.{
20.System.out.println(e);
21.}
22.try
23.{
24.MyClassobject2;
25.FileInputStreamfis=newFileInputStream(“serial.dat”);
26.ObjectInputStreamois=newObjectInputStream(fis);
27.System.out.println(“beforereadingobject”);
28.object2=(MyClass)ois.readObject();
29.System.out.println(“afterreadingobject”);
30.ois.close();
31.System.out.println(object2);
32.}
33.catch(Exceptione)
34.{
35.System.out.println(e);
36.}
37.}
38.}
39.classMyClassimplementsSerializable
40.{
41.Strings;
42.inti=100;
43.doubled;
44.publicMyClass(){};//Itismust
45.publicMyClass(Strings,inti,doubled)
46.{
47.this.s=s;
48.this.i=i;
49.this.d=d;
50.}
51.publicStringtoString()
52.{
53.return“s=“+s+”;i=“+i+”;d=”+d;
54.}
55.publicvoidwriteExternal(ObjectOutputoos)throwsIOException
56.{
57.System.out.println(“InsidewriteExternal”);
58.oos.writeObject(s);
59.oos.writeInt(i);
60.oos.writeDouble(d);
61.}
62.publicvoidreadExternal(ObjectInputois)throwsClassNotFoundException,
IOException
63.{
64.System.out.println(“InsidereadExternal”);
65.s=(String)ois.readObject();
66.i=ois.readInt();
67.}
68.}
Output:
s=Hello;i=99;d=123.45
beforewritingobject
afterwritingobject
beforereadingobject
afterreadingobject
s=Hello;i=99;d=123.45
Note:
During deserialization, object will be constructed using default constructor
(unlike serializable interface) and then the initialization will take place. Testoring state
shouldbedoneinreadExternal().Similarlyduringserializationonlyclassidentificationis
saved.AnystatemustbesavedexplicitlyinwriteExternal().
CHAPTER
∞16∞
(Applet)
Introduction-
AnappletisanapplicationdesignedtotravelovertheInternetandtobeexecutedon
theclientmachinebyaJavaCompatiblewebbrowserlikeInternetExplorerorNetscape
Navigator.AppletsarealsoJavaprogramsbuttheyreside(stored)ontheservers.
An applet cannot be executed like standalone application. Applet can be executed
onlybyembeddingitintoanHTMLpagelikeanimageorsoundfile.Torunanappletwe
needtoaccessanHTMLpagewhichhasappletembeddedintoit.Whenthewebbrowser
downloadssuchanHTMLpage,itsubsequentlyloadstheexecutablefile,whichcontains
appletcodeandthenexecutesitonthelocalmachine.
Afteranappletarrivesontheclient,ithaslimitedaccesstoresources,sothatitcan
produce an arbitrary multi-media user interface and run complex computations without
introducingtheriskofvirusesorbreaching(breaking)dataintegrity.
AppletArchitecture:
AppletsaredifferentfromnormalJavaprograms.
AppletsareGUIbased(window-based)programs
Appletsareevent-driven
When a normal Java program (which is not GUI based) needs input it prompts the
userandthencallssomeinputmethod,suchasreadLine()i.e.theinteractionisinitiated
bytheprogram.
This is not the way in which GUI-based programs behave. The user initiates
interactionwiththeprogramratherthanprograminitiatingtheaction.
For example, in a word processing software, user initiates action by clicking on
differentbuttons,whichgeneratesaneventandsomepieceofcodeisexecutedasaresult
andaccordinglysomeactiontakesplace.
Applets use awt package (Abstract Windows Toolkit) for providing GUI and for
event-handling.Theawtiscalledsobecauseittotallydependsonthefunctionalityofthe
underlyingoperatingsystem.
Anappletresemblesasetofinterruptserviceroutines.Anappletwaitsuntilanevent
occurs. The awt notifies the applet about an event by calling an event handler that has
beenprovidedbytheapplet.
Once this happens, the applet must take appropriate action and then quickly return
controltotheAWT.
This is a crucial point. For the most part, our applet should not enter a “mode” of
operationin whichit maintainscontrol foran extendedperiod. Instead,it mustperform
specificactionsinresponsetoeventsandthenreturncontroltotheAWTruntimesystem.
Inthosesituationsinwhichourappletneedstoperformarepetitivetaskonitsown
(for example, displaying a scrolling message across its window), we must start an
additionalthreadofexecution.
WritinganApplet:
All applets are sub classes of Applet class. The Applet class is contained in the
packagejava.applet.ThehierarchyoftheAppletclassisasfollows:
java.lang.Object
|
java.awt.Component
|
java.awt.Container
|
java.awt.Panel
|
java.applet.Applet
Theappletclassprovidesallnecessarysupportforappletexecution,suchasstarting
andstopping.
It also provides methods that load and display images. It also provides necessary
supportforallthewindow-basedactivities.
Oursubclassextendingtheappletclassmustalwaysbedeclaredaspublicasitis
instantiated(creatingobject)andexecutedbythewebbrowser.
Thebrowsermakesuseofnoargumentconstructorwheninstantiatingtheappletsoit
ismusttoprovideno-argumentpublicconstructorwiththepublicvisibility.
Itisrecommendedthatwe donotprovideconstructorintheAppletclassasinthat
casecompilerwillprovidethedefaultnoargumentconstructor.
Wecanmakeuseoftheinit()methodforinitialization.Whilewritingappletcodewe
normally override some of the methods of the Applet class, which are invoked
automaticallyduringappletexecution.
It is very common to override the paint() method. The code in the paint() method
mainlydisplaystheoutputintheAppletwindow.
Example16.1(App1.java)Thefollowingprogramillustratesasimpleapplet,whichjust
displays“HelloWorld”insideawindow.Whateverwedraw/displayintheapplet’spaint
method,itappearsintheapplet’swindow.
Inthefollowingexample,thebackgroundcoloroftheappletwindowissettoredandthe
foregroundcoloris settogreen sothebackground wouldappearas redandtext “Hello
Word”wouldbedisplayedingreencolor.
1.importjava.awt.*;
2.importjava.applet.Applet;
3./*<appletcode=“App1”width=500height=100></applet>*/
4.publicclassApp1extendsApplet
5.{
6.publicvoidinit()
7.{
8.setBackground(Color.red);
9.setForeground(Color.green);
10.}
11.publicvoidpaint(Graphicsg)
12.{
13g.drawString(“HelloWorld”,20,20);
14.}
15.}
Output:
ExecutinganApplet:
Applets are not executed by the console-based Java run-time interpreter. There are
twowaysinwhichwecanrunanapplet.
1.ExecutingtheappletwithinaJavacompatiblewebbrowser.
2.Usinganappletviewer,suchasthestandardSDKtool,appletviewer.An
appletviewerexecutesourappletin awindow.This isfastestandeasiestway to
testourapplet.
ExecutingAppletinawebbrowser:
WeneedtowriteashortHTMLtextfilethatcontainstheappropriateAPPLETtag.
Theapplettagmustincludeatleastfollowingthreeattributes:
Code
Width
Height
The attribute code’s value specifies the name of the class containing applet’s code.
The attribute width and height specify the width and height of the applet’s windows
respectively.
HeretheHTMLfileRunApp.Htmlwithapplet“App1”embeddedintoit.
<html>
<head>
<title>SimpleApplet</title>
</head>
<body>
<h1>Simple“HelloWorld”Application</h1>
<appletcode=“App1”width=500height=100>
</applet>
</body>
</html>
YoucanexecutetheappletbyopeningfileRunApp.html inweb browser.Thefile
canbeonlocalfilesystemorcanalsobeloadedfromawebserver.
ExecutingAppletusingappletviewer:
However, a more convenient method exists that we can use to speed up testing.
SimplyincludeacommentinyourjavasourcecodefilethatcontainsthatAPPLETtag.
Bydoingso,ourcodeisdocumentedwithaprototypeofthenecessaryHTMLstatements,
andwecantestyourcompiledoutputmerelybystartingtheappletviewerwithourJava
sourcecodefile.ifweusethismethod,thenaftercompilingwecanexecutetheappletas
follows:
appletviewerSimpleApplet.Java
AppletLifecycleMethods:
Applet overrides a set of methods that provides the basic mechanism by which the
browserorappletviewerinterfacestotheappletandcontrolsitsexecution.
Thesemethodsarealsocalledlifecyclemethodsbecausethebrowserorappletviewer
calls them automatically during different stages of applet lifecycle. In all there are five
lifecyclemethods:
publicvoidinit()
publicvoidstart()
publicvoidstop()
publicvoiddestroy()
publicvoidpaint(Graphicsg)
Four of these methods: init(), start(), stop(), and destroy() are defined in the applet
class.
Thepaint(),isdefined bytheawtComponentclass, defaultimplementationsforall
thesemethodsare provided.Appletsdo notneedto overridethosemethods theydonot
use.However,verysimpleappletswillnotneedtodefinethem.
AppletInitializationandTermination:
Whenanappletbegins,thefollowingmethodsarecalledinsequence
1. init()
2. start()
3. paint()
Whenanappletisterminated,thefollowingsequenceofmethodcallstakesplace:
4. stop()
5. destroy()
Theinit()Method:
Thisisthefirstmethodtobecalled.Thisiswhereweshouldinitializevariables
andwritecodeforotherinitializationactivities.Thismethodiscalledonlyonceduringthe
lifecycleofourappletimmediatelyafterinstantiation.
Thestart()Method:
Thestart()methodiscalledafterinit().Itisalsocalledtorestartanappletafterit
hasbeenstopped.Whereinit()iscalledoncethefirsttimeanappletisloaded,start()is
calledeachtimeanapplet’sHTMLdocumentisdisplayedonscreen.So,ifauserleavesa
webpageandcomesback,theappletresumesexecutionatstart().
Thepaint()Method:
The paint( ) is called after the init() and start() method when the applet begins
execution. The paint() method is also called each time our applet’s output must be
redrawn.Thissituationcanoccurforseveralreasons.Forexample,thewindowinwhich
theappletisrunningmaybeoverwrittenbyanotherwindowandthenuncovered.orthe
appletwindowmaybeminimizedandthenrestored.
TheStop()Method:
The stop() method is called when a web browser leaves the HTML document
containingtheappletwhenitgoestoanotherpage,forexample.Whenstop()iscalled,the
appletisprobablerunning.
Weshouldusestop()tosuspendthreadsthatdonotneedtorunwhentheappletisnot
visible.Wecanrestartthemwhenstart()iscallediftheuserreturnstothepage.Wecan
alsofreeanycostlyresourceandacquireitagaininthestart()method.
Thedestroy()Method:
The destroy () method is called when the environment determines that our applet
needs to be removed completely from memory. At this point, we should free up any
resourcestheappletmaybeusing.Thestop()methodisalwayscalledbeforedestroy().
Example 16.2 A simple applet that sets the background color to cyan, the foreground
colorto red,and displaysamessagethatillustrates theorder inwhichtheinit(),start(),
andpaint()methodsarecalledwhenanappletstartsup.
1.importjava.awt.*;
2.importjava.applet.*;
3./*<appletcode=“App2”width=500height=100></applet>*/
4.publicclassApp2extendsApplet
5.{
6.Stringmsg=””;
7.publicvoidinit()
8.{
9.System.out.println(“Insideinit”);
10.setBackground(Color.cyan);
11.setForeground(Color.red);
12.msg=“Insideinit()—”;
13.}
14.publicvoidstart()
15.{
16.System.out.println(“Insidestart”);
17.msg+=“Insidestart()—”;
18.}
19.publicvoidstop()
20.{
21.System.out.println(“InsideStop”);
22.msg+=“Insidestop()—”;
23.}
24.publicvoidpaint(Graphicsg)
25.{
26.System.out.println(“Insidepaint”);
27.msg+=“Insidepaint()—”;
28.g.drawString(msg,10,30);
29.}
30.publicvoiddestroy()
31.{
32.System.out.println(“Insidedestroy”);
33.}
34.}
Output:
DynamicApplet:
TheoutputdisplayedintheApplet’swindowcanbemadedynamic.Forexample,we
candisplayamovingbanner.Theappletcanalsobeusedinapplicationslikedisplaying
scoreandotherstatisticsrelatedtoaCricketmatchbyretrievingfromserver;displaying
stockpricesetc.
Example16.3
The following example displays a moving banner. It demonstrates use of
repaint()methodtorefreshthe display.Thisappletscrollsamessage,fromrightto left,
acrosstheapplet’swindow.
Since the scrolling of the message is a repetitive task, it is performed by a
separatethread,createdbytheappletwhenitisinitiated.Thisprogramalsodemonstrates
thattheresourcescanbefreedinthestop()methodandcanbereacquiredinthestart()
method.
1.importjava.awt.*;
2.importjava.applet.*;
3./*<appletcode=“App3”width=500height=100></applet>*/
4.publicclassApp3extendsAppletimplementsRunnable
5.{
6.Stringmsg=“ASimpleMovingBanner.”;
7.Threadt=null;
8.booleanstopFlag;
9.publicvoidinit()
10.{
11.setBackground(Color.cyan);
12.setForeground(Color.red);
13.}
14.publicvoidstart()
15.{
16.t=newThread(this);
17.stopFlag=false;
18.t.start();
19.}
20.publicvoidstop()
21.{
22.stopFlag=true;
23.t=null;
24.}
25.publicvoidpaint(Graphicsg)
26.{
27.g.drawString(msg,50,30);
28.}
29.publicvoidrun()
30.{
31.for(;;)
32.{
33.repaint();
34.try
35.{
36.Thread.sleep(250);
37.}
38.catch(InterruptedExceptione)
39.{
40.System.out.println(e);
41.}
42.msg=msg.substring(1)+msg.charAt(0);
43.if(stopFlag)
44.break;
45.}
46.}
47.}
Output:
Usingthestatuswindow:
In addition to displaying information in its window, an applet can also output a
messagetothestatuswindowsofthebrowserorappletvieweronwhichitisrunning.
TodosocallshowStatus()withthestringthatwewanttodisplay.Thestatuswindow
isa goodplacetogivethe userfeedback aboutwhatisoccurringin theapplet, suggest
options,orpossiblereportsometypesoferrors.
Thestatuswindowalsomakesanexcellentdebuggingaid(help),becauseitgivesus
aneasywaytooutputinformationaboutourapplet.
Example16.4:Thefollowingexampledemonstratehowtouseofthestatuswindow.
1.importjava.awt.*;
2.importjava.applet.*;
3./*<appletcode=“App4”width=500height=100></applet>*/
4.publicclassApp4extendsApplet
5.{
6.publicvoidinit()
7.{
8.setBackground(Color.cyan);
9.}
10.publicvoidpaint(Graphicsg)
11.{
12.g.drawString(“Thisisintheappletwindow”,10,20);
13.showStatus(“Thisisshowninthestatuswindow”);
14.}
15.}
Output:
TheHTML’sAPPLETTAG:
TheAPPLETtagisusedtostartanappletfrombothanHTMLdocumentandfroman
appletviewer.
An appletviewer will execute each APPLET tag that it finds in a separate window;
whilewebbrowserslikeNetscapeNavigator,andInternetExplorerallowmanyappletson
asinglepage.
ThesyntaxforthestandardAPPLETtagis:
<APPLET
CODE=appletclassname
CODEBASE=codebaseURL
ALT=alternateText,
NAME=appletInstancename
WIDTH=pixels
HEIGHT=pixels
ALIGN=alignment
VSPACE=verticalspaceinpixels
HSPACE=horizontalspaceinpixels
>
<PARAMNAME=attributeName-1VALUE=AttributeValue-1>
<PARAMNAME=attributeName-2VALUE=AttributeValue-2>
––––-
<PARAMNAME=attributeName-NVALUE=AttributeValue-N>
………HTMLdisplayedintheabsenceofJava………
</APPLET>
CODE:
CODEisarequiredattributethatgivesthenameofthefilecontainingourapplet’s
compiledclassfile.ThisfileisrelativetotheCODEBASEURLoftheapplet,which
isthedirectorythatthehtmlfilewasinordirectoryindicatedbyCODEBASEifset.
CODEBASE:
CODEBASE is an optional attribute that specifies the base URL of the applet
code,whichisthedirectorythatwillbesearchedfortheapplet’sexecutableclassfile
(specifiedbytheCODEtag).
TheHTMLdocument’sURLdirectoryisusedastheCODEBASEifthisattributeis
not specified. The CODEBASE does not have to be on the host from which the
HTMLdocumentwasread.
ALT:TheALTtagisanoptionalattributeusedtospecifyashorttextmessagethat
shouldbedisplayedifthebrowserunderstandstheAPPLETtagbutcannotcurrently
run Java applet. This is distinct from the alternate HTML we provide for browsers
thatdonotsupportapplets.
NAME: NAME is an optional attribute used to specify a name for the applet
instance.Appletsmustbenamedinorderforotherappletsonthesamepagetofind
them by name and communicate with them. To obtain an applet by name, use
getApplet(),whichisdefinedbytheAppletContextinterface.
WIDTHandHEIGHT:Sizeofapplet’sdisplayareainpixels.
ALIGH:ALIGNisanoptionalattributesthatspecifiesthealignmentoftheapplet.
This attribute is treated the same way as the HTML’S IMG tag with following
possiblevalues:
LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP,
ABSMIDDLE,ANDABSBOTTOM.
VSPACEandHSPACE:TheseattributesareoptionalVSPACEspecifiesthespace,
inpixels,aboveandbelowtheapplet.HSPACEspecifiesthespace,inpixelsoneach
side of the applet. They are treated the same as IMG tag’s VSPACE and HSPACE
attributes.
ThePARAMTag
The PARAM tag allows we to specify applet specific arguments in an HTML
page.Applets access theirattributes withthe getparameter() method.PARAM tag
hastwoattributes:NAMEandVALUE.
Example 16.5 This example demonstrates how to pass parameters to Applet from the
HTMLpage.
1.importjava.awt.*;
2.importjava.applet.*;
3./*<appletcode=“App5”width=500height=100>
5.<paramname=“fontName”value=“Arial”>
6.<paramname=“fontSize”value=“30”>
7.</applet>*/
8.publicclassApp5extendsApplet
9.{
10.StringfName;
11.intfSize;
12.publicvoidinit()
13.{
14.fName=getParameter(“fontName”);
15.if(fName==null)
16.fName=“Courier”;
17.fSize=Integer.parseInt(getParameter(“fontSize”));
18.Fontf1=newFont(fName,Font.PLAIN,fSize);
19.setFont(f1);
20.}
21.publicvoidpaint(Graphicsg)
22.{
23.g.drawString(“FontName:”+fName,0,25);
24.g.drawString(“FontSize:”+fSize,0,50);
25.g.drawString(“Helloworld”,0,75);
26.}
27.}
Output:
GettingDocumentBaseandCodeBase:
Often,wewillcreateappletsthatwillneedtoexplicitlyloadmediaandtext.Java
willallowtheapplettoloaddatafromthedirectoryholdingtheHTMLfilethatstartedthe
applet (the docoument base) and the directory from which the applet’s class file was
loaded(thecodebase).
ThesedirectoriesarereturnedasURLobjects.Theycanbeconcatenatedwitha
stringthat name thefile wewantto load.To actually loadanother file,wewill usethe
showdocument()methoddefinedbytheAppletcontextinterface.
Example 16.6 The following example demonstrates how we can obtain the document
baseandcodebaseintheappletcode.
App6.java
1.importjava.awt.*;
2.importjava.applet.*;
3.importjava.net.URL;
4.publicclassApp6extendsApplet
5.{
6.publicvoidpaint(Graphicsg)
7.{
8.URLu1=getCodeBase();
9.g.drawString(“Codebase:-”+u1,10,20);
10.URLu2=getDocumentBase();
11.g.drawString(“Documentbase:-“+u2,10,40);
12.}
13.}
App6.html
1.<html>
2.<body>
3.<appletcode=“App6”width=500height=200></applet>
4.</body>
5.</html>
Output:
AppletContextandShowDocument():
One application of Java is to use active image and animation to provide a
graphicalmeans of navigatingthe web thatis more interestingthan the underlinedblue
wordsusedbyhypertext.ToallowsourapplettotransfercontroltoanotherURL,wemust
usetheshowDcoument()methoddefinedbytheAppletContextinterface.
TheAppletContextisaninterfacethatletsusgetinformationfromtheapplet’s
executionenvironment.Thecontextofthecurrentlyexecutingappletisobtainedbyacall
tothegetAppletContext()methoddefinedbytheappletclass.
Within an applet, once we have obtained the applet’s context, we can bring
another document into view by calling showDocument() method. This method has no
return value and returns no exception if it fails so use it carefully. There are two
showDocument()methods.
voidShowDocument(URLurl)
ReplacestheWebpagecurrentlybeingviewedwiththegivenURL
voidShowDocument(URLurl,Stringwhere)
Displays the specified document at the specified loacation within the browser window.
Validargumentsfor“where’are:
“_self”(showinthecurrentframe)
“_parent”(showintheparentframe)
“_top”(showintopmostframe),and
“_blank”(showinnewbrowserwindow)
Example16.7
The following applet demonstrates use of Applet Context and showDocument(). Upon
execution,itobtainsthecurrentappletcontextandusesthatcontexttotransfercontroltoa
file called A.html. This file must be in the same directory as the applet. Test.html can
containanyvalidhypertextthatyourlike.
1.importjava.awt.*;
2.importjava.applet.*;
3.importjava.net.*;
4.publicclassApp7extendsApplet
5.{
6.AppletContextac;
7.URLu1;
8.publicvoidinit()
9.{
10.setBackground(Color.cyan);
11.}
12.publicvoidstart()
13.{
14.ac=getAppletContext();
15.u1=getCodeBase();
16.try
17.{
18.Thread.sleep(3000);
19.ac.showDocument(newURL(u1+“A.html”),“_blank”);
20.}
21.catch(MalformedURLExceptione)
22.{
23.showStatus(“InvalidURL”);
24.e.printStackTrace();
25.}
26.catch(InterruptedExceptione)
27.{
28.showStatus(“InvalidURL”);
29.e.printStackTrace();
30.}
31.}
32.publicvoidpaint(Graphicsg)
33.{
34.g.drawString(u1+“A.html”,20,20);
35.try
36.{
37.Thread.sleep(3000);
38.}
39.catch(InterruptedExceptione)
40.{
41.System.out.println(e);
42.}
43.}
44.}
App7.html
1.<html>
2.<head>
3.<Title>AppletContextDemo</Title>
4.</head>
5.<body>
6.<appletcode=“App7”width=200height=200></applet>
7.</body>
8.</html>
A.html
1.<html>
2.<head>
3.<title>NewPage</title>
4.</head>
5.<bodybgcolor=bluetext=red>
6.<h1>matrix</h1>
7.</body>
8.</html>
Example16.8
1.importjava.applet.*;
2.importjava.awt.*;
3.importjava.awt.event.*;
4./*<Appletcode=“CopyApp”width=500height=200></applet>*/
5.publicclassCopyAppextendsAppletimplementsActionListener
6.{
7.TextFieldtf1,tf2;
8.Buttonb1;
9.publicvoidinit()
10.{
11.setForeground(Color.red);
12.Fontf1=newFont(“Arial”,
13.Font.BOLD+Font.ITALIC,20);
14.tf1=newTextField(8);
15.tf2=newTextField(8);
16.tf1.setFont(f1);
17.tf2.setFont(f1);
18.b1=newButton(“Copy”);
19.b1.addActionListener(this);
20.b1.setFont(f1);
21.add(tf1);
22.add(tf2);
23.add(b1);
24.}
25.publicvoidpaint(Graphicsg)
26.{
27.g.drawString(“Matrix”,0,150);
28.}
29.publicvoidactionPerformed(ActionEventae)
30.{
31.Strings1=tf1.getText();
32.tf2.setText(s1);
33.}
34.}
Output:
Example16.9Sumof2numbersusingApplet
1.importjava.applet.*;
2.importjava.awt.*;
3.importjava.awt.event.*;
4./*<appletcode=“SumApplet”width=400height=400></applet>*/
5.publicclassSumAppletextendsAppletimplementsActionListener
6.{
7.TextFieldtf1,tf2,tf3;
8.Labell1,l2,l3;
9.Buttonb1;
10.publicvoidinit()
11.{
12.setLayout(newGridLayout(4,2));
13.l1=newLabel(“No.1”);
14.l2=newLabel(“No.2”);
15.l3=newLabel(“Result”);
16.tf1=newTextField(8);
17.tf2=newTextField(8);
18.tf3=newTextField(8);
19.b1=newButton(“Sum”);
20.b1.addActionListener(this);
21.add(l1);add(tf1);
22.add(l2);add(tf2);
23.add(l3);add(tf3);
24.add(b1);
25.}
26.publicvoidactionPerformed(ActionEventae)
27.{
28.Buttonabc=(Button)ae.getSource();
29.if(abc==b1)
30.{
31.inta,b,c;
32.a=Integer.parseInt(tf1.getText());
33.b=Integer.parseInt(tf2.getText());
34.c=a+b;
35.tf3.setText(String.valueOf(c));
36.}
37.}
38.}
CHAPTER
∞17∞
(AbstractWindowsToolkit-AWT)
Introduction-
Java provides a large number of built-in classes, which help us in designing
graphicaluserinterface(GUI).Mostoftheseclassesbelongtothepackagejava.awtand
arecollectivelyknownasAbstractWindowsToolkit(AWT).
We are familiar with software like MS-WORD, MS-EXCEL etc. All of these
softwarehaveaGUIi.e.whenwerunthesesoftware,weseegraphicaluserinterface.
Weaccessvariousfeaturesofthissoftwarebyselectingdifferentoptionsthrough
keyboardormouse.Lotofprogrammingisneededtodisplaytheuserinterface.
ThreeimportantpartsofAWT,whichhelpindesigninggraphicaluserinterfaces,are
Components
Containers
LayoutManagers
AlloftheaboveplayanimportantroleindesigningtheGUI.
Components:
Components are Java’s building blocks for creating GUI’s. A component is an
object having graphical representation that can be displayed on the screen and that can
interactwiththeuser.Examplesofcomponentsarethebuttons,checkboxesandscrollbars
ofatypicalgraphicaluserinterface.Thejava.awt.Componentclassis theabstractsuper
classofthenon-menurelatedAWTcomponents.Classcomponentcanalsobeextended
directly to create lightweight component. A lightweight is a component that is not
associatedwithanativeopaquewindow.
Somecomponentstypes,suchasbuttonsandscrollbars,areuseddirectlyforGUI
control.Otherkindsofcomponents(thosethatinheritfromtheContainerclass)provide
specialorganization.WhilethecomponentslikeTextField,TextArea,Listetc,areusedto
acceptinputfromtheuser.Thelabelisadifferenttypeofcomponentwhosepurposeisto
simplydisplaytheappropriatelabeltoidentifyothercomponents.
Java’s components are implemented by the many subclasses of the java.awt.Component
andjava.awt.Menucomponentsuperclasses.
One way to organize this fairly large number of classes is to divide them into
categories:
Visualcomponents
Containercomponents
Menucomponents
Componenthierarchy:ThefollowingdiagramshowsAWTthecomponenthierarchy.
Containers:
Thefollowingdiagramdescribesthecontainerhierarchy
Allthewindow–basedapplicationsstartwithatop-levelwindowvisibleonthe
screen.
Similarly all GUI based java applications also start with a top-level window,
whichisreferredtoastop-levelcontainerinjava’sterminology.
Containers are also java components that can contain other components. A
component can be made visible only by adding it to a container or putting it inside a
container.
AlljavaGUI’sresideeitherinanappletorinaFrame.Theappletsandframes
arethetwotop-levelcontainersinjava.
Theappletisthetop-levelcontainerforappletssothecomponentsmustbeadded
toit.Similarlytheframeisthetop-levelcomponentforthestandaloneapplications.
FormorecomplicatedGUI’sitisconvenienttodividetheappletsorframeinto
smallerregions.Theseregionsmightconstitute,forexample,atoolbaroramatrixofradio
buttons. In java, GUI sub-regions are implemented most commonly with the panel
container.
Panels, just like applets and frames can contain other components such as
buttons, canvas, checkboxes, scrollbars, scrollpanes, text areas, textfields, and other
panels.
ComplicatedGUI’ssometimeshaveverycomplicatedcontainmenthierarchiesof
panelswithinpanelswithinpanels.Andsoon,downthroughmanylayersofcontainment.
As containers are also components so the methods available for components are also
availableforcontainersduetoinheritance.
Themostcommonlyusedmethodforthecontainersisadd()methodusingwhich
thecomponentsareaddedthecontaineritsgeneralformis.
voidadd(Componentcomp);
Allthecomponentsarethesub-classesofthecomponentclasssoanycomponentcanbe
addedtothecontainerusingtheadd()method.
LayoutManager:
While adding components to a containers, one important issue is related to the
position and size of the component. The components position can be specified in two
ways.
(i)Absolutepositioning.
(ii)Relativepositioning.
Inabsolutepositioning,wespecifytheexactlocationatwhichthecomponentshould
beadded.Thismethodgivesusfinecontrolandmaybethebestchoiceifwedesignthe
GUIforjustoneplatform.
For example, a component can be added in middle of container along horizontal
direction,byspecifyingtheco-ordinatesoftop-leftcornerofthecomponent.
Wecancalculatetheseco-ordinatesbasedonthecontainerwidthandthecomponent
width.Butthecomponentwillnotbeleftinthemiddle.Ifthecontainerwidthchangesor
thesizeofthecomponentchanges.
Theother approach,relative positioning,may notallowus tospecify theexact
locationof thecomponentsbut maybe suitablein thesituationwhere wewant thatthe
componentshouldalwaysbeinthemiddleofthecontaineralongthehorizontaldirection.
Wecanachievethisbyspecifyingtherelativepositionofthecomponentlikeleft,
right, center etc. it is very common to center headings in documents using word
processors.Theheadingsremaincenteredevenifthewidthofthepagechangesthisisan
exampleorrelativepositioning.
Injavaitispossibletouseabsolutepositioningbutitisnotadvisable.TheAWT
is designed to use relative positioning. We can specify component layouts with relative
specifications, such as the component will be added to the right of the previous
component, the component will be added below some other component, the component
will appear at top, size of the component will be ¼th of the container width etc. such
specificationsareusefulevenwithoutknowledgeofcomponentsizes.
Javaencourages relativepositioningbecause itis platformindependent andthe
sameGUIshouldworkonawidevarietyofplatformswithoutmodifications.
Built-injavaclassescalledlayoutmanagershandlethetaskofmappingrelativepositions
toactual/physicalpositions.Javasupportsmanytypesoflayoutmanagers,wewilldiscuss
aboutfollowinglayoutmangers.
1. FlowLayout
2. GridLayout
3. BorderLayout
4. CardLayout
5. GridBagLayout
TwoObservationswhenworkingwithlayoutmanagers:
Wedonothavetobeartheburdenofspecifyingtheexactpositionand
dimensionofeachcomponent.
We no longer had the power to specify the exact position and
dimensionsofeachcomponent.
WhyJavauseslayoutmanagers?
Therearetworeasons:
1. The theory lies in the position that precise layout (thatis, specification in pixels of
each component’s size and position) is a repetitious and often performed task;
therefore,accordingtoOOP’slayoutfunctionalityoughttobeencapsulatedintoone
ormoreclassestoautomatethetask.
Certainly the layout managers eliminate a lot of development tedious. Many
programmersdisliketheideaoflayoutmanagersfirst,butcometoappreciatethem
moreandmoreastediouschoicesareeliminated.
2. The practical reason for having layout manager stems from java’s platform
independence. In java, AWT components borrow their behaviour from the window
systemoftheunderlyinghardwareonwhichtheJVMisrunning.
ThusonaMacintosh,anAWTbuttonstoolslikeanyotherMacbutton;onamotif
platform,ajavabuttonlookslikeanyothermotifbutton,andsoon.Theproblemhere
is that buttons and other components have different sizes when instantiated on
differentplatforms.
If java encouraged precise pixel-level sizing and positioning, there wouldbe lot of
java GUI’s that looked exquisite on their platform of origin and terrible or even
unusable,onotherplatforms.
Asdiscussedabove,layoutmanagerssolvetheproblembyusingrelativepositioning.
Layoutpolicy:
Everyjava component has preferredsize. The preferredsize expresses how bigthe
component would like to be, barring conflict with a layout manager. Preferred size is
generally the smallest size necessary to render the component in a visually meaningful
wayforexample,abutton’spreferredsizeisthesizeofitslabeltext,plusalittleborderof
emptyspacearoundthetext,plustheshadoweddecorationsthatmarktheboundaryofthe
button thus a buttons preferred size is “just big enough”. Preferred size is platform
dependentsincecomponentboundarydecorationsvaryfromsystemtosystem.
Whenalayoutmanagerlaysoutitscontainer’schildcomponents,ithastobalance
twoconsiderations;
(i)layoutpolicyand
(ii)eachcomponent’spreferredsize
Firstprioritygoestoenforcinglayoutpolicy.Ifhonoringacomponent’spreferred
size would mean violating the layout policy, then the layout manager overrules the
component’spreferredsize.Understandingalayoutmanagermeansunderstandingwhere
itwillplaceacomponentandalsohowitwilltreatacomponent’spreferredsize.
1.FlowLayout:
The functionality of the flow layout manager is encapsulated in the class
java.awt.FlowLayout.
The Flow Layout Managers arranges components in horizontal rows. It is the
defaultlayoutmanagertypeforpanelsandapplets.
Theflowlayoutmanagerfitsasmanycomponentsaspossibleintothetoprow
andmovestheothercomponentintosecondrow.Ifnospaceisleftinthesecondrow,the
componentwillmovetothethirdrow,andsoon.Thisisquitesimilartotypingtextina
document.
Whenwereachattheendofthecurrentline,thenextwordmovestothe next
line,andsoon.Ifwechangethewidthorheightofthedocument,theentiredocumentis
re-formatted.
The components always appear, left to right, in the order in which they were
addedtotheircontainer.
Bydefault,theflowlayoutmanagerleavesagapoffivepixelsbetweencomponents
inboththe horizontalandvertical directions.Thisdefaultcanbechanged bycallingan
overloadedversionofthe FlowLayoutconstructor,andpassinginthedesiredhorizontal
andverticalgaps.
Withineveryrow,thecomponentsareevenlyspaced,andtheclusterofcomponentsis
centered. The alignment (sometimes called “justification”) of the clustering can be
controlledbypassingaparametertotheFlowLayoutconstructor.Thepossiblevaluesare
:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
Example17.1:
1.importjava.awt.*;
2.classMyFrame1
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newFrame();
7.FlowLayoutflow=newFlowLayout();
8.f.setLayout(flow);
9.Labell1=newLabel(“Name:“);
10.f.add(l1);
11.TextFieldtf1=newTextField(“Matrix”);
12.f.add(tf1);
13.tf1.setBackground(Color.green);
14.tf1.setForeground(Color.red);
15.Buttonb1=newButton(“ok”);
16.Fontf1=newFont(“Arial”,Font.BOLD,24);
17.b1.setFont(f1);
18.f.add(b1);
19.f.setSize(500,100);
20.f.setVisible(true);
21.}
22.}
Note:-If we reduce the size of the above window and three components do not fit in a
singlerowthencomponentsaremovedinthenextrowstartingfromlastcomponent.
Output:
Example17.2
1.importjava.awt.*;
2.publicclassMyFrame2extendsFrame
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.MyFrame2f=newMyFrame2();
7.f.setLayout(newFlowLayout(FlowLayout.CENTER));
8.System.out.println(f.paramString());
9.Labell1=newLabel(“Name:”);
10.f.add(l1);
11.TextFieldtf1=newTextField(“SampleProgram”);
12.f.add(tf1);
13.tf1.setBackground(Color.GREEN);
14.tf1.setForeground(Color.RED);
15.Buttonb1=newButton(“OK”);
16.b1.setFont(newFont(“Serif”,Font.BOLD,24));
17.//b1.setEnabled(false);
18.Dimensiond=b1.getSize();
19.System.out.println(“ButtonSize:”+d.width+””+d.height);
20.f.add(b1);
21.//f.setResizable(false);
22.//f.setUndecorated(true);
23.f.setVisible(true);
24.Dimensiond1=b1.getSize();
25.System.out.println(“ButtonSize:”+d1.width+””+d1.height);
26.Dimensiond2=f.getSize();
27.System.out.println(“FrameSize:”+d2.width+””+d2.height);
28.try
29.{
30.Thread.sleep(5000);
31.}
32.catch(InterruptedExceptione){}
33.f.setVisible(false);
34.f.setSize(500,100);
35.f.setVisible(true);
36.try
37.{
38.Thread.sleep(5000);
39.}
40.catch(InterruptedExceptione){}
41.f.setVisible(false);
42.f.setBounds(20,20,100,100);
43.f.setVisible(true);
44.Dimensiond3=f.getSize();
45.System.out.println(“FrameSize:”+d3.width+””+d3.height);
46.System.out.println(f.paramString());
47.}
48.}
Output:
frame0,0,0,0x0,invalid,hidden,layout=java.awt.FlowLayout,title=,resizable,normal
ButtonSize:00
ButtonSize:5235
FrameSize:12334
FrameSize:123100
frame0,20,20,123x100,layout=java.awt.FlowLayout,title=,resizable,normal
Example17.3
Thecomponentswillbeleftaligned,ifwechangetheline:
f.setLayout(newFlowLayout(FlowLayout.CENTER));
intheaboveprogramto
f.setLayout(newFlowLayout(FlowLayout.LEFT));
Output:
Example17.4:
Thecomponentswillberightaligned,ifwechangetheline:
f.setLayout(newFlowLayout(FlowLayout.LEFT));
intheaboveprogramto
f.setLayout(newFlowLayout(FlowLayout.RIGHT));
Output:
Example17.5:-Wecanchangethegapbetweencomponentsinarow(horizontalgap)and
thegapbetweenrows(verticalgap)byusingtheoverloadedconstructorwhilesettingthe
layout:
f.setLayout(newFlowLayout(FlowLayout.CENTER,20,20))
vgap(betweenrows)hgap(betweencomponents)
Output:
3. GridLayout:
The functionality of the Grid Layout Manager is encapsulated in the class
java.awt.GridLayout. The Grid Layout Manager arranges components in tabular
formatinrowandcolumns.
Wecanthinkofcontainerspaceasagridofrowsandcolumns.Wehavetospecify
thenumberofrowsandcolumnswhilespecifyingthelayout.
TheGridLayoutManagerfitsasmanycomponentsasthesizeoftherow(numberof
columns specified in the layout) into the top row and moves the other component into
secondrow,andsoon.Thisislikethespreadsheet,whichisdividedintofixednumberof
rowsandcolumns.
The flow layout manager always honors a component’s preferred size. The
GridLayout manager takes the opposite extreme: when it performs a layout in a given
space,itignoresacomponent’spreferredsize.
Eachrowandcolumninagirdlayoutwillbethesamesize,theoverallareaavailable
tothelayoutisdividedequallybetweenthenumberofrowsandbetweenthenumberof
columns.Thegridlayoutuses“rowmajor”notation,i.e.componentsappearintheorderin
whichtheywereadded,fromlefttoright,rowbyrow.
GridLayout manger behaves strangely when we add few components (that is,
significantlyfewerthanthenumberofrowstimesthenumberofcolumns)orverymany
components(thatis,morethanthenumberofrowstimesthenumberofcolumns).
If the same components are to be laid in a taller, narrower frame, then every
componentisproportionallytallerandnarrowerandvice-versa.
Example17.6:
1.importjava.awt.*;
2.publicclassMyFrame6extendsFrame
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newMyFrame6();
7.f.setLayout(newGridLayout(5,3));
8.for(introw=0;row<5;row++)
9.{
10.f.add(newLabel(“Label”+row));
11.f.add(newButton(“Button”+row));
12.f.add(newTextField(“TextField”+row));
13.}
14.f.setSize(500,200);
15.f.setVisible(true);
16.}
17.}
Output:
4. BorderLayout:
The functionality of the BorderLayout manager is encapsulated in the class
java.awt.BorderLayout.TheBorderLayoutmanageristhedefaultmanagerforframes,so
soonerorlaterapplicationprogrammersarecertaintocometogripswithit.
Itenforcesaveryusefullayoutpolicy,butitispossiblylessintuitivethaneitherthe
flow or grid layout managers. The Flow layout manger always honor’s a component’s
preferred size; the Grid layout manager never does. The Border layout manager does
somethinginbetween.
The Border Layout Manager divides the available container space into five parts:
North,South,East,WestandCenter.Wecanaddonecomponenttoeachregion.
Each of the five regions may be empty or may contain one component (that is, no
region is required to contain a component, but the regions can only contain one
component).
The Border layout manager honors the preferred height of the North and South
components,andforcesthemtobeexactlyaswideasthecontainer.TheNorthandSouth
regionsareusefulfortoolbars,statuslines,andanyothercontrolsthatoughttobeaswide
aspossible,butnohigherthannecessary.
TheEastandWestregionsaretheoppositeofNorthandSouth.InEastandWest,a
componentgetsitspreferredwidthbuthasitsheightcontained.
Here a component Extends vertically up to the bottom of the North component (if
thereisone)ortothetopofthecontainer(ifthereisnoNorthcomponent).
SimilarlythecomponentextendsverticallydowntotheSouthcomponent(ifthereis
one)ortothebottomofthecontainer(ifthereisnoSouthcomponent).
We can only put a single component in each region well, if that component is a
container, then we can get multiple components displayed. The Border layout is not
affectedbytheorderinwhichweaddcomponents.Instead,wemustspecifywhichofthe
fiveregionswillreceivethecomponentweareadding.
Theoverloadedversionofadd()takestwoparameters:
First,thecomponentbeingadded,and
Second,anobject
ProperuseofBorderlayoutmanagerrequiresthatthesecondparameterbeaconstant
definedintheBorderLayoutclassitself.Thefiveconstantsthatweshouldknowabout
are:
BorderLayout.NORTH
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.CENTER
The fifth region that a Border layout manager controls is called Center. Center is
simplythepartofacontainerthatremainsafterNorth,South,East,andWesthavebeen
allocated.
Whenaddingacomponenttocenter,itislegalbutveryunwise,toemitthesecond
parametertoadd()call.InJavaPlatform,theBorderlayoutmanagerwillassumethatWe
meancenter;
However,inolderversions,thebehaviorwasunpredictable,andtypicallyresultedin
thecomponentbeingentirelyinvisible.
Example17.7
1.importjava.awt.*;
2.publicclassMyFrame7
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newFrame();
7.ScrollbarsbRight=newScrollbar(Scrollbar.VERTICAL);
8.f.add(sbRight,BorderLayout.EAST);
9.ScrollbarsbLeft=newScrollbar(Scrollbar.VERTICAL);
10.f.add(sbLeft,BorderLayout.WEST);
11.LabellabelTop=newLabel(“ThisisNorth”);
12.labelTop.setFont(newFont(“Serif”,Font.ITALIC,36));
13.labelTop.setForeground(Color.white);
14.labelTop.setBackground(Color.black);
15.f.add(labelTop,BorderLayout.NORTH);
16.LabellabelBottom=newLabel(“Thisissouth”);
17.labelBottom.setFont(newFont(“Monospaced”,Font.BOLD,18));
18.labelBottom.setForeground(Color.white);
19.labelBottom.setBackground(Color.black);
20.f.add(labelBottom,BorderLayout.SOUTH);
21.f.setSize(500,200);
22.f.setVisible(true);
23.}
24.}
Output:
Example17.8:
1.importjava.awt.*;
2.publicclassMyFrame8extendsFrame
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newMyFrame8();
7.//f.setLayout(newBorderLayout());
8.f.add(newButton(“N”),BorderLayout.NORTH);
9.f.add(newButton(“S”),BorderLayout.SOUTH);
10.f.add(newButton(“E”),BorderLayout.EAST);
11.f.add(newButton(“W”),BorderLayout.WEST);
12.Panelp=newPanel();
13.p.setBackground(Color.green);
14.f.add(p,BorderLayout.CENTER);
15.//f.add(p);defaultiscenter
16.f.setSize(300,300);
17.f.setVisible(true);
18.}
19.}
Output:
Example17.9:
1.importjava.awt.*;
2.classBorderLayout3extendsFrame
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newBorderLayout3();
7.//f.setLayout(newBorderLayout());
8.Paneltoolbar=newPanel();
9.toolbar.setLayout(newFlowLayout(FlowLayout.LEFT));
10.toolbar.setBackground(Color.lightGray);
11.toolbar.add(newButton(“This”));
12.toolbar.add(newButton(“Is”));
13.toolbar.add(newButton(“The”));
14.toolbar.add(newButton(“Toolbar”));
15.f.add(toolbar,BorderLayout.NORTH);
16.TextFieldstatus=newTextField(“Status.”);
17.status.setFont(newFont(“Monospaced”,Font.BOLD,48));
18.f.add(status,BorderLayout.SOUTH);
19.f.setSize(300,300);
20.f.setVisible(true);
21.}
22.}
Output:
CardLayout:-
In CardLayout we can store many cards but one card will be shown at a time.
Onlyonecardwillbevisibleatatime,butyoucanflipfromonecardtoanother.Here
cardmeansaPanel.
If we want to show two cards one at a time then we have to create first two
PanelsoneforeachcardandonemainPanelforcontainingthesetwocards.Thiscanbe
usefulforuserinterfaceswithoptionalcomponentsthatcanbedynamicallyenabledand
disableduponuserinput.
Constructors:
CardLayout();
createsanewcardlayoutwithgapsofsize0.
CardLayout(int,int);
CreatesanewCardLayoutwiththespecifiedhorizontalandverticalgaps.The
horizontalgapsareplacedattheleftandrightedges.Theverticalgapsareplacedatthe
topandbottomedges.
FromotherlayoutstheCardLayoutrequiresabitmorework.Thecardsareheld
typicallyinanobjectoftypepanel.Whencardsareaddedtothepanel,theyareusually
givenaname.Thuswewillusetheadd()methodwhenaddingcardstoapanel.
voidadd(Componentobjpanel,Objectobjname)
Here,objnameisastringthatspecifiesthenameofthecardwhosepanelisspecifiedby
objpanel.
Methods:
voidfirst(Containerparent)
Goestothefirstcardofthecontainer.
voidnext(Containerparent)
Goestothenextcardofthegivencontainer.Ifthecurrentlyvisiblecardisthe
lastone,thismethodflipstothefirstcardinthelayout.
voidprevious(Containerparent)
Goestothepreviouscardofthegivencontainer.Ifthecurrentlyvisiblecardis
thefirstone,thismethodflipstothelastcardinthelayout.
voidlast(Containerparent)
Goestothelastcardofthecontainer
voidshow(Containerparent,Stringname)
Goestothecomponentthatwasaddedtothelayoutwiththegivenname.Ifno
suchcomponentexists,thennothinghappens.
ThefollowingstepsareusedtocreatesaCardLayout
1,CreatesanewPanelobjectandanobjectofCardLayout.
2.SetthelayoutforPanelobjectasCardLayoutusingitsinstancecreatedin
firststeps.
3.Nowforeachcard,createsaseparatePanelobjectandaddwhatever
componentswewanttoaddtothatPanellikebuttons,checkboxes,etc.
4.EachPanelobjectcreatedinsteps3isaddedtothemainPanelobject
createdinstep1,givingauniquecardnameforeachcard.
5.Finallythemainpanelisaddedtotheappletwindow.
Example17.10:
1.importjava.awt.*;
2.importjava.awt.event.*;
3.importjava.applet.*;
4./*<appletcode=“CardLayoutTest”width=500height=100></applet>*/
5.publicclassCardLayoutTestextendsAppletimplementsActionListener,
MouseListener
6.{
7.Panelmp;
8.CardLayoutc1;
9.publicvoidinit()
10.{
11.Buttonb1=newButton(“First”);
12.Buttonb2=newButton(“Second”);
13.b1.addActionListener(this);
14.b2.addActionListener(this);
15.add(b1);
16.add(b2);
18.Panelp1=newPanel();
19.Labell1=newLabel(“INDIA”);
20.p1.add(l1);
22.Panelp2=newPanel();
23.Labell2=newLabel(“USA”);
24.p2.add(l2);
26.mp=newPanel();
27.c1=newCardLayout();
28.mp.setLayout(c1);
29.mp.add(p1,“Country1”);
30.mp.add(p2,“Country2”);
31.add(mp);
32.addMouseListener(this);
33.}
34.publicvoidactionPerformed(ActionEventae)
35.{
36.Buttonb=(Button)ae.getSource();
37.if(b.getLabel().equals(“First”))
38.c1.show(mp,“Country1”);
39.else
40.c1.show(mp,“Country2”);
41.}
42.publicvoidmousePressed(MouseEventme)
43.{
44.c1.next(mp);
45.}
46.publicvoidmouseReleased(MouseEventme){}
47.publicvoidmouseClicked(MouseEventme){}
48.publicvoidmouseEntered(MouseEventme){}
49.publicvoidmouseExited(MouseEventme){}
50.}
Output:
GridBagLayout-
TheGridBagLaoutisthemostcomplexandflexibleofthestandardlayout
managers.AlthoughitsoundslikeitshouldbeasubclassofGridLayout,butitisdifferent
entirely.WithGridLayout,elementsarearranged
Example17.11:
AWTcomponentscanbeclassifiedas:
1. VisualComponents.
2. ContainerComponents.
3. MenuComponents.
Visual Components and Container components both are part of the component
hierarchystartingwiththeclassjava.awt.Component.
1. Methodsofjava.awt.Componentclass
Severalmethodsareimplementedbyallthevisualandcontainercomponents,by
virtueofinheritancefromjava.awt.component.(Themenucomponentsextendfrom
java.awt.MenuComponent,Sotheydonotinheritthesamesuperclassfunctionality).
Thesemethodsarediscussedbelow:
DimensiongetSize()
ReturnsthesizeofthiscomponentintheformofaDimensionobject,whichhas
publicdatamembersheightandwidthoftypeint.
voidsetBackground(Colorc)
Setsthebackgroundcolorofacomponent.Generallybackgroundcolorisused
forrenderingthenon-textualareaofthecomponent.
voidsetForeground(Colorc)
Sets the foreground color of a component. Generally foreground color of a
component is used for rendering text. If We do not explicitly set a component’s
foregroundorbackgroundcolor,thecomponentusestheforegroundandbackground
colorofitsimmediatecontainer.
voidsetFont(Fontf)
ThesetFont()methoddeterminesthefontthatacomponentwilluseforrendering
anytextthatitneedstodisplay.IfWedonotexplicitlysetacomponent’sfont,the
componentusesthefontofitscontainer.
voidsetEnabled(Booleanb)
If the argument is true, then the component has its normal appearance. If the
argument is false, then the component is grayed out and does not respond to user
input.
voidsetSize(Dimensiond)
Setsthesizeofthecomponent.
voidsetSize(intwidth,intheight)
Setsthesizeofthecomponent.
voidsetBounds(intx,inty,intwidth,intheight)
Attempts to move and resize the component. The new location of the top- left
cornerisspecifiedbyxandy,andthenewsizeisspecifiedbywidthandheight.
voidsetVisible(Booleanb)
ThismethodtakesaBooleanargumentthatdictateswhetherthecomponentisto
beseenonthescreen.Thismethodisgenerallyusedforframes.
Note-
ifWehavetriedcallingsetSize()orsetBounds()methods,weknowthatitis
usuallyfutile.Thesizeandpositionthatweattempttogiveacomponentisoverruled
byalayoutmanager.
In fact, these two methods exist mostly for the use of layout managers. The
major exception to this rule is the Frame class, which is not under the thumb of a
layoutmanagerandisperfectlywillingtohavewesetitssizeorbounds.
VisualComponents:
Thevisualcomponentsaretheonesthatuserscanactuallyseeandinteractwith.The
AWTsupportsthefollowingvisualcomponents.
Button
Canvas
Checkbox
Choice
FileDialog
Label
List
ScrollPane
Scrollbar
TextArea
TextField
To use one of these components in a GUI, we first create an instance by calling the
appropriateconstructor.Thenweaddthecomponenttoacontainer.
Button:
TheButtonclass,implementsapushbutton.
Constructors
Button()
Button(String)
The constructor takes a string parameter that specifies the text of the button’s
label.WhenabuttonispusheditsendsanActionevent.
Methods:
StringgetLabel()
Getsthelabelofthisbutton.
voidsetLabel(Stringlabel)
Setsthebutton’slabeltobethespecifiedstring.
voidaddActionListener(ActionListener1)
Adds the specified action listener to receive action events
fromthisbutton.
Example17.12
1.importjava.awt.*;
2.classButtonTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newFrame(“TestingButtonComponent”);
7.f.setLayout(newFlowLayout());
8.Fontf1=newFont(“Arial”,Font.BOLD,40);
9.Colorc1=newColor(255,0,0);
10.Colorc2=newColor(0,255,0);
11.Buttonb1=newButton();
12.Buttonb2=newButton(“Cancel”);
13.b1.setForeground(c1);
14.b2.setForeground(c1);
15.b1.setBackground(c2);
16.b2.setBackground(c2);
17.b1.setFont(f1);
18.b2.setFont(f1);
19.b1.setLabel(“Ok”);
20.System.out.println(b2.getLabel());
21.f.add(b1);
22.f.add(b2);
23.f.setSize(500,200);
24.f.setVisible(true);
25.}
26.}
Output:
Canvas:
A Canvas is a component, which has no default appearance or behavior. We can
subclass canvas to create custom drawing regions, work areas, components and so on.
Canvases receive input events from the mouse and the keyboard, it is up to the
programmertotransformthoseinputsintoameaningfullookandfeel.
Thedefaultsize(or,moreproperly,thepreferredsize)ofacanvasisuselesslysmall.
Onewaytodealwiththisproblemistousealayoutmanagerthatwillresizethecanvas.
AnotherwayistocallsetSize()onthecanvasourself,canvasesareararecasewherethis
mightactuallyworkbecausethevaluewesendintothesetSize()methodbecomesthe
canvas’spreferredsize.
Example17.13
1.importjava.awt.*;
2.classCanvasTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newFrame();
7.f.setLayout(newFlowLayout());
8.Canvasc=newMyCanvas();
9.c.setSize(100,100);
10.f.add(c);
11.f.setSize(300,300);
12.f.setVisible(true);
13.}
14.}
15.classMyCanvasextendsCanvas
16.{
17.publicvoidpaint(Graphicsg)
18.{
19.setBackground(Color.green);
20.g.setColor(Color.red);
21.g.drawLine(0,0,99,99);
22.}
23.}
Output:
Checkbox:
A check box is a two state button. The two states are true (checked) and false
(unchecked).Thethreebasicformsofthecheckboxconstructorsare:
Constructors-
Checkbox()
Createsacheckboxwithanemptystringforitslabel.
Checkbox(Stringlabel)
Createsacheckboxwiththespecifiedlabel.
Checkbox(Stringlabel,booleanstate)
Createsacheckboxwiththespecifiedlabelandsetsthespecifiedstate.Ifwedo
notspecifyandinitialstate,thedefaultisfalse.
Methods:
StringgetLabel()
Getsthelabelofthischeckbox.
voidsetLabel(Stringlabel)
Setsthischeckbox’slabeltobethestringargument.
boleangetState()
Determineswhetherthischeckboxisinthe“on”or“off“state.
voidsetState(booleanstate)
Setsthestateofthischeckboxtothespecifiedstate.
voidaddItemListener(ItemListener)
Addsthespecifieditemlistenertoreceiveitemeventsfromthischeck
box.
Example17.14
1.importjava.awt.*;
2.classCheckboxTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newFrame(“TestingCheckboxComponent”);
7.f.setLayout(newGridLayout(3,1));
8.Checkboxc1=newCheckbox();
9.Checkboxc2=newCheckbox(“Lunch”,true);
10.Checkboxc3=newCheckbox(“Dinner”);
11.c1.setLabel(“BreakFast”);
12.c3.setState(true);
13.f.add(c1);f.add(c2);f.add(c3);
14.
15.if(c1.getState())
16.System.out.println(c1.getLabel());
17.if(c2.getState())
18.System.out.println(c2.getLabel());
19.if(c3.getState())
20.System.out.println(c3.getLabel());
21.
22.f.setSize(100,100);
23.f.setVisible(true);
24.}}
Output:
AnotherExample-
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classCheckboxTestextendsFrameimplementsItemListener
4.{
5.Checkboxc1;
6.TextFieldtf1;
7.CheckboxTest()
8.{
9.setLayout(newGridLayout(2,1));
10.c1=newCheckbox(“Red”);
11.c1.addItemListener(this);
12.add(c1);
13.tf1=newTextField();
14.add(tf1);
15.setSize(100,100);
16.setVisible(true);
17.}
18.publicstaticvoidmain(Stringargs[])
19.{
20.newCheckboxTest();
21.}
22.publicvoiditemStateChanged(ItemEventie)
23.{
24.if(c1.getState())
25.tf1.setBackground(Color.red);
26.else
27.tf1.setBackground(Color.white);
28.}
29.}
Radiobutton:
Checkboxes can be grouped together into checkbox groups, which have radio
behavior.Withradiobehavior,onlyonememberofacheckboxgroupcanbetrueatany
time; selecting a new member changes the state of the previously selected member to
false.Manywindowssystems(Motifforexample)implementradiogroupsascomponents
intheirownright.
Wecanimplementradiobehaviorbycreatingmultiplecheckboxesandgroupingthem
usingjava.awt.CheckboxGroupClass.InJavathejava.Awt.CheckboxGroupclassisnot
acomponent;itissimplyanon-visibleclassthatorganizescheckboxes.Thismeansthat
Javaimposesnorestrictionsonthespatialrelationshipsamongmembersofacheckbox
group.
If we want to, we could put one member of a group in the upper left corner of a
frame,anothermemberinthelower-rightcorner,andathirdmemberinadifferentframe
altogether.Ofcourse,theresultwouldprobablybecontrarytobothreasonandmostGUI
styleguides.
TwomethodsoftheCheckboxGroupclasssupportgettingandsettingthecurrently
selectedmemberorthegroup.
CheckboxgetSelectedCheckbox()
Getsthecurrentchoicefromthischeckboxgroup.
voidsetSelectedCheckbox(Checkboxbox)
Sets the currently selected check box in this group to be
specifiedcheckbox.
Example17.15
1.importjava.awt.*;
2.classCheckboxGroupTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newFrame(“TestingRadioButtonComponent”);
7.f.setLayout(newGridLayout(3,1));
8.CheckboxGroupcbg=newCheckboxGroup();
9.Checkboxc1=newCheckbox(“BreakFast”,false,cbg);
10.Checkboxc2=newCheckbox(“Lunch”,true,cbg);
11.Checkboxc3=newCheckbox(“Dinner”,false,cbg);
12.c3.setState(true);
13.f.add(c1);f.add(c2);f.add(c3);
14.
15.if(c1.getState())
16.System.out.println(c1.getLabel());
17.elseif(c2.getState())
18.System.out.println(c2.getLabel());
19.elseif(c3.getState())
20.System.out.println(c3.getLabel());
21.
22.f.setSize(100,100);
23.f.setVisible(true);
24.}
25.}
Output:
Choice:
Achoiceisapull–down/drop-downlist.
Methods:
voidadd(Stringitem)
AddsanitemtothisChoicemenu.
voidaddItemListener(ItemListeneri)
Addsthe specifieditem listenerto receiveitemeventsfrom
thischoicemenu.
StringgetItem(intindex)
GetstheStringatthespecifiedindexinthisChoicemenu.
intgetItemCount()
ReturnsthenumberofitemsinthisChoicemenu.
intgetSelectedIndex()
Returnstheindexofthecurrentlyselecteditem.
StringgetSelectedItem()
Getsarepresentationofthecurrentchoiceasastring.
voidinsert(Stringitem,intindex)
Insertstheitemintothischoiceatthespecifiedposition.
voidremove(intposition)
Removesthefirstoccurrenceofitemformthechoicemenu.
voidremove(Stringitem)
RemovesthefirstoccurrenceofitemfromtheChoicemenu.
voidremoveAll()
Removesallitemsfromthechoicemenu.
voidselect(intpos)
Setstheselectediteminthischoicemenutobetheitematthe
specifiedposition.
voidselect(StringStr)
Sets the selected item in this Choice menu to be the item
whosenameisequaltothespecifiedstring.
Example17.16
1.importjava.awt.*;
2.classChoiceTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsInterruptedException
5.{
6.Framef=newFrame(“TestingChoiceComponent”);
7.f.setLayout(newFlowLayout());
8.f.setSize(100,100);
9.f.setVisible(true);
10.Choicec1=newChoice();
11.c1.add(“BreakFast”);
12.c1.add(“Lunch”);
13.c1.add(“Dinner”);
14.f.add(c1);
15.c1.select(“Dinner”);//c1.select(2);
16.Thread.sleep(1000);
17.System.out.println(c1.getSelectedItem());
18.System.out.println(c1.getSelectedIndex());
19.System.out.println(c1.getItemCount());
20.System.out.println(c1.getItem(0));
21.c1.insert(“Brunch”,1);
22.c1.remove(2);//c1.remove(“Lunch”);
23.}
24.}
Output:
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classCheckboxItemTestextendsFrameimplementsItemListener
4.{
5.TextFieldtf1;
6.Choicec1;
7.CheckboxItemTest()
8.{
9.setLayout(newFlowLayout());
10.c1=newChoice();
11.c1.add(“red”);
12.c1.add(“green”);
13.c1.add(“blue”);
14.tf1=newTextField(8);
15.tf1.setBackground(Color.red);
16.c1.addItemListener(this);
17.add(c1);
18.add(tf1);
19.setSize(200,200);
20.setVisible(true);
21.}
22.publicstaticvoidmain(Stringargs[])
23.{
24.newCheckboxItemTest();
25.}
26.publicvoiditemStateChanged(ItemEventie)
27.{
28.Strings=(String)ie.getItem();
29.if(s.equals(“red”))
30.tf1.setBackground(Color.red);
31.elseif(s.equals(“green”))
32.tf1.setBackground(Color.green);
33.elseif(s.equals(“blue”))
34.tf1.setBackground(Color.blue);
35.}
36.}
Label:
The simplest visible AWT component is label. Labels are not generally used to
respondtouserinput,ortosendoutevents.
Constructors:
Label()
Constructsanemptylabel.
Label(Stringtext)
Constructsanewlabelwiththespecifiedstringoftext,leftjustified.
Label(Stringtext,intalignment)
Constructsanewlabelthatpresentthespecifiedstringoftextwiththespecified
alignment.
Thedefaultalignmentforlabelsistotheleft.Tosetthealignment,usethethird
fromoftheconstructorandpassinoneofthefollowing:
Lable.LEFT
Label.CENTER
Label.RIGHT
Methods:
StringgetText()
Getsthetextofthethislabel.
voidsetText(Stringtext)
Setsthetextforthislabeltothespecifiedtext.
Example17.17
1.importjava.awt.*;
2.classLabelTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newFrame(“TestingLabelComponent”);
7.f.setLayout(newGridLayout(3,3));
8.f.setFont(newFont(“Arial”,Font.PLAIN,20));
9.Labell1=newLabel(“India”,Label.LEFT);
10.Labell2=newLabel(“Pakistan”,Label.LEFT);
11.Labell3=newLabel(“UK”,Label.LEFT);
13.Labell4=newLabel(“India”,Label.CENTER);
14.Labell5=newLabel(“Pakistan”,Label.CENTER);
15.Labell6=newLabel(“UK”,Label.CENTER);
17.Labell7=newLabel(“India”,Label.RIGHT);
18.Labell8=newLabel(“Pakistan”,Label.RIGHT);
19.Labell9=newLabel(“UK”,Label.RIGHT);
21.l3.setText(“USA”);
22.System.out.println(l1.getText());
24.f.add(l1);f.add(l4);f.add(l7);
25.f.add(l2);f.add(l5);f.add(l8);
26.f.add(l3);f.add(l6);f.add(l9);
28.f.setSize(500,200);
29.f.setVisible(true);
30.}
31.}
Output:
List:
Alist isa collection oftext items, arrangedvertically. Ifa list containsmore items
thanitcandisplay,itautomaticallyacquiresaverticalscrollbar.
Constructors:
List()
CreatesanewScrollinglist.Thisconstructordoesnotspecifynumberofvisible
rowsbutproducesadefault preferredheightof fourrows.Of course,inmany
casestheactualheightofalistwillbedictatedbyalayoutmanager.
List(introws)
Createsanewscrollinglistinitializedwiththespecifiednumberofvisiblelines.
List(introws,booleanmultipleMode)
Createsanewscrollinglistinitializedtodisplaytospecifiednumberofrowsand
allowsmultipleselections.
Example17.18
1.importjava.awt.*;
2.classListTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newFrame();
7.f.setLayout(newFlowLayout());
8.Listl1=newList(3,true);
9.l1.add(“India”);
10.l1.add(“Nepal”);
11.l1.add(“ShriLanka”);
12.l1.add(“USA”);
13.l1.add(“UK”);
14.f.add(l1);
15.System.out.println(l1.getRows());
16.f.setSize(300,300);
17.f.setVisible(true);
18.}
19.}
Output:
TheListhasfiveitemsbutonly3visiblerows,soascrollbarisautomatically
providedtogiveaccesstothebottomtwolines.
Note:SelectinganiteminalistcausesthelisttosendanItemevent;double-clickingan
itemsendsanActionEvent.
voidadd(Stringitem)
Addthespecifieditemtotheendofscrollinglist.
voidadd(Stringitem,intindex)
Addsthespecifieditemtothescrollinglistatthepositionindicatedby
theindex.
voidaddActionListener(ActionListeneri)
Addsthespecifieditemlistenertoreceiveactioneventsform
thislist.
voidaddItemListener(ItemListeneri)
Addsthespecifieditemlistenertoreceiveitemeventsformthislist.
StringgetItem(intindex)
Getstheitemassociatedwiththespecifiedindex.
intgetItemCount()
Getsthenumberofitemsinthelist.
String[]getItems()
Getstheitemsinthelist.
intgetRows()
Getsthenumberofvisiblelinesinthislist.
intgetSelectedIndex()
Getstheindexoftheselectediteminthelist.
int[]getSelectedIndexes()
Getstheselectedindexesinthelist.
StringgetSelectedItem()
GetstheSelectediteminthisscrollinglist.
String[]getSelectedItems()
Getstheselecteditemsinthisscrollinglist.
voidremove(intposition)
Removestheitematthespecifiedpositionfromthisscrollinglist.
voidremove(Stringitem)
Removesthefirstoccurrenceofanitemfromthelist.
voidremoveAll()
Removesallitemsfromthislist.
voidreplaceItem(SringnewValue,intindex)
Replaestheitematthespecifiedindexinthescrollinglistwiththenew
string.
voidselect(intindex)
Selectstheitematthespecifiedindexinthescrollinglist.
voidsetMultipleMode(booleanb)
Sets the flag that determines whether this list allows multiple
selections.
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classListTestextendsFrameimplementsActionListener
4.{
5.Buttonb1,b2,b3,b4,b5,b6;
6.Listl1,l2;
7.TextFieldtf1,tf2;
8.ListTest()
9.{
10.setLayout(newGridLayout(3,3));
11.l1=newList(3,true);
12.l2=newList(3,true);
13.b1=newButton(“>”);
14.b2=newButton(“>>”);
15.b3=newButton(“<”);
16.b4=newButton(“<<”);
17.b5=newButton(“Add”);
18.b6=newButton(“Add”);
19.b1.addActionListener(this);
20.b2.addActionListener(this);
21.b3.addActionListener(this);
22.b4.addActionListener(this);
23.b5.addActionListener(this);
24.b6.addActionListener(this);
25.tf1=newTextField();
26.tf2=newTextField();
27.Panelp1=newPanel();
28.p1.setLayout(newGridLayout(4,1));
29.p1.add(b1);
30.p1.add(b2);
31.p1.add(b3);
32.p1.add(b4);
33.add(l1);add(p1);add(l2);
34.add(tf1);add(newLabel());add(tf2);
35.add(b5);add(newLabel());add(b6);
36.setSize(300,300);
37.setVisible(true);
38.}
39.publicstaticvoidmain(Stringargs[])
40.{
41.newListTest();
42.}
43.publicvoidactionPerformed(ActionEventae)
44.{
45.Buttonb=(Button)ae.getSource();
46.if(b==b1)
47.{
48.Strings[]=l1.getSelectedItems();
49.for(inti=0;i<s.length;i++)
50.{
51.l2.add(s[i]);
52.l1.remove(s[i]);
53.}
54.}
55.elseif(b==b2)
56.{
57.Strings[]=l1.getItems();
58.for(inti=0;i<s.length;i++){
59.l2.add(s[i]);
60.l1.remove(s[i]);
61.}
62.
63.}
64.elseif(b==b3)
65.{
66.Strings[]=l2.getSelectedItems();
67.for(inti=0;i<s.length;i++)
68.{
69.l1.add(s[i]);
70.l2.remove(s[i]);
71.}
72.}
73.elseif(b==b4)
74.{
75.Strings[]=l2.getItems();
76.for(inti=0;i<s.length;i++)
77.{
78.l1.add(s[i]);
79.l2.remove(s[i]);
80.}
81.}
82.elseif(b==b5)
83.{
84.l1.add(tf1.getText());
85.}
86.elseif(b==b6)
87.{
88.l2.add(tf2.getText());
89.}
90.}
91.}
TextFieldandTextArea:
The Text Field and Text Area classes implement one-dimensional and two-
dimensionalcomponentsfortextinput,displayandediting.Bothclassesextendfromthe
TextComponentsuperclass.
Object Component TextComponent (TextField,TextArea)
Bothclasses(TextFieldandTextArea)haveavarietyofconstructors,whichofferthe
optionofspecifyingornotspecifyinganinitialstringorpreferredsize.Theconstructors
that do not specify a preferred size are most appropriate for situations where a layout
managerwillignorethecomponent’spreferredsize.
ConstructorsofTextFieldClass:
TextField()
Constructsanewtextfiled.
TextField(intcolumns)
Constructsanewemptytextfieldwiththespecifiednumberofcolumns.
TextField(Stringtext)
Constructsanewtextfieldinitializedwiththespecifiedtext.
TextField(Stringtext,intcolumns)
Constructs a new text field initialized with the specified text to be displayed, and
wideenoughtoholdthespecifiednumberofcolumns.
ConstructorsofTextAreaClass:
TextArea()
Constructsanewtextareawiththeemptystringtext.
TextArea(introws,intcolumns)
Constructs a new text area with the specified number of row & columns and the
emptystringastext.
TextArea(Stringtext)
Constructsanewtextareawiththespecifiedtext.
TextArea(Stringtext,introws,intcolumns)
Constructsanewtextareawiththespecifiedtext,andwiththespecifiednumberof
rowsandcolumns.
TextArea(Stringtext,introws,intcolumns,intScrollbarPolicy)
Constructsanewtextareawiththespecifiedtext,andwiththerows,columns,and
scrollbarpolicyasspecified.
ThetextArea classdefinesseveral constantsthatcan besuppliedas valuesforthe
scrollbarPolicyargument.
SCROLLBARS_BOTH,
SCROLLBARS_VERTICAL_ONLY,
SCROLLBARS_HORIZONTAL_ONLY,
SCROLLBARS_NONE.
For both classes, there are some surprising issues to the number of columns
parameter.
First,thenumberofcolumnsisameasureofwidthintermsofcolumnsoftext,
as rendered in a particular front. A 25-columns text area with a tiny will be very
narrow,whilea5-columnstextareawithahugefontwillbeextremelywide.
Next, there is the problem of proportional fonts. For a fixed width font, it is
obviouswhatthecolumnwidthshouldbe.Forproportionalfont,thecolumnwidthis
taken to be the average of all the font’s character widths. This average is a simple
average of all the characters in the set; it does not take into account frequency of
characters use. So in most cases, text components that contain largely lowercase
letterswilldisplaymorethantherequestednumberofcharacters.
MethodsintextComponentClass:
StringgetSelectText()
Returns the selected text from the text that is presented by this text
component.
StringgetText()
Returnsthetextthatispresentedbythistextcomponent.
voidSetEditable(Booleanb)
Sets the flag that determines whether or not this text component is
editable.
voidsetTextSrtingt)
Setsthetextthatispresentedbythistextcomponenttobethespecified
text.
Example17.19
importjava.awt.*;
1.classTextFieldTest
2.{
3.publicstaticvoidmain(Stringargs[])
4.{
5.Framef=newFrame();
6.f.setLayout(newFlowLayout());
7.TextFieldtf1=newTextField();
8.TextFieldtf2=newTextField(8);
9.TextFieldtf3=newTextField(“matrix”);
10.TextFieldtf4=newTextField(“matrix”,20);
11.TextAreata1=newTextArea();
12.TextAreata2=newTextArea(3,8);
13.TextAreata3=newTextArea(“abc\nxyz\naaa”);
14.TextAreata4=newTextArea(“abc\nxyz\naaa”,2,2);
15.TextAreata5=newTextArea(“abc\nxyz\naaa”,4,20,
TextArea.SCROLLBARS_BOTH);
16.f.add(tf1);f.add(tf2);f.add(tf3);f.add(tf4);
17.f.add(ta1);f.add(ta2);f.add(ta3);f.add(ta4);
18.f.add(ta5);
19.tf1.setText(“abc”);
20.System.out.println(tf3.getText());
21.tf3.setEditable(false);
22.f.setSize(800,400);
23.f.setVisible(true);
24.}
25.}
Output:
FileDialog:
This class represents a file open or file save dialog. A file dialog is a modal
dialog,whichmeansinputfromthedialog’sparentframewillbedirectedexclusivelyto
the dialog, as long as dialog remains visible on the screen. The dialog is automatically
removed when the use specifies a file or clicks the cancel button. The most useful File
dialogconstructorhasthefollowingform:
FileDialog(Frameparent,Stringtitle,intmode)
The dialog’s parent is the frame over which the dialog will appear. The title string
appearsinthedialog’stitlebar.
Themodeshouldbeeither.
FileDialog.LOADor
FileDialog.SAVE
Aftertheuserhasspecifiedafile,thenameofthefileoritsdirectorycanberetrieved
withthefollowingmethods.:
StringgetDirectory()
Getstheselecteddirectoryofthisfiledialog.
StringgetFile()Getstheselectedfileofthisfiledialog.
Example17.20
1.importjava.awt.*;
2.publicclassFileDialogTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newFrame();
7.f.setLayout(newFlowLayout());
8.f.setSize(200,200);
9.f.setVisible(true);
10.FileDialogfd=newFileDialog(f,“Loadfile”,FileDialog.LOAD);
11.fd.setVisible(true);
12.System.out.println(fd.getFile());
13.System.out.println(fd.getDirectory());
14.}
15.}
ScrollPane:
AscrollPanecancontainasinglecomponent,whichmaybetallerorwiderthan
thescrollpaneitself.
If the container component is larger than the scroll pane, then the default
behavior of the scroll pane is to acquire horizontal and/ or vertical scroll bars as
needed.
Therearetwoconstructorsforthisclass:
ScrollPane()
Createanewscrollpanecontainerwithascrollbardisplaypolicyof“asneeded”.
ScrollPane(intscrollbarDisplayPolicy)
Create a new scrollpane container with the specified scroll bar behavior. The
scrollpanedisplaypolicyshouldbeoneof:
ScrollPane.SCROLLBARS_AS_NEEDED(default)
ScrollPane.SCROLLBARS_ALWAYS
ScrollPane.SCROLLBARS_NEVER
TheCode listedbelowcreates ascroll panewithdefault (As_NEEDED)scroll
bar behavior. The scroll pane contains a very large button; So the scroll bars will
definitelybeneeded.
Example17.21
1.importjava.awt.*;
2.classSPaneTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newFrame();
7.f.setLayout(newGridLayout(1,2));
8.f.setSize(250,150);
9.ScrollPanespane=newScrollPane();
10.spane.setBackground(Color.green);
11.f.add(spane);
12.f.add(newTextArea());
13.Buttonb1=newButton(“PushMe!”);
14.b1.setFont(newFont(“Serif”,Font.ITALIC,100));
15.spane.add(b1);
16.f.setVisible(true);
17.}
18.}
Output:
Scrollbar-
The Scrollbar component that adjusts lists and scroll panes is available as a
componentinitsownright.Therearethreeconstructors:
Scrollbar()
Constructsanewverticalscrollbar.
Scrollbar(intorientation)
Constructsanewscrollbarwithhespecifiedorientation.
Scrollbar (int orientation, int initialValue, int sliderSize, int minValue, int
maxValue)
Constructs a new scroll bare with the specified orientation initial value, slider
size,andminimumandmaximumvalues.ThesliderSizeparametercontrolsthesize
oftheslider,butnotinpixelunits.
Forconstructorsthattakeanorientationparameter,thisvalueshouldbeoneof:
Scrollbar.HORIZONTAL
Scrollbar.VERTICAL
Example17.22
1.importjava.applet.*;
2.importjava.awt.*;
3.importjava.awt.event.*;
4./*<appletcode=“RGB”width=500height=200></applet>*/
5.publicclassRGBextendsAppletimplementsAdjustmentListener
6.{
7.TextFieldtf1;
8.Scrollbarsb1,sb2,sb3;
9.publicvoidinit()
10.{
11.setLayout(newGridLayout(4,1));
12.sb1=newScrollbar(Scrollbar.HORIZONTAL,0,10,0,255);
13.sb2=newScrollbar(Scrollbar.HORIZONTAL,0,10,0,255);
14.sb3=newScrollbar(Scrollbar.HORIZONTAL,0,10,0,255);
15.sb1.addAdjustmentListener(this);
16.sb2.addAdjustmentListener(this);
17.sb3.addAdjustmentListener(this);
18.tf1=newTextField(8);
19.add(tf1);add(sb1);
20.add(sb2);add(sb3);
21.}
22.publicvoidadjustmentValueChanged(AdjustmentEventae)
23.{
24.inta=0,b=0,c=0;
25.a=sb1.getValue();
26.b=sb2.getValue();
27.c=sb3.getValue();
28.Colorc1=newColor(a,b,c);
29.tf1.setBackground(c1);
30.}
31.}
CHAPTER
∞18∞
(INTRODUCTIONTOAWTEVENTS)
Introduction-
WhenanormalJavaprogram(whichisnotGUIbased)needsinput,itprompts
the user and then calls some input method, such as readline() i.e. the interaction is
initiatedby theprogram. Thisisnotthewayinwhichgui-basedprograms behave.The
userinitiatesinteractionwiththeprogramratherthanprograminitiatingtheaction.
Forexample,inawordprocessingsoftware,userinitiatesactionbyclickingon
differentbuttons,whichgeneratesaneventandsomepieceofcodeisexecutedasaresult
and accordingly some action takes place. The clicking on save button will invoke the
methodwhichsavesthecontentstoafile.
Interface Event(Methods) class Methods
ActionListener actionPerformed() ActionEventae getSource
ItemListener itemStateChanged() ItemEventie getItem
AdjustmentListener adjustmentValueChanged() AdjustmentEventae getAdjustable()
MouseListener
MouseAdapter
mouseEntered
mouseExited
mouseClicked
mousePressed
mouseReleased
MouseEventme getX()
getY()
getPoint()
getClickCount()
getButton()
getModifiersEx()
getModifiersExText()
MouseMotionListener
MouseMotionAdapter
mouseMoved
mouseDragged
MouseEventme sameasprev.
KeyListener
KeyAdapter
keyTyped
keyPressed
keyReleased
KeyEventke getKeyChar()
getKeyCode()
FocusListener
FocusAdapter
focusGained
focusLost
FocusEventfe getSource()
WindowListener
WindowAdapter
windowOpend
windowClosing
windowClosed
windowActivated
windowDeactivated
windowIconified
windowDeiconified
WindowEventwe getWindow()
Java uses event delegation model for event handling. In the event delegation
modelacomponentmaybetoldwhichobjectorshouldbenotifiedwhenthecomponent
generatesaparticularkindofevent.
Ifacomponentisnotinterestedinaneventtype,theneventsofthattypewillnot
bepropagated.Thedelegationmodelisbasedonthefollowingkeyconcepts:
Eventclasses.
Eventlisteners.
Adapters.
Eventclasses:
Clicking on a button results in an event. The event has lot of information
associatedwithit,like:time,componentgeneratingtheevent,co-ordinatesofthepointat
whichclickingtookplaceetc.
Thisinformationisputinsideaneventclass.Theconceptissimilartoexception
handling. Whenever an exception occurs an object of appropriate exception class is
createdandalltheexceptionrelatedinformationisputintothisobject.
Wehavehierarchyofeventclasses,whichissomewhatsimilartothehierarchy
of exception classes. Whenever some event occurs, it is detected by event handling,
mechanism,whichcreatesobjectsofappropriateeventclassandputsalltheeventrelated
informationintoit.
Eventlisteners:
Event listeners are responsible for taking appropriate action when an event
occurs. An event listener is an object to which a component has delegated the task of
handlingaparticularkindofevent.
When the component experiences input, an event of the appropriate type is
constructed,theeventisthenpassedastheparametertoamethodcallonthelistener.A
listenermustimplementtheinterfacethatcontainsthateventhandlingmethod.
We can compare the event listeners with the catch blocks for handling the
exceptions. We need to provide a catch block corresponding to the exception to be
handled.Similarlyifwewanttohandleaneventgeneratedbysomecomponent,weneed
toprovideappropriatelistener.
Thelistenersareassociatedwiththecomponents.Differenteventshavedifferent
listeners.Wheneventoccurs,anappropriatelistenermethodiscalledandeventobjectis
passedasparameter.
Adapters:
The listeners defined in the language are interfaces only. We need to provide
implementationoftheappropriatelistener.Somelistenershave2ormoremethods.
To implement a listener having more than one method, we need to provide
implementation of all the methods even if we are interested only in one method. the
adapterclassesprovidethesolutiontothisproblem.
Anadapterclassprovidesdummyimplementationofallthemethodsofalistener.
This helps in reducing programming efforts. If we want to use just one method of a
listenerclasscontaining say5methods thenwecan simplyextentthe adapterclassand
overridethedesiredmethod.
Eventhierarchy:
TheAWThasawell-definedeventhierarchy.Normallytheclassescorresponding
toleafnodesintheeventhierarchyrepresenttheactualevents.Whilenon-leafclassesact
asbaseclassesandencapsulate.
AWTeventhierarchyisdescribedinthefollowingdiagram.
Thejava.util.eventObjectclass:
Thisisthetopmostsuperclassofalltheeventclasses.Itisaverygeneralclass,
withonlyonemethodofinterest,whichreturnstheobjectthatoriginatedtheevent.
Objectgetsource()
Thejava.awt.AWTEventClass:
Onesubclassofeventobjectisjava.awt.AWTEvent,whichisthesuperclassof
allthedelegationmodeleventclasses.Again,thereisonlyonemethodofinterest,which
returntheidoftheevent.
intgetID()
Anevent’sIDisanintthatspecifiestheexactnatureoftheevent.Forexample,
aninstanceofthemouseeventclasscanrepresentoneofsevenoccurrences:click,Drag,
Entrance,Move,Exit,Press,Release.Eachofthesepossibilitiesisrepresentedbyanint
MouseEvent.MOUSE_CLICKED,MouseEvent.MOUSE_DRAGGED,andsoon.
Thesubclassesofjava.awt.AWTEventrepresentthevariouseventtypesthatcan
be generated by the various AWT components, and contain all necessary information
relatingtotheactivitythattriggeredtheevent.
Thenon-superclasseventtypes(i.ethosethatareactuallyfiredbycomponent)are:
1. ActionEvent:generalbyactivationofcomponentsforexample.itisgeneratedon
buttonclick,ondouble-clickonlistitemandonpressingenterinaTextField.
2. AdjustmentEvent: generated by adjustment of adjustable components such as
scrollbars.
3. ContainerEvent: generated when components are added to or removed from a
container.
4. FocusEvent:generatedwhenacomponentreceivesorlosesinputfocus.
5. ItemEvent:generatedwhenanitemisselectedfromalist,choice,orcheckbox.
6. KeyEvent:generatedbykeyboardactivity.
7. MouseEvent:generatedbymouseactivity.
8. MouseWheelEvent:Anevent,whichindicatesthatthemousewheelwasrotated
inacomponent.
9. WindowEvent: generated by window activity ( such as iconifying or
deiconifying.)
10. TextEvent:generatedwhenatextcomponentismodified.
Thejava.awt.eventpackage:
Thispackageprovidestheinterfacesandclassesfordealingwithdifferenttypes
of events fired by AWT components. The events are fired by event sources. An event
listener registers with an event source to receive notifications about the events of a
particulartype.
This package defines events and event listeners, as well as event listener
adapters, which are convenience classes to make easier the process of writing event
listeners.
EventListenerInterfaces:
Eacheventclasshasacorrespondinglistenerinterfaceanddefinesoneormore
methods. The most commonly used listener interfaces are described in the following
sections.
TheActionListenerInterface:
This is the listener interface for receiving action events. The class that is
interestedinprocessinganactioneventimplementthisinterface,andtheobjectcreated
withthatclassisregisteredwithacomponent,usingthecomponent’saddActionListener()
method.Whentheactioneventoccurs,theactionlistener’sactionperformed()methodis
invokedwhosesignaturesare:
void actionPerfomed(ActionEvente)
Invokedwhenanactionoccurs.
TheAdjustmentListernerInterface:
Thisisthelistenerinterfaceforreceivingadjustmentevents.
void adjustmentValueChanged(Adjustmentevente)
Invokedwhenthevalueofthethumb/sliderchanges.
TheContainerListenerinterface:
This is the listener interface for receiving events when a component is added to or
removedfromacontainer.
Methods:
void
componentAdded(containerEvente)
Invokedwhenacomponentisaddedtothecontainer.
void componentRemoved(containerEvente)
Invokedwhenacomponentisremovedfromthecontainer.
TheFocusListenerInterface:
Thisisthelistenerinterfaceforreceivingeventswhenacomponentgainsorlosesfocus.
Methods:
void focusGained(focusEvente)
Invokedwhenacomponentgainsthekeyboardfocus.
void focusLost(focusEvente)
Invokedwhenacomponentlosesthekeyboardfocus.
TheItemListenerInterface:
Thisisthelistenerinterfaceforreceivingitemevents.
Method:
voiditemStateChanged(ItemEvente)
Invokedwhenanitemhasbeenselectedordeselectedbytheuser.
ThekeyListenerInterface:
Thisisthelistenerinterfaceforreceivingkeyboardevents(keystrockes)
void keyPressed(KeyEvente)
Invokedwhenakeyispressed.
void keyReleased(KeyEvente)
Invokedwhenakeyisreleased.
void keyTyped(KeyEvente)
Invokedwhenakeyistyped(pressedandreleased.)
TheMouseListenerInterface:
Thisisthelistenerinterfaceforreceivingmouseevents(press,release.Click,enter,and
exit)onacomponent.
Method:
voidmouseClicked(MouseEvente)
Invokedwhenthemousebuttonisclicked(pressedandreleased)ona
Component.
voidmouseEntered(MouseEvente)
Invokedwhenthemouseentersacomponent.
voidmouseExited(MouseEvente)
Invokedwhenamouseexitsacomponent.
voidmousePressed(MouseEvente)
Invokedwhenamousebuttonispressedonacomponent.
voidmouseReleased(MouseEvente)
Invokedwhenamousebuttonisreleasedonacomponent.
MouseMotionListener:
This is the listener interface for receiving mouse motion events (move and drag) on a
component.
Method:
voidmouseDragged(MouseEvente)
Invokedwhenamousebuttonispressedonacomponentandthen
dragged.
voidmouseMoved(MouseEvente)
Invoked when a mouse cursor is moved over a component but no
buttonsispushed.
TheMouseWheelListenerInterface:
Thisisthelistenerinterfaceforreceivingmousewheeleventsonacomponent.
Method:
voidmouseWheelMoved(MouseEvente)
Invokedwhenthemousewheelisrotated.
TheWindowListenerInterface:
whenthewindow’sstatuschangesbyvirtueofbeingopened,closed,activatedor
deactivated,iconifiedordeiconified,therelevantmethodinthelistenerobjectisinvoked,
andthewindoweventispassedtoit.
Methods:
voidwindowAcitvated(WindowEvente)
Invokedwhenthewindowissettobetheactivewindow.
voidwindowClosed(WindowEvente)
Invoked when the window has been close as the result of calling
Disposeonthewindow.
voidwindowClosing(WindowEvente)
Invoked when the user attempts to close the window from the
window’ssystemmenu.
voidwindowDeactivated(WindowEvente)
Invokedwhenawindowisnolongertheactivewindow.
voidwindowDeiconified(WindowEvente)
invokedwhenawindowischangedfromaminimizedtoa
normalstate.
voidwindowIconified(WindowEvente)
Invoked when a window is changed from a normal to a minimized
state.
voidwindowOpended(WindowEvente)
Invokedthefirsttimeawindowismadevisible.
HandlingActionEvent:
Example18.1
The following example explains how to handle the actionevnet generated as a result of
clickingonabutton.
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classA1
4.{
5.publicstaticvoidmain(Stringargs[])
6.{
7.Framef=newFrame();
8.f.setLayout(newFlowLayout());
9.f.setSize(500,100);
10.Buttonb1=newButton(“Pushme”);
11.Buttonb2=newButton(“Clickme”);
12.b1.addActionListener(newB());
13.b2.addActionListener(newC());
14.f.add(b1);
15.f.add(b2);
16.f.setVisible(true);
17.}
18.}
19.classBimplementsActionListener
20.{
21.publicvoidactionPerformed(ActionEventae)
22.{
23.System.out.println(“ButtonPushed”);
24.}
25.}
26.classCimplementsActionListener
27.{
28.publicvoidactionPerformed(ActionEventae)
29.{
30System.out.println(“ButtonClicked”);
31.}
32.}
Output:
Example18.2:
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classA2implementsActionListener
4.{
5.staticButtonb1=null,b2=null;
6.publicstaticvoidmain(Stringargs[])
7.{
8.Framef=newFrame();
9.f.setLayout(newFlowLayout());
10.f.setSize(500,100);
11.b1=newButton(“Pushme”);
12.b2=newButton(“Clickme”);
13.b1.addActionListener(newA2());
14.b2.addActionListener(newA2());
15.f.add(b1);
16.f.add(b2);
17.f.setVisible(true);
18.}
19.publicvoidactionPerformed(ActionEventae)
20.{
21.if(ae.getSource()==b1)
22.System.out.println(“ButtonPushed”);
23.else
24.System.out.println(“ButtonClicked”);
25.}
26.}
Output:SameasPreviousExample.
Example18.3:
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classA3implementsActionListener
4.{
5.Buttonb1=null,b2=null;
6.A3()
7.{
8.Framef=newFrame();
9.f.setLayout(newFlowLayout());
10.f.setSize(500,100);
11.b1=newButton(“Pushme”);
12.b2=newButton(“Clickme”);
13.b1.addActionListener(this);
14.b2.addActionListener(this);
15.f.add(b1);
16.f.add(b2);
17.f.setVisible(true);
18.}
19.publicstaticvoidmain(Stringargs[])
20.{
21.newA3();
22.}
23.publicvoidactionPerformed(ActionEventae)
24.{
25.if(ae.getSource()==b1)
26.System.out.println(“ButtonPushed”);
27.else
28.System.out.println(“ButtonClicked”);
29.}
30.}
Output:SameasPreviousExample.
Example18.4
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classA4implementsActionListener
4.{
5.staticButtonb1=null,b2=null;
6.staticTextFieldtf1=null,tf2=null,tf3=null;
7.publicstaticvoidmain(Stringargs[])
8.{
9.Framef=newFrame();
10.f.setLayout(newGridLayout(4,2));
11.f.setSize(500,300);
12.Labell1=newLabel(“No1.”);
13.Labell2=newLabel(“No2.”);
14.Labell3=newLabel(“Result”);
15.tf1=newTextField();
16.tf2=newTextField();
17.tf3=newTextField();
18.b1=newButton(“Sum”);
19.b2=newButton(“Avg”);
20.b1.addActionListener(newA4());
21.b2.addActionListener(newA4());
22.f.add(l1);f.add(tf1);
23.f.add(l2);f.add(tf2);
24.f.add(l3);f.add(tf3);
25.f.add(b1);f.add(b2);
26.f.setVisible(true);
27.}
28.publicvoidactionPerformed(ActionEventae)
29.{
30.inta,b,c;
31.floatav;
32.a=Integer.parseInt(tf1.getText());
33.b=Integer.parseInt(tf2.getText());
34.if(ae.getSource()==b1)
35.tf3.setText(””+(a+b));
36.else
37.tf3.setText(””+(a+b)/2.0f);
38.}}
Output:
Note:acomponentmayhavemultiplelistenersassociatedwithit.thereisnoguarantee
thatlistenerswillbenotifiedintheorderinwhichtheywereadded.
Thereisalsonoguaranteethatalllistenernotificationwilloccurinthesamethread,
thus,listenersmusttakeprecautionsagainstcorruptingshareddata.
Aneventlistenermayberemovedfromacomponent’slistoflistenersbycalling
removeXXXListener()method,passinginthelistenertoberemoved.
Forexample,codebelowremovesactionlisteneralfrombuttonbtn:
btn.removeActionListener(al);
Handlingwindowevents
Example18.5:
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classA5
4.{
5.publicstaticvoidmain(Stringargs[])
6.{
7.Framef=newFrame();
8.f.setLayout(newFlowLayout());
9.f.setSize(300,300);
10.f.addWindowListener(newB());
11.f.setVisible(true);
12.}
13.}
14.classBimplementsWindowListener
15.{
16.publicvoidwindowOpened(WindowEventwe)
17.{
18.System.out.println(“WindowOpened”);
19.}
20.publicvoidwindowActivated(WindowEventwe)
21.{
22.System.out.println(“WindowActivated”);
23.}
24.publicvoidwindowDeactivated(WindowEventwe)
25.{
26.System.out.println(“windowDeactivated”);
27.}
28.publicvoidwindowClosing(WindowEventwe)
29.{
30.System.out.println(“WindowClosing”);
31.Framef=(Frame)we.getWindow();
32.f.dispose();
33.}
34.publicvoidwindowClosed(WindowEventwe)
35.{
36.System.out.println(“WindowClosed”);
37.}
38.publicvoidwindowIconified(WindowEventwe)
39.{
40.System.out.println(“WindowIconified”);
41.}
42.publicvoidwindowDeiconified(WindowEventwe)
43.{
44.System.out.println(“WindowDeiconified”);
45.}
46.}
Adapters:
Some of the event listener interfaces have several methods. The largest interface,
WindowListenerhassevenmethods.SupposewewanttocatchwindowClosing()event,
sothatthecodeforclosingwindowcanbeexecuted.Althoughweneedonlyonemethod
window Closing ( ) in the class implementing Window Listener but we will have to
providedummyimplementationforallthemethods.
The java.awt.event package provides several adapter classes, one for each listener
interfacethatdefinesmorethanjustasinglemethod.
An adapter is simply a class that implements an interface by providing do nothing
methods. For example, the Window Adapter class implements the Window Listener
interfacewithsevendo-nothingmethods.
AdapterclassesandTheirInterfaces:
AdapterClassListenerInterfaces
ContainerAdapterContainerListener
FocusAdapterFocusListener
KeyAdapterKeyListener
MouseAdapterMouseListener
MouseMotionAdapterMouseMotionListener
WindowAdapterWindowListener
Example18.6UseoftheWindowAdapterClass.
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classA6
4.{
5.publicstaticvoidmain(Stringargs[])
6.{
7.Framef=newFrame();
8.f.setLayout(newFlowLayout());
9.f.setSize(300,300);
10.f.addWindowListener(newB());
11.f.setVisible(true);
12.}
13.}
14.classBextendsWindowAdapter
15.{
16.publicvoidwindowClosing(WindowEventwe)
17.{
18.System.out.printIn(“WindowClosing”);
19.Framef=(Frame)we.getWindow();
20.f.dispose();
21.}
22.}
TheInputEventclass:
This is the root event class for all component level input events. Input events are
delivered to listeners before they are processed normally by the source where they
originated. This allows listeners and component subsclasses to “consume” the event so
that the source will not process them in their default manner. For example, consuming
mouse pressed events on a Button component will prevent the Button from being
activated.
Methods:
voidconsume()
Consumes this event so that it will not be processed in the default
mannerbythesourcethatoriginatedit.
intgetModifiers()
ReturnstheModifiermaskforthisevent.
intgetModifiersEx()
Returnstheextendedmodifiermaskforthisevent.
staticStringgetModifiersExText(intmodifiers)
ReturnsaStringdescribingtheextendedmodifierKeyssuchas“shift”,
“Ctrl+Shift”etc.
longgetWhen()
Returnsatimestampofwhenthiseventoccurred.
booleanisAltDown()
ReturnswhetherornottheAltmodifierisdownonthisevent.
booleanisConsumed()
Returnswhetherornotthiseventhasbeenconsumed.
booleanisControlDown()
ReturnswhetherornottheControlmodifierisdownonthisevent.
booleanisShiftDown()
Returnswhetherornottheshiftmodifierisdownonthisevent.
TheMouseEventClass:
This is sub- class of Input Event class. This event indicates that a mouse action
occurredinacomponent.Amouseactionisconsideredtooccurinaparticularcomponent
ifandonlyifthemousecursorisovertheun-obscuredpartofthecomponent’schildrenor
byamenuorbyatop-levelwidow.
ThiseventisusedbothforMouseevents(click,enter,press,exit,release)andMouse
motionevents(moveanddrag).
Methods:
intgetButton()
Returns which, if any, of the mouse buttons has changed
state.
intgetClickCount()
Returns the number of mouse clicks associated with this
event.
staticStringgetMouseModifiersText(intmodifiers)
ReturnsaStringdescribingthemodifierKeysthatweredown
duringtheevent,suchas“Shift”,or“Ctrl+shift”.
pointgetPoint()
Returns the x, y position of the event relative to the source
component.
intgetX()
Returnsthehorizontalxpositionoftheeventrelativetothe
sourcecomponent.
intgetY()
Returns the vertical y position of the event relative to the
sourcecomponent.
booleanisPopupTrigger()
Returnswhetherornotthismouseeventis thepopupmenu
triggereventfortheplatform.
Note: Popup menus are triggered differently on different systems. Therefore,
isPopupTrigger () should be checked in both mouse Pressed and mouse Released for
propercross-platformfunctionality.
HandlingMouseEvents:
Example18.7
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classA7
4.{
5.publicstaticvoidmain(Stringargs[])
6.{
7.Framef=newFrame();
8.f.setLayout(newFlowLayout());
9.f.setSize(300,300);
10.Buttonb1=newButton(“PushMe”);
11.b1.addMouseListener(newB());
12.b1.addMouseMotionListener(newC());
13.b1.addActionListener(newD());
14.f.add(b1);
15.f.setVisible(true);
16.}
17.}
18.classBimplementsMouseListener
19.{
20.publicvoidmouseEntered(MouseEventme)
21.{
22.System.out.println(“MouseEntered…”);
23.System.out.println(me.getX());
24.System.out.println(me.getY());
25.}
26.publicvoidmouseExited(MouseEventme)
27.{
28.System.out.println(“MouseExited…”);
29.Pointp1=me.getPoint();
30.System.out.println(p1.x);
31.System.out.println(p1.y);
32.}
33.publicvoidmousePressed(MouseEventme)
34.{
35.System.out.println(“Mousepressed…”);
36.intms=me.getModifiersEx();
37.Strings=me.getModifiersExText(ms);
38.System.out.println(s);
39.}
40.publicvoidmouseReleased(MouseEventme)
41.{
42.System.out.println(“MouseReleased…”);
43.System.out.println(“ClickCount—>”+me.getClickCount());
44.}
45.publicvoidmouseClicked(MouseEventme)
46.{
47.System.out.println(“MouseClicked…”);
48.System.out.println(“Button—>”+me.getButton());
49.}
50.}
51.classCimplementsMouseMotionListener
52.{
53.publicvoidmouseMoved(MouseEventme)
54.{
55.System.out.println(“MouseMoved…”);
56.}
57.publicvoidmouseDragged(MouseEventme)
58.{
59.System.out.println(“MouseDragged…”);
60.}
61.}
62.classDimplementsActionListener
63.{
64.publicvoidactionPerformed(ActionEventae)
65.{
66.System.out.println(“ButtonPressed…”);
67.}}
TheActionEventClass:
Itis a semanticevent, which indicatesthat a component– defined actionoccurred.
This high level event is generated by a component (such as a Button) when the
component-specificactionoccurs(Suchasbeingpressed).Theeventispassedtoevery
Action Listener object that registered to receive such events usingthe component’s add
actionListenermethod.
TheobjectthatimplementstheActionListenerinterfacegetsthisActionEventwhen
the event occurs. The listener is therefore spared the details of processing individual
mousemovementsandmouseclicks,andcaninsteadprocessa“meaningful”(semantic)
eventlike“buttonpressed”.
Note:ToinvokeanActionEventonaButtonusingtheKeyboard,usethespacebar.
Methods:
StringgetAction(Command)
Returnsthecommandstringassociatedwiththisaction.
intgetModifiers()
ReturnsthemodifierKeyshelddownduringthisactionevent.
longgetWhen()
Returnsthetimestampofwhenthiseventoccurred.
Example18.8:
ThisexampleillustrateshowwecanidentifythekeymodifierseffectivewhenandAction
Eventoccurs.
1.importjava.awt.*;
2.importjava.awt.event*;
3.publicclassKeyModifierDemoextendsFrameimplementsActionListener
4.{
5.Buttonb;
6.KeyModifierDemo()
7.{
8.b=newButton(“Button”);
9.b.addActionListener(this);
10.setLayout(newFlowLayout());
11.add(b);
12.setBounds(100,100,200,200);
13.setVisible(true);
14.}
15.publicstaticvoidmain(Stringargs[])
16.{
17.newKeyModifierDemo();
18.}
19.publicvoidactionPerformed(ActionEventae)
20.{
21.System.out.println(“ButtonPressed”);
22.intms=ae.getModifiers();
23.if(ms&InputEvent.CTRL_DOWN_MASK)!=0)
24.{
25.System.out.println(“CTRLkeywaspressed”);
26.}
27.if(ms&InputEvent.SHIFT_DOWN_MASK)!=0)
28.{
29.System.out.println(“ShiftKeywaspressed”);
30.}
31.if(ms&InputEvent.ALT_DOWN_MASK)!=0)
32.{
33.System.out.println(“ALTkeywaspressed”);
34.}
35.}
36.}
HandlingMultipleActionCommands:
Action events are the simplest. When we find out that a scroll bar has sent an
adjustmentevent,theobviousquestionis,“Nowwhatisthescrollbar’svalue?”.Whenwe
findoutthatthemousehasbeenclicked,itisnaturaltowonder,“Whatarethemouse’sx
andycoordinates?” Butwhenwe findoutthatabuttonhassent anActionevent, there
doesnotseemtobeanyadditionalinformationtoseek;thebuttonhasbeenclicked,and
thatseemstobeallthereistoKnow.
However,thereisanextrapieceofinformationassociatedwithanActionevent.This
information is a string, know as an Action command. We can extract an Action event’s
ActioncommandwiththegetActionCommand()method.IfanActioneventwassentbya
textfield,getActionCommand()returnsthecurrentcontentsofthetextfield.(Atextfield
sendsanActioneventwhentheusertypestheEnterKey.).IfanActioneventwassentby
abutton,thedefaultbehaviorisforgetActionCommand()toreturnthestringthatisthe
button’slabel.However,we can explicitlyset a button’sActionCommand bycalling its
setActionCommand(String)method.
Buttonbtn=newButton(“Hello”);
btn.setActionCommand(“Hello”);
The benefit of Action commands for buttons is apparent when a button’s Action
listenerneedstodecidehowtoreacttoanActionevent.Itiscommonforasinglelistener
to act as a listener for several components ; in our context, a single object might be an
Actionlistenerforseveralormanybutton.Inthissituation,theobject’sactionPerformed(
) method must being by determining which button was hit .The following example,
demonstratesthis:
Example18.9:
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classButtonRefTest
4.{
5.Buttonb1,b2,b3;
6.ButtonRefTest()
7.{
8.Framef=newFrame();
9.f.setLayout(newFlowLayout());
10.f.setSize(300,300);
11.b1=newButton(“PushMe”);
12.b2=newButton(“ClickMe”);
13.b3=newButton(“HitMe”);
14.f.add(b1);f.add(b2);f.add(b3);
15.Bobj=newB(b1,b2,b3);
16.b1.addActionListener(obj);
17.b2.addActionListener(obj);
18.b3.addActionListener(obj);
19.f.setVisible(true);
20.}
21.publicstaticvoidmain(Stringargs[])
22.{
23.newButtonRefTest();
24.}
25.}
26.classBimplementsActionListener
27.{
28.Buttonb4,b5,b6;
29.B(Buttonb1,Buttonb2,Buttonb3)
30.{
31.b4=b1;
32.b5=b2;
33.b6=b3;
34.}
35.publicvoidactionPerformed(ActionEventae)
36.{
37.Buttonb=(Button)ae.getSource();
38.if(b==b4)
39.System.out.println(“FirstButtonwaspressed”);
40.elseif(b==b5)
41.System.out.println(“SecondButtonwaspressed”);
42.elseif(b==b6)
43.System.out.println(“ThirdButtonwaspressed”);
44.}
45.}
Example18.10:
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classGetLabelTest
4.{
5.Buttonb1,b2,b3;
6.GetLabelTest()
7.{
8.Framef=newFrame();
9.f.setLayout(newFlowLayout());
10.f.setSize(300,300);
11.b1=newButton(“PushMe”);
12.b2=newButton(“ClickMe”);
13.b3=newButton(“HitMe”);
14.f.add(b1);f.add(b2);f.add(b3);
15.Bobj=newB();
16.b1.addActionListener(obj);
17.b2.addActionListener(obj);
18.b3.addActionListener(obj);
19.f.setVisible(true);
20.}
21.publicstaticvoidmain(Stringargs[])
22.{
23.newGetLabelTest();
24.}
25.}
26.classBimplementsActionListener
27.{
28.publicvoidactionPerformed(ActionEventae)
29.{
30.Buttonb=(Button)ae.getSource();
31.Strings=b.getLabel();
32.if(s.equals(“PushMe”))
33.System.out.println(“FirstPushMeButtonwaspressed”);
34.elseif(s.equals(“ClickMe”))
35.System.out.println(“SecondPushMeButtonwaspressed”);
36.elseif(s.equals(“HitMe”))
37.System.out.println(“ThirdPushMeButtonwaspressed”);
38.}
39.}
Example18.11:UsingsetActionCommand()methodtosettheActionCommand.
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classActionCommandTest
4.{
5.Buttonb1,b2,b3;
6.ActionCommandTest()
7.{
8.Framef=newFrame();
9.f.setLayout(newFlowLayout());
10.f.setSize(300,300);
11.b1=newButton(“PushMe”);
12.b2=newButton(“PushMe”);
13.b3=newButton(“PushMe”);
14.b1.setActionCommand(“First”);
15.b2.setActionCommand(“Second”);
16.b3.setActionCommand(“Third”);
17.f.add(b1);f.add(b2);f.add(b3);
18.Bobj=newB();
19.b1.addActionListener(obj);
20.b2.addActionListener(obj);
21.b3.addActionListener(obj);
22.f.setVisible(true);
23.}
24.publicstaticvoidmain(Stringargs[])
25.{
26.newActionCommandTest();
27.}
28.}
29.classBimplementsActionListener
30.{
31.publicvoidactionPerformed(ActionEventae)
32.{
33.Buttonb=(Button)ae.getSource();
34.Strings=b.getActionCommand();
35.if(s.equals(“First”))
36.System.out.println(“FirstPushMeButtonwaspressed”);
37.elseif(s.equals(“Second”))
38.System.out.println(“SecondPushMeButtonwaspressed”);
39.elseif(s.equals(“Third”))
40.System.out.println(“ThirdPushMeButtonwaspressed”);
41.}
42.}
HandlingKeyEvents
Example18.12:
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classKeyTestextendsFrameimplementsKeyListener
4.{
5.Stringmsg=””;
6.intx=50,y=100;
7.publicstaticvoidmain(Stringarg[])
8.{
9.Framef=newKeyTest();
10.f.setSize(300,300);
11.f.addKeyListener((KeyTest)f);
12.f.setVisible(true);
13.}
14.publicvoidkeyReleased(KeyEventke)
15.{
16.System.out.println(“KeyUp…”);
17.}
18.publicvoidkeyTyped(KeyEventke)
19.{
20.System.out.println(“KeyTyped…”);
21.msg=msg+ke.getKeyChar();
22.repaint();
23.}
24.publicvoidkeyPressed(KeyEventke)
25.{
26.System.out.println(“KeyPressed…”);
27.intkey=ke.getKeyCode();
28.switch(key)
29.{
30.caseKeyEvent.VK_F1:
31.msg=msg+“<F1>”;break;
32.caseKeyEvent.VK_F2:
33.msg=msg+“<F2>”;break;
34.caseKeyEvent.VK_F3:
35.msg=msg+“<F3>”;break;
36.caseKeyEvent.VK_PAGE_DOWN:
37.msg=msg+“<PgDn>”;break;
38.caseKeyEvent.VK_PAGE_UP:
39.msg=msg+“<PgUp>”;break;
40.caseKeyEvent.VK_LEFT:
41.msg=msg+“<LeftArrow>”;break;
42.caseKeyEvent.VK_RIGHT:
43.msg=msg+“<RightArrow>”;break;
44.caseKeyEvent.VK_CONTROL:
45.msg=msg+“<Ctrl>”;break;
46.}
47.repaint();
48.}
49.publicvoidpaint(Graphicsg)
50.{
51.g.setColor(Color.red);
52.g.drawString(msg,x,y);
53.}
54.}
Example18.13:DemonstrationofFocusListenerColorofTextFieldchangesonfocus
lostorgained
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classFocusTestextendsFrameimplementsFocusListener
4.{
5.staticTextFieldtf1,tf2;
6.publicstaticvoidmain(Stringargs[])
7.{
8.FocusTestf=newFocusTest();
9.f.setLayout(newFlowLayout());
10.tf1=newTextField(8);
11.tf1.setBackground(Color.blue);
12.tf1.addFocusListener(f);
13.tf2=newTextField(8);
14.tf2.setBackground(Color.blue);
15.tf2.addFocusListener(f);
16.f.add(tf1);
17.f.add(tf2);
18.f.setSize(200,200);
19.f.setVisible(true);
20.}
21.publicvoidfocusGained(FocusEventfe)
22.{
23.TextFieldtf=(TextField)fe.getSource();
24.tf.setBackground(Color.red);
25.}
26.publicvoidfocusLost(FocusEventfe)
27.{
28.TextFieldtf=(TextField)fe.getSource();
29.tf.setBackground(Color.blue);
30.}
31.}
Example18.14:DemonstrationofrequestFocus()Wecan’tuseWindowListenerinsame
classsowedefinedtwoclassesoneforframe&anotherforWindowListener.
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classAextendsFrameimplementsActionListener
4.{
5.staticTextFieldtf1,tf2;
6.staticButtonb1;
7.publicstaticvoidmain(Stringargs[])
8.{
9.Af=newA();
10.f.setLayout(newFlowLayout());
11.f.addWindowListener(newB());
12.tf1=newTextField(8);
13.tf2=newTextField(8);
14.b1=newButton(“Set”);
15.b1.addActionListener(f);
16.f.add(tf1);
17.f.add(tf2);
18.f.add(b1);
19.f.setSize(200,200);
20.f.setVisible(true);
21.}
22.publicvoidactionPerformed(ActionEventae)
23.{
24.tf2.requestFocus();
25.}
26.}
27.classBextendsWindowAdapter
28.{
29.publicvoidwindowClosing(WindowEventwe)
30.{
31.Framef=(Frame)we.getWindow();
32.f.dispose();
33.}
34.}
Example18.15Displayingadialogbox
1.importjava.awt.*;
2.classDialogTest
3.{
4.publicstaticvoidmain(Stringargs[])throwsInterruptedException
5.{
6.Framef1=newFrame();
7.f1.setSize(300,300);
8.f1.setVisible(true);
9.Dialogd1=newDialog(f1);
10.d1.setSize(100,100);
11.d1.setVisible(true);
12.Thread.sleep(3000);
13.d1.dispose();
14.}
15.}
Example18.16DemonstrationofMenuBar
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classMyMenuextendsFrameimplementsActionListener,WindowListener,
ItemListener
4.{
5.TextFieldtf1;
6.Stringmsg=””;
7.CheckboxMenuItemitem4;
8.MyMenu()
9.{
10.super(“Matrix”);
11.setLayout(newFowLayout());
12.tf1=newTextField(8);
13.add(tf1);
14.MenuBarmbar=newMenuBar();
15.Menufile=newMenu(“File”);
16.MenuItemitem1=newMenuItem(“New…”);
17.item1.addActionListener(this);
18.file.add(item1);
19.MenuItemitem2=newMenuItem(“Open…”);
20.item2.addActionListener(this);
21.file.add(item2);
22.Menusub=newMenu(“SubMenu”);
23.MenuItemitem3=newMenuItem(“Option1”);
24.sub.add(item3);
25.file.add(sub);
26.item4=newCheckboxMenuItem(“TextBox”,true);
27.item4.addItemListener(this);
28.file.add(item4);
29.mbar.add(file);
30.addWindowListener(this);
31.setMenuBar(mbar);
32.setSize(400,400);
33.setVisible(true);
34.}
35.publicvoidpaint(Graphicsg)
36.{
37.g.drawString(msg,150,250);
38.}
39.publicvoidactionPerformed(ActionEventae)
40.{
41.Strings1=(String)ae.getActionCommand();
42.if(s1.equals(“New…”))
43.{
44.tf1.setText(“NewSelected”);
45.msg=“NewSelected”;
46.}
47.elseif(s1.equals(“Open…”))
48.{
49.tf1.setText(“OpenSelected”);
50.msg=“OpenSelected”;
51.}
52.repaint();
53.}
54.publicvoidwindowClosing(WindowEventwe)
55.{
56.Framef=(Frame)we.getWindow();
57.f.dispose();
58.}
59.publicvoidwindowClosed(WindowEventwe){}
60.publicvoidwindowActivated(WindowEventwe){}
61.publicvoidwindowDeactivated(WindowEventwe){}
62.publicvoidwindowIconified(WindowEventwe){}
63.publicvoidwindowDeiconified(WindowEventwe){}
64.publicvoidwindowOpened(WindowEventwe){}
65.publicvoiditemStateChanged(ItemEventie)
66.{
67.tf1.setVisible(item4.getState());
68.}
69.publicstaticvoidmain(Stringargs[])
70.{
71.newMyMenu();
72.}
73.}
Example18.17DemonstrationofListbox
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classListTestextendsFrameimplementsActionListener
4.{
5.staticListl1,l2;
6.publicstaticvoidmain(Stringargs[])
7.{
8.ListTestf=newListTest();
9.f.setLayout(newFlowLayout());
10.l1=newList(3,true);
11.l1.add(“India”);
12.l1.add(“Pakistan”);
13.l1.add(“USA”);
14.l1.add(“UK”);
15.l1.add(“China”);
16.l2=newList(3,true);
17.Buttonb1=newButton(“Transfer”);
18.b1.addActionListener(f);
19.f.add(l1);
20.f.add(l2);
21.f.add(b1);
22.f.setSize(200,200);
23.f.setVisible(true);
24.}
25.publicvoidactionPerformed(ActionEventae)
26.{
27./*for(inti=l1.getItemCount()-1;i>=0;i—)
28.{
29.l2.add(l1.getItem(i));
30.l1.remove(i);
31.}
32.*/
33.Strings1[]=l1.getSelectedItems();
34.for(inti=0;i<s1.length;i++)
35.{
36.l2.add(s1[i]);
37.l1.remove(s1[i]);
38.}
39.}
40.}
Example18.18Sumoftwonumbersusingframe
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classSumimplementsActionListener
4.{
5.staticButtonb1,b2;
6.staticTextFieldtf1,tf2,tf3;
7.staticFramef;
8.publicstaticvoidmain(Stringargs[])
9.{
10.f=newFrame();
11.Sums1=newSum();
12.f.setLayout(newGridLayout(4,2));
13.Labell1=newLabel(“EnterNo.1:”);
14.tf1=newTextField(8);
15.Labell2=newLabel(“EnterNo.2:”);
16.tf2=newTextField(8);
17.Labell3=newLabel(“Result:”);
18.tf3=newTextField(8);
19.b1=newButton(“Sum”);
20.b2=newButton(“Close”);
21.b1.addActionListener(s1);
22.b2.addActionListener(s1);
23.f.add(l1);
24.f.add(tf1);
25.f.add(l2);
26.f.add(tf2);
27.f.add(l3);
28.f.add(tf3);
29.f.add(b1);
30.f.add(b2);
31.f.setSize(200,200);
32.f.setVisible(true);
33.}
34.publicvoidactionPerformed(ActionEventae)
35.{
36.Buttonb=(Button)ae.getSource();
37.if(b==b1)
38.{
39.intn1=Integer.parseInt(tf1.getText());
40.intn2=Integer.parseInt(tf2.getText());
41.tf3.setText(String.valueOf(n1+n2));
42.}
43.if(b==b2)
44.{
45.f.dispose();
46.}
47.}
48.}
Example18.19DisplayinganimageonApplet
1.importjava.awt.*;
2.importjava.net.*;
3.importjava.applet.*;
4./*<Appletcode=“ScrollPane1”width=200height=200></applet>*/
5.publicclassScrollPane1extendsApplet
6.{
7.Imageimg1;
8.URLfile1;
9.publicvoidinit()
10.{
11.try
12.{
13.file1=newURL(“FILE:///c:/javaprg/a.jpg”);
14.}
15.catch(MalformedURLExceptione)
16.{
17.System.out.print(e);
18.}
19.img1=getImage(file1);
20.}
21.publicvoidpaint(Graphicsg)
22.{
23.g.drawImage(img1,0,0,this);
24.}
25.}
Example18.20Demonstrationofmovingcircle
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classCircle1extendsFrameimplementsMouseListener,Runnable
4.{
5.intx,y,w,h;
6.staticCircle1f;
7.publicvoidrun()
8.{
9.y=50;
10.w=50;
11.h=50;
12.for(x=0;x<500;x+=10)
13.{
14.try
15.{
16.Thread.sleep(500);
17.}
18.catch(InterruptedExceptione)
19.{
20.System.out.println(e);
21.}
22.repaint();
23.}
24.}
25.publicstaticvoidmain(Stringargs[])
26.{
27.f=newCircle1();
28.Threadt=newThread(f);
29.t.start();
30.f.addMouseListener(f);
31.f.setSize(500,500);
32.f.setVisible(true);
33.}
34.publicvoidpaint(Graphicsg)
35.{
36.g.setColor(Color.RED);
37.g.drawOval(x,y,w,h);
38.g.setColor(Color.BLUE);
39.g.fillOval(x+1,y+1,w-1,h-1);
40.}
41.publicvoidmousePressed(MouseEventme)
42.{
43.x=me.getX();
44.y=me.getY();
45.w=50;
46.h=50;
47.Graphicsg=f.getGraphics();
48.g.clearRect(0,0,200,200);
49.paint(g);
50.}
51.publicvoidmouseReleased(MouseEventme){}
52.publicvoidmouseClicked(MouseEventme){}
53.publicvoidmouseEntered(MouseEventme){}
54.publicvoidmouseExited(MouseEventme){}
55.}
CHAPTER
∞19∞
(PaintinginAWT)
Introduction-
ManytypesofAWTcomponents(buttonsandscrollbars,forexample)havetheir
appearance dictated by the underlying window system. Other component types notably
applets,frames,panelsandcanvaseshavenointrinsicappearance.Ifweuseanyofthese
classesotherthansimplyascontainersandwantourcomponenttolookatalluseful,we
willhavetoprovidethecodethatimplementsthecomponentsappearance.
Everycomponenthasagraphicscontextassociatedwithit.Thegraphicscontext
correspondencetotheframebufferrelatedtothecomponent.
We can draw on the component using methods supported by the Graphics
Context.AnythingdrawnontheGraphicscontextappearsonthecomponent.
The correct approach for painting on any component is to override its paint( )
methodandprovidetheappropriatecode.
The paint( ) method has one argument of type Graphics, which represents the
GraphicsContextofthecomponent.Itisalsopossibletodrawonthecomponentwithout
usingpaint()methodalthoughthisapproachisnotrecommended.
Thepaint()methodandtheGraphicsContext:
Oneinterestingpointabouttheframeinthefollowingexampleisthatnoexplicit
callsmadetothepaint()method;themethodissimplyprovided.Theenvironmentseems
todoagoodjobofcallingpaint()attherightmoment.
PaintingonacomponentisaccomplishedbymakingcallstoaGraphicscontext,which
isaninstanceoftheGraphicsclass.Agraphicscontextknowshowtorenderontoasingle
target.ThethreemediaaGraphicsContextcanrenderontoare:
1. Components.
2. Images.
3. Printers.
Any Kind of component can be associated with a Graphics context. The
associationispermanent;acontextcannotbereassignedtoanewcomponent.Although
wecanusegraphicscontextstopaintontoanykindofcomponent,itisunusualtodoso
withcomponentsthatalreadyhaveanappearance.
Buttons,Choices, Checkboxes,Labels,Scrollbars, TextFields,andTextAreasdo
notoftenrequireprogrammerlevelrendering.Mostoften,thesecomponentsjustusethe
versionofpaint()thattheyinheritfromthecomponentsuperclass.
This version does nothing; the components are rendered by the underlying
window system. However, there are four classes of “blank” components that have no
defaultappearanceandwillshowupasemptyrectangles,unlesstheyaresub-classedand
givenpaint()methods.
Thesefourcomponentclassesare:
Applet.
Canvas.
Frame.
Panel.
Example19.1 The Frame Class is extended and paint() methods is over-ridden to
changetheappearanceoftheframe.
1.importjava.awt.*;
2.publicclassSimplePaintextendsFrame
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newSimplePaint();
7.f.setSize(200,200);
8.f.setVisible(true);
9.}
10.publicvoidpaint(Graphicsg)
11.{
12.g.setColor(Color.white);
13.g.fillRect(0,0,300,300);
14.g.setColor(Color.grey);
15.g.fillOval(30,30,50,50);
16.}
17.}
Output:
When we subclass a component class and give the sub class its own paint()
method,theenvironmentcallsthatmethodatappropriatetimes,passinginanappropriate
instanceofGraphics.
Operationssupportedbythegraphicsclass
Thefourmajorcategoriesofoperationsprovidedbythegraphicsclass(graphics
context)are:
Selectingacolor.
Selectingafont.
Drawingandfilling.
Clipping.
Selectingacolor:
Colors are selected by calling the setcolor()method. The required argument is an
instanceofthecolorclass.
There are 13 pre-defined colors, accessible as static final variables of the color
class.
(The variables are themselves instance of the color class. Which makes some
peopleuneasy,butjavahasnotroublewithsuchthings.)Thepre-definedcolorsare:
1. Color.black
2. Color.blue
3. Color.cyan
4. Color.darkGray
5. Color.gray
6. Color.green
7. Color.lightGray
8. Color.magenta
9. Color.orange
10. Color.pink
11. Color.red
12. Color.white
13. Color.yellow
If we want a color that is not on this list, we can construct our own. There are several
versionofthecolorconstructor,thesimplestis:
Color(intredLevel,intgreenLevel,intblueLevel)
Thethreeparametersareintensitylevelonascaleof0to255,fortheprimarycolors.
Thecolorsareadditive,whichmeanstheymixlikelight,notlikepaint.
newColor(0,0,0)black(absenceoflight)
newColor(255,0,0)red(onlyredhueisincluded)
newColor(255,255,255)white(allcolorsshiningatonce)
Codefragmentbelowliststhefirstpartofapaint()methodthatsetsthecolorofits
graphicscontexttopalegreen:
publicvoidpaint(Graphicsg)
{
Colorc=newColor(170,255,170);
g.setColor(c);
}
After call to setColor() in the above code all graphics will be painted in pale
(light)green, until the next g.setColor() call. Calling g.setColor(0 does not change the
colorofanythingthathasalreadybeendrawn;itonlyaffectsubsequentoperations.
SelectingaFont:
Settingthefont ofagraphicscontextislikesettingthe colorsubsequentstring
drawingoperationswillusethenewfont,whilepreviouslydrawnstringsarenotaffected.
Beforewecansetafont,wehavetocreateone.Theconstructorforthefontclasslooks
likethis:
Font(stringfontName,intstyle,intsize)
The first parameter is the name of the font. Font availability is platform
dependent.Wecangetalistofavailablefontnames,returnedasanarrayofstrings,by
callingthegetFontList()methodonourtoolkitlikethis:
StringfontNames[]=Toolkit.getDefaultToolkit().getFontList();
Therearethreefontnamesthatareplatformindependentandthatweareencouragedto
use:
1. “Serif”
2. “Sansserif”
3. “Monospaced”
On 1.0.X releases of the JDK these were called, respectively
“TimesRoman”,”Helvetica”and“Courier”.
Thestyleparametercanbesenttoanyofthefollowingintconstant:
1. Font.PLAIN
2. Font.BOLD
3. Font.ITALIC
Thecodefragmentbelowsetsthefontsofgraphicscontextgcto24pointboldsansserif:
Fontf=newFont(“SansSerif”,Font.BOLD,24);
gc.setFont(f);
Wecanspecifycombinationsofstyles,forexampleabolditalicfont,bypassingthesum
ifstyles,likethis:
Font.BOLD+Font.ITALIC
Drawingandfilling:
All the rendering methods of graphics class specify pixel co-ordinate positions
fortheshapestheyrendereverycomponenthasitswonco-ordinatespace,withtheorigin
inthecomponent’supper-leftcorner,xincreasingtotherightandyincreasingdownward.
Followingfigureshowsthecomponentco-ordinatesystem:
Thegraphics contextclass doesnothave anextensive setof paintingmethods.
(SophisticatedrenderingishandledbyextendedAPIssuchas2d,3d,andanimation.)
Themethodsinthegraphiccontextclassthatweneedtoknowaboutare:
voiddrawLine(intx1,inty1,intx2,inty2)
Drawsa line,usingthe currentcolor, betweenthe points (x1,y1)and (x2,y2) in this
graphicscontext’scoordinatesystem.
voiddrawRect(intx,inty,intwidth,intheight)
Drawstheoutlineofthespecifiedrectangle.
voidfillRect(intx,inty,intwidth,intheight)
Fillsthespecifiedrectangle.
voiddrawOval(intx,inty,intwidth,intheight)
Drawstheoutlineofanovalboundedbyhespecifiedrectangle.
voidfillOval(intx,inty,intwidth,intheight)
Fillsanovalboundedbythespecifiedrectanglewiththecurrentcolor.
Anovalisspecifiedbyarectangularboundingbox.Theovalliesinsidethebounding
boxandistangenttoeachofthebox’ssidesatthemid-pointasshownbelow:
To draw a circle, use a square-bounding box. Note that the painting only draws
foregroundpixels,notbackground,sothespaceinsidetheboundingboxbutoutsidethe
ovalisleftunchanged.Herexandyaretheco-ordinatesoftheupperleftcornerofthe
boundingbox,andwidthandheightarethewidthandheightofthebox.
voiddrawArc(intx,inty,intwidth,intheight,intstartAngle,intarcAngle)
Drawtheoutlineofacircularorellipticalarccoveringthespecifiedrectangle.
voidfillArc(intx,inty,intwidth,intheight,intstartangle,intarcangle)
Fillsacircularorellipticalarccoveringthespecifiedrectangle.
Anarcissegmentofanoval.Thespecifyanarc,wefirstspecifytheoval’sbounding
box,justaswedowithdrawOval()andfillOval().Wealsoneedtospecifythestarting
andendingpintsofthearc,whichwedonyspecifyinganstartingangleandtheangle
sweptoutbythearc.
Afilledarcisregionboundedbythearcitselfandthetworadiifromthecenterofthe
ovaltotheendpointsofthearc.
voiddrawPolygon(int[]xPoints,int[]yPointsintnPoints)
Drawsaclosedpolygondefinedbyarraysofxandycoordinates.
voidfillPolygon(int[]xPoints,int[]yPoints,intnPoints)
Fillsaclosedpolygondefinedbyarraysofxandycoordinates.
A polygon is a closed figure with an arbitrary number of vertices. The vertices are
passedtothedrawPolygon()andfillPolygon()methodsastwointarrays.Thefirstarray
containsthexco-ordinatesofthevertices,thesecondarraycontainstheyco-ordinates.
Athirdparameterspecifiesthenumberofvertices.
Note:endpointisjoinedwiththefirstpoint.
voiddrawPolyLine(int[]xPoints,int[]yPoints,intnPoints)
Drawsasequenceofconnectedlinesdefinedbyarrayofxandycoordinates.
Apolylineis similarto apolygon ,but itis openrather thatclosed. Thereis noline
segmentconnectingthelastvertextothefirst.
voiddrawString(Stringstr,intx,inty)
Drawsthetextgivenbythespecifiedstring,usingthisgraphicscontext’scurrentfont
andcolor.Thex,yparametersspecifytheleftedgeofthebaselineofthestring.The
characterswithdescenders(g.j,p,q,andyinmostfonts)extendbelowthebaseline.
Thefactthattext-coordinatesarerelativetothebaselineisimportant.Inasimpletext,
forexample,wemighttrytodrawastringat(0,0)expectingittoappearatthetopleft
ofthespace.However,becauseofthebaseline,wewillonlyseethedescendersofthe
string,whichmightmeanthatweseenothingatall.
Bydefault,agraphicscontextusesthefontoftheassociatedcomponenthowever,we
cansetadifferentfontbycallingthegraphicscontext’ssetFont()method.
booleandrawImage(Imageimg,intx,inty,ImageObserverobserver)
Drawsasmuchofthespecifiedimageasiscurrentlyavailable.
Here, im is the image to be rendered, and x and y are the coordinates within the
destinationcomponentoftheupper-leftcorneroftheimage.Theimageobservermust
beanobjectthatimplementstheimageobserverinterface.
An image is an off-screen representation of a rectangular collection of pixel values.
Java’simagesupportiscomplicated.
Fornow,assumethatwehavesomehowobtainedanimage(thatis,aninstanceofclass
java.awt,image)thatwewanttorendertothescreenusingacertaingraphicscontext.
Thewaytodothisistocallthegraphicscontext’sdrawImage()method.
Example19.2:
This example illustrates how to create an image and then draw on it using its
graphics context . the image can then be displayed in the applet window using
drawImage()method.
1.importjava.awt.*;
2.importjava.applet.*;
3.importjava.net.URL;
4./*<appletcode=“PaintImage”width=200height=100></applet>*/
5.publicclassPaintImageextendsApplet
6.{
7.privateImageim;
8.publicvoidinit()
9.{
10.im=createImage(100,50);
11.Graphicsimgc=im.getGraphics();
12.imgc.setColor(Color.gray);
13.imgc.fillRect(0,0,100,50);
14.imgc.setColor(Color.black);
15.imgc.fillOval(0,0,50,40);
16.}
17.publicvoidpaint(Graphicsg)
18.{
19.g.drawImage(im,10,10,this);
20.}
21.}
Output:
Example19.3:
Thisexampleillustrateshowtocreateanimageobjectfromanexistingimage.The
imagecanthenbedisplayedintheappletwindowusingdrawimage()method.
1.importjava.awt.*;
2.importjava.applet.*;
3.importjava.net.*;
4./*
5.<appletcode=”PaintImage”width=500height=500>
6.</applet>
7.*/
8.publicclassPaintImage1extendsApplet
9.{
10.privateImageim;
11.publicvoidinit()
12.{
13.try
14.{
15.im=getImage(newURL(“FILE:///c:/matrix/logo.gif”));
16.//im=getImage(newURL(“http://127.0.0.1:8008/logo.gif”));
17.}
18.catch(MalformedURLExpectione)
19.{
20.System.out.println(e);
21.}
22.}
23.publicvoidpaint(Graphicsg)
24.{
25.g.drawImage(im,10,10,this);
26.}
27.}
Clipping:
Mostcallsthatprogrammersmakeongraphicscontextinvolvecolorselectionor
drawingand filling.Aless commonoperation isclipping.Clippingissimply restricting
theregionthatagraphicscontextcanmodify.
Every graphics context that is, every instance of the graphics class has a clip
region,which definesallor partof theassociated component.Whenwe callone ofthe
drawXXX()orfillXXX()methodofthegraphicsclass,onlythosepixelsthatliewithinthe
graphicscontext’sclipregionaremodified.
Thedefaultclipregionfor agraphicscontextisthe entirevisibleregionofthe
associatedcomponent.Therearemethodsthatretrieveandmodifyaclipregion.Consider
thefollowingpaintmethod.
Example19.4:
1.importjava.awt.*;
2.classClipextendsFrame
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newClip();
7.f.setSize(300,330);
8.f.setVisible(true);
9.}
10.publicvoidpaint(Graphicsg)
11.{
12.for(inti=0;i<300;i=i+100)
13.{
14.for(intj=30;j<330;j=j+100)
15.{
16.g.fillOval(i,j,100,100);
17.}
18.}
19.}
20.}
Output:
Thepaint()methodofaboveprogramdrawsadotpattern.Considerwhathappenswhen
this is the paint( ) method of an applet/ frame that is 200 * 200 pixels. Because loop
countersgoallthewayupto500,themethodattemptstodrawoutsidetheboundsofthe
applet/frame.
Thisisnotaproblem,becausethegraphicscontextbydefaulthasaclipregion
thatcoincideswiththeapplet/frameitself.
Tosetaretangularclipregionforagraphicscontext,wecancallthesetClip(x,y,
width, height) method, passing in four ints that describe the position and size of the
desiredcliprectangle.
Forexample,thecodeabovecouldbemodifiedasfollows:
Example19.5:
1.importjava.awt.*;
2.classClip2extendsFrame
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Framef=newClip2();
7.f.setSize(300,330);
8.f.setVisible(true);
9.}
10.publicvoidpaint(Graphicsg)
11.{
12.g.setClip(50,80,200,200);
13.for(inti=0;i<300;i=i+100)
14.{
15.for(intj=30;j<330;j=j+100)
16.{
17.g.fillOval(i,j,100,100);
18.}
19.}
20.g.drawString(“Hello!Kamal”,50,50);
21.g.drawString(“Bye!Kamal”,120,150);
22.}}
Output:
Nowpaintingisclippedtoa200*200rectangleinthecenterofthe300*300
appletframeasshownabove.
ClippingisgoodtoKnowaboutinitsownright.Clippingalsocomesintoplay
whentheenvironmentneedstorepairexposedportionsofacomponent.
Summaryaboutthepaint()methodandthegraphicscontext:
AGraphicscontextisdedicatedtosinglecomponent.ToPaintonacomponent,
wecallthegraphicscontext’sdrawXXXX()andfillXXXX()methods.Tochangethe
colororfontofgraphicsoperations,wecallthegraphicscontext’ssetColor()orsetFont(
)methods,respectively.
GuIThreadandpainting:
TheJavaruntimeenvironmentcreatesandcontrolsitsownthreadsthatoperate
behindthescreanes,andoneofthethreadsisresponsibleforGUImanagement.
TheGUIthreadistheenvironment’stoolforacceptinguserinputeventsandfor
callingthepaint()methodofcomponentsthatneedpainting.
Call to paint ( ) are not all generated by the environment. Java programs can of course
maketheirowncalls,eitherdirectlyorindirectlyviatherepaint()method.
Itisalsopossibletodrawonacomponentusingitsgraphicscontext.Thereisnoneedto
callpaint()orrepaint()methodinthisapproach.
Differentapproachesfordrawingonacomponentareasfollows:
(i)DirectlydrawingafterobtainingGraphicsContextthe
component.
(ii)Spontaneous painting (paint ( ) method is called
implicitly/automaticallybyGUIthread)
(iii)Explicitlyinvokingpaint()method
(iv)Explicitly invoking repaint ( ) method, which then
indirectlyinvokeshepaint()method().
DirectlydrawingafterobtainingGraphicsContextofthecomponent:
Sinceitispossibletogetareferencetoacomponent’sGraphicscontextusingthe
methodgetGraphics(),itistemptingtobelievethatonecansimplydrawtoacomponent
fromanyconvenientmethod.Generallythisapproachisseriouslyflawed.
Supposewehaveanapplet thatwantsto drawa reddotat thepoint ofthemost recent
mouseclick.T
heremainderoftheappletshouldbeyellow.Assumethattheappletishandlingitsown
mouseevents.Wemightconsidercreatinganeventhandlerlikethis:
Example19.6:
1.importjava.awt.*;
2.importjava.awt.event.*;
3.classPaintApproachextendsFrameimplementsMouseListener
4.{
5.publicstaticvoidmain(Stringargs[])
6.{
7.PaintApproachf=newPaintApproach();
8.f.setSize(300,300);
9.f.addMouseListener(f);
10.f.setVisible(true);
11.}
12.publicvoidmouseEntered(MouseEvente){}
13.publicvoidmouseExited(MouseEvente){}
14.publicvoidmousePressed(MouseEvente){}
15.publicvoidmouseReleased(MouseEvente){}
16.publicvoidmouseClicked(MouseEvente)
17.{
18.System.out.println(“MouseClicked…”);
19.Graphicsg=getGraphics();
20.g.setColor(Color.yellow);
21.g.fillRect(0,0,getSize().width,getSize().height);
22.g.setColor(Color.Red);
23.g.fillOval(e.getX()–10,e.getY()–10,20,20);
24.}
25.}
Ifthisappletevergetscoveredandexposed,theGUIthreadwillimplicitlycall
paint ( ), unfortunately, paint ( ) does not Know about the red circle that was drawn in
methodmouseClicked(),sotheredcirclewillnotberepaired.
Theproperplaceforalldrawingoperationsisinpaint(),orinmethodscalled
frompaint();this techniqueensurethattheGUIthread willbeabletorepairexposure
damage.TheGUIthreadexpectspaint()tobeabletocorrectlyreconstructthescreenat
anyarbitrarymoment.
One possible way to achieve this is to remove all drawing code from event
handlersandothearbitrarymethodsandplacethatcodeintothepaint()method.
Next, when a method needs to draw, arrange for it to write to variables that
describethedescribethedesireddrawing,sothatthosevariableareaccessibletothepaint
()methodandcanbeusedbythepaint()methodtoperformthedrawing.
Now when the paint ( ) methods gets called, whether by one of our general
methods,orbytheGUIthread,itcandrawwhateverwasoriginallyintended.
Spontaneous Painting ( paint() method is called implicitly/automatically by GUI
thread):
Spontaneous painting is not an official Java term, but it gets the point across.
Somepaintinghappensbyitself,withnoimpetusbytheprogram.Forexample,asevery
introductory
Javabookexplains,whenabrowserstarts-upanapplet,shortlyaftertheinit()
methodcompletes,callismadetothepaint()method.Also,whenpartorallofabrowser
oraframeiscoveredbyanotherwindowandthenbecomesexposedacallismadetothe
paint()methodsoastorefreshtheappletwindow.
It is the GUI thread that executes these calls to paint ( ). Every applet and every
applicationthathasaGUI,hasaGUIthread.
TheGUIthreadspontaneouslycallspaint()wheneverallorpartofacomponentneeds
redrawingafteranyofthefollowingevents:
Afterexposure.
Afterde-iconification.
Afterfirstdisplay.
Whenabrowserreturnstoapreviouslypagecontaininganapplet,providedthat
applet is at least partially visible.When the GUI thread calls paint ( ), it must supply a
graphics context, since the paint ( ) method’s input parameter is an instance of the
Graphicsclass.
Anearliersection(“clipping”)discussedthefactthateverygraphicscontexthas
a clip region. The GUI thread makes sure that the graphics contexts that get passed to
paint ( ) have their clip regions appropriately set. Most often, the default clip region is
appropriate.
However, when a component is exposed, the clip region is set to be just that
portionofthecomponentthatrequiresrepair.Ifonlyasmallpieceofthecomponentwas
exposed,thentheclipregionensuresthatnotimeiswasteddrawingpixelsthatarealready
thecorrectcolor.
Ifanexposedregionisnon-rectangular,thenmultiplecallstopaint()mightoccur,with
theclipregionofeachsuccessivelybuildinguptoensurethatthewholeexposedareagets
repaintedeventually.
Explicitlyinvokingpaint()method:
The component may not get refreshed if the drawing operations on it are
performed ina methodother thanthe paint( )method. Ifdrawing isdone inthe paint
method()thenitgetsdisplayedwhenwecallthepaint()methodexplicitlyaswellas
whenthepaint()methodiscalledimplicitlyGUIthread.
The mouse Clicked ( ) method of the previous example is rewritten so that it simply
modifiestheinstancevariablesmouseXandmouseYwhenevermouseclickhappens.
Thereddoisdrawninthepaint()methodonlysothatitgetsrepairedevenifappletgets
coveredandexposed.
Example19.7:
The example in the previous section is modified so that the components display gets
refreshedinthesituationsdescribedabove.Thishappensbecausethereddotisdrawnin
thepaint()method.
1.importjava.awt.*;
2.importjava.awt.event.*;
3.publicclassPaintApproach1extendsFrameimplementsMouseListener
4.{
5.intmouseX,mouseY;
6.publicstaticvoidmain(Stringarg[])
7.{
8.PaintApproach1f=newPaintApproach2();
9.f.setSize(300,300);
10.f.addMouseListener(f);
11.f.setVisible(true);
12.}
13.publicvoidmouseEntered(MouseEvente){}
14.publicvoidmouseExited(MouseEvente){}
15.publicvoidmousePressed(MouseEvente){}
16.publicvoidmouseReleased(MouseEvente){}
17.publicvoidmouseClicked(MouseEvente)
18.{
19.System.out.println(“MouseClicked…”);
20.mouseX=e.getX();
21.mouseY=e.getY();
22.Graphicsg=getGraphics();
23.paint(g);
24.}
25.publicvoidpaint(Graphicsg)
26.{
27.g.setColor(Color.yellow);
28.g.fillRect(0,0,getSize().width,getSize().height);
29.g.setColor(Color.red);
30.g.fillOval(mouseX–10,mouseY–10,20,20);
31.}
32.}
Explicitly invoking repaint( ) method, which then indirectly invokes the paint(
)method:
Invokingpaint()methodexplicitlymayalsoleadtotwoseriousproblems.
The first problem is that the GUI thread is calling the paint ( ) method as and
when it needs to It occurs when exposure needs to be handled. This can cause thread
interactionissues.
To be fair, we will see that we might have to handle some of these issues any
way,evenwhenusingthepreferredapproach,sincethepaint()methodwillusedatathat
wearemodifyinginotherthreads.However,wewillminimizetheproblemifweallow
paint()tobecalledonlyintheGUIthread.
TheSecondproblemisoneofCPUusage.Considerthisscenario:ourprogramis
getting regular notification that it should update the display with the next frame of an
animationorsimilarcontinuouslymovinggraphic.
Alsosupposethatthedrawingiscomplexandtime-consuming.Itwesimplycall
thewholepaint()method,wemightbeonlypartwaythroughthedrawingwhenframe
triggeroccurs.
This would result in our program spending. Or trying to spend, all its time in
drawingFurther,thedrawingwouldgetfurtherandfurtherbehindwhereitshouldbe.
Theseproblemscanbe dealtsimplybyusingthe preferredmethodofhandling
program initiated drawing. The idea is that the main program maintains data set that
describesthedrawingthatshouldbepresentedtotheuser,butdoesnotdirectlycallthe
drawingroutines.
Instead, the program requests that the GUI thread should run the painting
routines,inbroadlythesamewaythatthreadwoulddoifitwerehandlingexposure.
TheGUIthreadusesthedatasetpresentedbymainprogramtodecidewhatand
howtodraw.
To support this approach, the GUI system provides a method called repaint( ).
ThismethodisdefinedintheComponentclass,andsoisavailableonanythingvisibleina
GUI.Whenwecallthismethod,weareissuingarequesttotheGUIthreadthatitshould
performthepaintingsystemroutines.
TheGUIthreaddoesso withinareasonable timescale,although thismightbe
limited by other high- priority thread activity.This approach ensures that the thread
interactionsbetweentheGUIthreadanduserthreadsareminimized.
Wemust,naturally,ensurethatourdatasetisneverusedbytheGUIthreadwhile
thatdataisinaninconsistentstate.However,thiscanbeachievedquiteeasilyusingeither
synchronizationordoublebufferingtechnique.
Anotherconsequenceofthisbehavioristhat,nomatterhaowmuchdrawingthe
programtriestodo,thesystemgenerallyremainssynchronizedwithcurrentframe.
This happens because if we call the repaint ( ) method ten times, for example,
before the GUI thread is able to service the first call, then the result will be a single
executionofthepaintingsystem.
Therefore, in overloaded conditions, the painting system automatically skips
framesthatthehostCPUsimplycannotdealwith.Thismeansthattheprogrammercan
writecodethatreliablygetsthebestavailablevideoperformanceonagivenplatform,but
stillworkstolerablywellonanyotherplatform.Thefollowingcodeimplementsthiskind
ofscheme.
Example19.8:
1.importjava.awt.*;
2.importjava.awt.event.*;
3.publicclassPaintApproach2extendsFrameimplementsMouseListener
4.{
5.intmouseX,MouseY;
6.publicstaticvoidmain(Stringargs[])
7.{
8.PaintApproach2f=newPaintApproach2();
9.f.setSize(300,300);
10.f.addMouseListener(f);
11.f.setVisible(true);
12.}
13.publicvoidmouseEntered(MouseEvente){}
14.publicvoidmouseExited(MouseEvente){}
15.publicvoidmousePressed(MouseEvente){}
16.publicvoidmouseReleased(MouseEvente){}
17.publicvoidmouseClicked(MouseEvente)
18.{
19.System.out.println(“MouseClicked…“);
20.mouseX=e.getX();
21.mouseY=e.getY();
22.repaint();
23.}
24.publicvoidpaint(Graphicsg)
25.{
26.g.setColor(Color.white);
27.g.fillRect(0,0,getSize().width,getSize().height);
28.g.setColor(Color.gray);
29.g.fillOval(MouseX-10,mouseY–10,20,20);
30.}
31.}
Noticethatrepaint()callhasreplacedthedirecthandlingofpainting.Now,regardlessof
howfrequentlytheeventhandleriscalled,callstopaint()willnotoutstripthesystem’s
abilitytodraw,andtheprogramcannotfallincreasinglybehind.
The previous code shows the essence of the preferred approach to program
initiateddrawing.Themainprogramstoresinformationinistancevariablesandthencalls
therepaint()method.
Therepaint()methodrequeststhattheGUIthreaddrawsthescreen.TheGUI
threadusesthepaint( )methodtodothe drawing,andthatmethodshouldperformthe
drawingaccordingtotheinformationintheinstancevariable.
Thebenefitsofthisapproachare:
Thescreeniscorrectlyrepairedwhentheenvironmentspontaneouslycallspaint(
).
Thethread interactions,between foregroundthreads tryingto draw andthe GUIthread,
arecontrolledandpredictable.
Thevirtualmachineisneveroverwhelmedbypainting.
When all the code is written this way, there are no surprises for other
programmerstryingtodebugthecode.
Although this approach works well, there is a situation where still further
improvementisneeded:animation.Ifweusetheapproachexactlyasdescribed,wewill
probablynoticethatananimationflickersunpleasantlywhileitruns.
SmoothAnimation:
Onefeatureofthedefault behaviorofthe repaintingmechanismthat wemight
notalways wantis thatthesystem clearsour drawingarea aspart ofthepreparation to
respond to our call to repaint ( ). This can make animations and another real time
drawings flicker unpleasantly. It turns out that when we call repaint( ), the GUI thread
does not call paint ( ); instead it calls the update ( ) method. The default behavior of
update()istodotwothings.Clearthebackgroundandthencallpaint.Likethis:
publicvoidupdate(Graphicsg)
{
g.clearRect(0,0,width,height);
paint(g);
}
We might reasonably ask why repaint () starts by clearing the window if this
causes flickering. Well, in many cases, drawings are done using lines, rectangles, ovals
andsoforthdrawnonabackground.
Ifwearetryingtomakeaspinningstick,weneedtoremovetheoldlinebefore
wedrawthenewone.Anotherwaytothinkaboutthisistoconsiderthatifwearetrying
todrawanewdrawing,weshouldfirsterasetheoldone.
So,howcanwearrangeforthenewdrawingtoappearwithouthavingtoclear
thewholedisplayfirst?Wesimplyneedtofindanotherwaytoremovetheolddrawing.
Thegeneralapproachistoensurethatwedrawthewholedrawing-bothbackgroundand
foreground each time we draw a frame. If we can arrange this, then we do not need to
clearthecomponent,andtheflickeringgoesaway.
To prevent the component being cleared before paint ( ) is called, we simply
overridetheupdate()methodsothatitcallspaintdirectly,asshownbelow:
publicvoidupdate(Graphicsg)
{
paint(g);
}
This is a standard technique and works perfectly, provided that our paint ( )
method does indeed refresh all the pixels of the display. On particularly easy way to
handlethisistouseanoffscreenimagetostoreadrawingofwhatshouldbeshownon
thedisplay.
Thistechniqueisnotalwaysthemostefficient,ineitherspeedormemoryterms,
but it is simple and easy to implement, and generally well understood by Java
programmers.
CHAPTER
∞20∞
(Java.Lang.ObjectClass)
Introduction-
TheObjectclassofjava.langpackageistherootofallthehierarchiesinJava.All
classesextendtheObjectclass,eitherdirectlyorindirectly.
Even if you write a simple class (i.e. it is not extending any base-class), it
implicityextendbuilt-inObjectclass.Thusthefeaturesofthisclasswillbeavailableinall
theclasses.
MethodsinObjectclass:
Theobjectclassdefinesfollowingmethods,whichareinheritedbyalltheclasses.
1. publicinthashCode()
2. publicbooleanequals(Objectobj)
3. publicfinalClassgetClass()
4. publicStringtoString()
5. protectedvoidfinalize()throwsThrowable
6. protectedObjectclone()throwsCloneNotSupportedException
7. publicfinalvoidwait(longtimeout)throwsInterrputedException
8. publicfinalvoidwait(longtimeout,intnanos)throwsInterrputedException
9. publicfinalvoidwait()throwsInterrputedException
10. publicfinalvoidnotify()
11. publicfinalvoidnotifyAll()
1.publicinthashCode():
Whenstoringobjectsinhash tables,thismethodcanbeused togetahashvaluefor an
object.Thisvalueisguaranteedtobeconsistentduringtheexecutionoftheprogram.
2.booleanequals(Objectobj):
Ifeveryobjectistobeconsideredunique,thenitisnotnecessarytooverridetheequals()
methodoftheObjectclass.Thismethodcomaresobjectreferenceforequality.
3.finalClassgetClass():
Returns the runtime class of the object, which is represented by an object of the class
java.lang.Classatruntime.
Example20.1:Thefollowingexampleillustratesthatthismethodcanbeusedtogetthe
Classobjectcorrespondingtoanyjavaobject.WecanthenusemethodsoftheclassClass
togetinformationabouttheobject’sclassusingreflection/introspection.getMethods()and
getFields() will display all the public members only, but get DeclaredMethods() and
getDeclaredFields()willdisplayallthemembers.
1.importjava.lang.reflect.Method;
2.importjava.lang.reflect.Field;
3.classDispClassMembers1
4.{
5.publicstaticvoidmain(Stringargs[])
6.{
7.Strings=newString(“Hello”);
8.Classc=s.getClass();
9.Methodm[]=c.getMethods();
10.System.out.println(“……PublicMethods(”+m.length+“)……”);
11.for(inti=0;i<m.length;i++)
12.System.out.println(m[i]);
13.Fieldf[]=c.getFields();
14.System.out.println(“……PublicFields(“+f.length+”)……”);
15.for(inti=0;i<f.length;i++)
16.System.out.println(f[i]);
17.m=c.getDeclaredMethods();
18.System.out.println(“……DeclaredMethods(“+m.length+”)……”);
19.for(inti=0;i<m.length;i++)
20.System.out.println(m[i]);
21.f=c.getDeclaredFields();
22.System.out.println(“……DeclaredFields(“+f.length+”)……”);
23.for(inti=0;i<f.length;i++)
24.System.out.println(f[i]);
25.}
26.}
Output:
……PublicMethods(72)……
publicintjava.lang.String.hashCode()
publicintjava.lang.String.compareTo(java.lang.String)
publicintjava.lang.String.compareTo(java.lang.Object)
publicintjava.lang.String.indexOf(int,int)
publicintjava.lang.String.indexOf(int)
publicintjava.lang.String.indexOf(java.lang.String)
publicintjava.lang.String.indexOf(java.lang.String,int)
publicbooleanjava.lang.String.equals(java.lang.Object)
publicjava.lang.Stringjava.lang.String.toString()
publiccharjava.lang.String.charAt(int)
publicintjava.lang.String.codePointAt(int)
publicintjava.lang.String.codePointBefore(int)
publicintjava.lang.String.codePointCount(int,int)
publicintjava.lang.String.compareToIgnoreCase(java.lang.String)
publicjava.lang.Stringjava.lang.String.concat(java.lang.String)
publicbooleanjava.lang.String.contains(java.lang.CharSequence)
publicbooleanjava.lang.String.contentEquals(java.lang.StringBuffer)
publicbooleanjava.lang.String.contentEquals(java.lang.CharSequence)
publicstaticjava.lang.Stringjava.lang.String.copyValueOf(char[])
publicstaticjava.lang.Stringjava.lang.String.copyValueOf(char[],int,int)
publicbooleanjava.lang.String.endsWith(java.lang.String)
publicbooleanjava.lang.String.equalsIgnoreCase(java.lang.String)
publicstaticjava.lang.Stringjava.lang.String.format(java.lang.String,java.lang.Object[])
publicstaticjava.lang.String
java.lang.String.format(java.util.Locale,java.lang.String,java.lang.Object[])
publicbyte[]java.lang.String.getBytes()
publicbyte[]java.lang.String.getBytes(java.nio.charset.Charset)
publicbyte[]java.lang.String.getBytes(java.lang.String)throws
java.io.UnsupportedEncodingException
publicvoidjava.lang.String.getBytes(int,int,byte[],int)
publicvoidjava.lang.String.getChars(int,int,char[],int)
publicnativejava.lang.Stringjava.lang.String.intern()
publicbooleanjava.lang.String.isEmpty()
publicintjava.lang.String.lastIndexOf(int)
publicintjava.lang.String.lastIndexOf(java.lang.String)
publicintjava.lang.String.lastIndexOf(java.lang.String,int)
publicintjava.lang.String.lastIndexOf(int,int)
publicintjava.lang.String.length()
publicbooleanjava.lang.String.matches(java.lang.String)
publicintjava.lang.String.offsetByCodePoints(int,int)
publicbooleanjava.lang.String.regionMatches(boolean,int,java.lang.String,int,int)
publicbooleanjava.lang.String.regionMatches(int,java.lang.String,int,int)
publicjava.lang.String
java.lang.String.replace(java.lang.CharSequence,java.lang.CharSequence)
publicjava.lang.Stringjava.lang.String.replace(char,char)
publicjava.lang.Stringjava.lang.String.replaceAll(java.lang.String,java.lang.String)
publicjava.lang.Stringjava.lang.String.replaceFirst(java.lang.String,java.lang.String)
publicjava.lang.String[]java.lang.String.split(java.lang.String,int)
publicjava.lang.String[]java.lang.String.split(java.lang.String)
publicbooleanjava.lang.String.startsWith(java.lang.String,int)
publicbooleanjava.lang.String.startsWith(java.lang.String)
publicjava.lang.CharSequencejava.lang.String.subSequence(int,int)
publicjava.lang.Stringjava.lang.String.substring(int,int)
publicjava.lang.Stringjava.lang.String.substring(int)
publicchar[]java.lang.String.toCharArray()
publicjava.lang.Stringjava.lang.String.toLowerCase()
publicjava.lang.Stringjava.lang.String.toLowerCase(java.util.Locale)
publicjava.lang.Stringjava.lang.String.toUpperCase()
publicjava.lang.Stringjava.lang.String.toUpperCase(java.util.Locale)
publicjava.lang.Stringjava.lang.String.trim()
publicstaticjava.lang.Stringjava.lang.String.valueOf(boolean)
publicstaticjava.lang.Stringjava.lang.String.valueOf(char[],int,int)
publicstaticjava.lang.Stringjava.lang.String.valueOf(int)
publicstaticjava.lang.Stringjava.lang.String.valueOf(long)
publicstaticjava.lang.Stringjava.lang.String.valueOf(float)
publicstaticjava.lang.Stringjava.lang.String.valueOf(double)
publicstaticjava.lang.Stringjava.lang.String.valueOf(char[])
publicstaticjava.lang.Stringjava.lang.String.valueOf(java.lang.Object)
publicstaticjava.lang.Stringjava.lang.String.valueOf(char)
publicfinalnativejava.lang.Classjava.lang.Object.getClass()
publicfinalvoidjava.lang.Object.wait(long,int)throwsjava.lang.InterruptedException
publicfinalvoidjava.lang.Object.wait()throwsjava.lang.InterruptedException
publicfinalnativevoidjava.lang.Object.wait(long)throwsjava.lang.InterruptedException
publicfinalnativevoidjava.lang.Object.notify()
publicfinalnativevoidjava.lang.Object.notifyAll()
……PublicFields(1)……
publicstaticfinaljava.util.Comparatorjava.lang.String.CASE_INSENSITIVE_ORDER
……DeclaredMethods(70)……
publicintjava.lang.String.hashCode()
publicintjava.lang.String.compareTo(java.lang.String)
publicintjava.lang.String.compareTo(java.lang.Object)
publicintjava.lang.String.indexOf(int,int)
publicintjava.lang.String.indexOf(int)
publicintjava.lang.String.indexOf(java.lang.String)
publicintjava.lang.String.indexOf(java.lang.String,int)
staticintjava.lang.String.indexOf(char[],int,int,char[],int,int,int)
publicbooleanjava.lang.String.equals(java.lang.Object)
publicjava.lang.Stringjava.lang.String.toString()
publiccharjava.lang.String.charAt(int)
privatestaticvoidjava.lang.String.checkBounds(byte[],int,int)
publicintjava.lang.String.codePointAt(int)
publicintjava.lang.String.codePointBefore(int)
publicintjava.lang.String.codePointCount(int,int)
publicintjava.lang.String.compareToIgnoreCase(java.lang.String)
publicjava.lang.Stringjava.lang.String.concat(java.lang.String)
publicbooleanjava.lang.String.contains(java.lang.CharSequence)
publicbooleanjava.lang.String.contentEquals(java.lang.StringBuffer)
publicbooleanjava.lang.String.contentEquals(java.lang.CharSequence)
publicstaticjava.lang.Stringjava.lang.String.copyValueOf(char[])
publicstaticjava.lang.Stringjava.lang.String.copyValueOf(char[],int,int)
publicbooleanjava.lang.String.endsWith(java.lang.String)
publicbooleanjava.lang.String.equalsIgnoreCase(java.lang.String)
publicstaticjava.lang.Stringjava.lang.String.format(java.lang.String,java.lang.Object[])
publicstaticjava.lang.String
java.lang.String.format(java.util.Locale,java.lang.String,java.lang.Object[])
publicbyte[]java.lang.String.getBytes()
publicbyte[]java.lang.String.getBytes(java.nio.charset.Charset)
publicbyte[]java.lang.String.getBytes(java.lang.String)throws
java.io.UnsupportedEncodingException
publicvoidjava.lang.String.getBytes(int,int,byte[],int)
voidjava.lang.String.getChars(char[],int)
publicvoidjava.lang.String.getChars(int,int,char[],int)
publicnativejava.lang.Stringjava.lang.String.intern()
publicbooleanjava.lang.String.isEmpty()
publicintjava.lang.String.lastIndexOf(int)
publicintjava.lang.String.lastIndexOf(java.lang.String)
publicintjava.lang.String.lastIndexOf(java.lang.String,int)
publicintjava.lang.String.lastIndexOf(int,int)
staticintjava.lang.String.lastIndexOf(char[],int,int,char[],int,int,int)
publicintjava.lang.String.length()
publicbooleanjava.lang.String.matches(java.lang.String)
publicintjava.lang.String.offsetByCodePoints(int,int)
publicbooleanjava.lang.String.regionMatches(boolean,int,java.lang.String,int,int)
publicbooleanjava.lang.String.regionMatches(int,java.lang.String,int,int)
publicjava.lang.String
java.lang.String.replace(java.lang.CharSequence,java.lang.CharSequence)
publicjava.lang.Stringjava.lang.String.replace(char,char)
publicjava.lang.Stringjava.lang.String.replaceAll(java.lang.String,java.lang.String)
publicjava.lang.Stringjava.lang.String.replaceFirst(java.lang.String,java.lang.String)
publicjava.lang.String[]java.lang.String.split(java.lang.String,int)
publicjava.lang.String[]java.lang.String.split(java.lang.String)
publicbooleanjava.lang.String.startsWith(java.lang.String,int)
publicbooleanjava.lang.String.startsWith(java.lang.String)
publicjava.lang.CharSequencejava.lang.String.subSequence(int,int)
publicjava.lang.Stringjava.lang.String.substring(int,int)
publicjava.lang.Stringjava.lang.String.substring(int)
publicchar[]java.lang.String.toCharArray()
publicjava.lang.Stringjava.lang.String.toLowerCase()
publicjava.lang.Stringjava.lang.String.toLowerCase(java.util.Locale)
publicjava.lang.Stringjava.lang.String.toUpperCase()
publicjava.lang.Stringjava.lang.String.toUpperCase(java.util.Locale)
publicjava.lang.Stringjava.lang.String.trim()
publicstaticjava.lang.Stringjava.lang.String.valueOf(boolean)
publicstaticjava.lang.Stringjava.lang.String.valueOf(char[],int,int)
publicstaticjava.lang.Stringjava.lang.String.valueOf(int)
publicstaticjava.lang.Stringjava.lang.String.valueOf(long)
publicstaticjava.lang.Stringjava.lang.String.valueOf(float)
publicstaticjava.lang.Stringjava.lang.String.valueOf(double)
publicstaticjava.lang.Stringjava.lang.String.valueOf(char[])
publicstaticjava.lang.Stringjava.lang.String.valueOf(java.lang.Object)
publicstaticjava.lang.Stringjava.lang.String.valueOf(char)
……DeclaredFields(7)……
privatefinalchar[]java.lang.String.value
privatefinalintjava.lang.String.offset
privatefinalintjava.lang.String.count
privateintjava.lang.String.hash
privatestaticfinallongjava.lang.String.serialVersionUID
privatestaticfinaljava.io.ObjectStreamField[]java.lang.String.serialPersistentFields
publicstaticfinaljava.util.Comparatorjava.lang.String.CASE_INSENSITIVE_ORDER
Example20.2:
Thepreviousexampleismodifiedsoastoreadthefullyqualifiedclassnameascommand
lineargumentandthendisplaytheinformationabouttheclass’smethodsandfieldsusing
reflection/introspection.
1.importjava.lang.reflect.Method;
2.importjava.lang.reflect.Field;
3.classDispClassMembers2
4.{
5.publicstaticvoidmain(Stringargs[])throwsClassNotFoundException
6.{
7.Classc=Class.forName(args[0]);
8.Methodm[]=c.getMethods();
9.System.out.println(“……PublicMethods(”+m.length+“)……”);
10.for(inti=0;i<m.length;i++)
11.System.out.println(m[i]);
12.Fieldf[]=c.getFields();
13.System.out.println(“……PublicFields(”+f.length+“)……”);
14.for(inti=0;i<f.length;i++)
15.System.out.println(f[i]);
16.m=c.getDeclaredMethods();
17.System.out.println(“……DeclaredMethods(“+m.length+”)……”);
18.for(inti=0;i<m.length;i++)
19.System.out.println(m[i]);
20.f=c.getDeclaredFields();
21.System.out.println(“……DeclaredFields(“+f.length+”)……”);
22.for(inti=0;i<f.length;i++)
23.System.out.println(f[i]);
24.}
25.}
Output:
Sameaspreviousbutpasstheclassname“String”fromcommandlinearguments.
javacDispClassMembers2.java
javaDispClassMembers2String
4.StringtoString():
Ifasubclassdoesnotoverridethismethod,itreturnsatextualrepresentationof
theobject,whichhasthefollowingformat:
“<nameoftheclass>@<hashcodevalueofobject>”
Themethodisusuallyoverriddenandusedfordebuggingpurposes.Themethod
call System.out.println(Objref) will implicitly convert its argument to a textual
representationusingtoString()method.
Example20.3:
ThisexampledemonstrateswhatgetsdisplayedifwetrytodisplayobjectofclassBox.
theobjectisconvertedtothetextualrepresentationusingthetoStringmethodoftheobject
class.
1.classBox
2.{
3.doublew,h,d;
4.Box(doublew,doubleh,doubled)
5.{
6.this.w=w;this.h=h;this.d=d;
7.}
8.}
9.classToStringDemo1
10.{
11.publicstaticvoidmain(Stringargs[])
12.{
13.Boxb=newBox(10,12,14);
14.Strings=”Boxb:”+b;
15.System.out.println(b);
16.System.out.println(s);
17.}
18.}
Output:
Box1@82b41
Box1b:Box1@82b41
Example20.4:
ThisexampledemonstratethatifweoverridethetoString()methodintheBoxclassthen
theoverriddenmethodisusedtoconverttheobjecttoitstextualrepresentation.
1.classBox
2.{
3.doublew,h,d;
4.Box(doublew,doubleh,doubled)
5.{
6.this.w=w;this.h=h;this.d=d;
7.}
8.publicStringtoString()
9.{
10.return“Dimensionsare”+w+“by”+h+“by”+d+“.”;
11.}
12.}
13.classToStringDemo2
14.{
15.publicstaticvoidmain(Stringargs[])
16.{
17.Boxb=newBox(8,11,13);
18.Strings=”Boxb:”+b;//concatenatesboxobject&callingtoString()method
19.System.out.println(b);//CallingtoString()method
20.System.out.println(s);
21.}
22.}
Output:
Dimensionare8.0by11.0by13.0
Boxb:Dimensionare8.0by11.0by13.0
5.protectedvoidfinalize()throwsThrowable
Itiscalledonanobjectjustbeforeitisgarbagecollected,sothatanycleaningup
can be done. However, the default finalize() method in the object class does not do
anything useful. This may be useful for releasing non-java resources but not
recommended.Itispossiblethatfinalize()methodmayneverbecalledifenoughmemory
isavailableandinthatcaseresourcesmayneverbereleased.
6.protectedObjectclone()throwsCloneNotSupportedException
New objects that are exactly the same (i.e. have identical states) as the current
objectcanbecreatedbytheclone()method,thatis,primitivevaluesandreferencevalues
arecopied,thisiscalledshallowcloning.
Aclasscanoverridetheclone()methodtoprovideitsownnotionofcloning.For
example,cloningacompositeobjectbyrecursivelycloningtheconstituentobjectiscalled
deepcloning.Whenoverridden,themethodinthesubclassisusuallydeclaredpublicto
allowanyclienttocloneobjectsoftheclass.
Ifoverridingclone()methodreliesontheclone()methodintheObjectclass,then
thesubclassmustimplementthecloneablemarkerinterfacetoindicatethatitsobjectscan
besafelycloned.Otherwise,theclone()methodintheObjectclasswillthrowachecked
CloneNotSupportedException.
Usingclone()andtheCloneableinterface:
Theclone()methodgeneratesaduplicatecopyoftheobjectonwhichitiscalled.
Thesearefewimportantfactsrelatedtoclone()method:
Only classes that implement the Cloneable interface can be cloned. The
Cloneableinterfacedefinesnomembers.Itisusedtoindicatethataclassallowsabit-wise
copyofanobject(thatis,aclone)tobemade.
Ifyoutrytocallclone()onobjectofaclassthatdoesnotimplementcloneable
interface,CloneNotSupportedExceptionisthrown.
Cloneableinterfaceisanemptyinterface.Suchaninterfaceiscalledmarker/tag
interface.Whenacloneismade,theconstructorfortheobjectbeingclonedisnotcalled.
A clone is simply an exactly copy of the original. Cloning is potentially a
dangerousaction,becauseitcancauseunintendedsideeffects.
For example, if the object being cloned contains a reference variable called
objRef,thenwhenthecloneismadetheobjRefinclonewillrefertothesameobjectas
doesobjRefinoriginal.Iftheclonemakesachangetothecontentsoftheobjectreferred
tobyobjRef,thenitwillbechangedfortheoriginalobject,too.
Example20.5:
Thefollowingexampledemonstratestheuseofclone()method.TheCloneDemo1classis
makingclone of theobject of classTestClone1byindirectlycalling theclone() method
throughclone2()method.
1.classTestClone1implementsCloneable
2.{
3.inta;
4.floatb;
5.publicTestClone1clone2()throwsCloneNotSupportedException
6.{
7.return(TestClone1)clone();
8.}
9.}
10.classCloneDemo1
11.{
12.publicstaticvoidmain(Stringa[])throwsCloneNotSupportedException
13.{
14.TestClone1tc1=newTestClone1();
15.TestClone1tc2;
16.tc1.a=8;tc1.b=4.5f;
17.tc2=tc1.clone2();
18.System.out.println(tc2.a);
19.System.out.println(tc2.b);
20.}
21.}
Output:
8
4.5
Here,themethodclone2()callsclone()ofObjectclassandreturnstheresult.Noticethat
theobjectreturnedbyclone()mustbecastintoitsappropriatetypei.e.TestClone1.
Example20.6:Inthefollowingexample,theclone()methodisoverriddensothatitcanbe
calledfromcodeoutsideofitsclass.Todothis,itsaccessmodifiermustbepublic.
1.classTestClone2implementsCloneable
2.{
3.inta;
4.floatb;
5.publicObjectclone()throwsCloneNotSupportedException
6.{
7.returnsuper.clone();
8.}
9.}
10.classCloneDemo2
11.{
12.publicstaticvoidmain(Stringargs[])throwsCloneNotSupportedException
13.{
14.TestClone2tc1=newTestClone2();
15.TestClone2tc2;
16.tc1.a=8;tc1.b=4.5f;
17.tc2=(TestClone2)tc1.clone();
18.System.out.println(tc2.a+“,”+tc2.b);
19.}
20.}
Output:8,4.5
Example 20.7: In the following example, the clone() method is overridden such thatit
does not make use of the clone() method of the Object class. We are writing our own
clone()method.
1.classTestClone3
2.{
3.inta;
4.floatb;
5.publicObjectclone()
6.{
7.TestClone3tc=newTestClone3();
8.tc.a=a;
9.tc.b=b;
10.returntc;
11.}
12.}
13.classCloneDemo3
14.{
15.publicstaticvoidmain(Stringargs[])
16.{
17.TestClone3tc1=newTestClone3();
18.TestClone3tc2;
19.tc1.a=8;
20.tc1.b=4.5f;
21.tc2=(TestClone3)tc1.clone();
22.System.out.println(tc2.a+“,”+tc2.b);
23.}
24.}
Output:
8,4.5
Note: You need not declare CloneNotSupportedException and need not implement
Cloneableinterfaceifimplementingyouownclone()method.
SideEffectofCloning-
Thesideeffectscausedbycloningaresometimesdifficulttoseeatfirst.Itiseasytothink
thataclassissafeforcloningwhenitactuallyisnot.
In general, you should not implement Cloneable interface for any class without good
reason.
Example20.8:Thisexampledemonstratesthesideeffectofcloning.
1.classTestShallowCloneimplementsCloneable
2.{
3.inta;
4.floatb;
5.intc[];
6.publicObjectclone()throwsCloneNotSupportedException
7.{
8.returnsuper.clone();
9.}
10.}
11.classShallowCloneDemo
12.{
13.publicstaticvoidmain(Stringarg[])throwsCloneNotSupportedException
14.{
15.TestShallowClonetc1=newTestShallowClone();
16.TestShallowClonetc2;
17.tc1.a=8;
18.tc1.b=4.5f;
19.intc[]=newint[4];
20.for(inti=0;i<4;i++)
21.c[i]=i;
22.tc1.c=c;
23.for(inti=0;i<4;i++)
24.System.out.println(“tc1.c[”+i+“]=”+tc1.c[i]);
25.tc2=(TestShallowClone)tc1.clone();
26.System.out.println(“tc2.a”+tc2.a);
27.System.out.println(“tc2.b”+tc2.b);
28.for(inti=0;i<4;i++)
29.System.out.println(“tc2.c[”+i+“]=”+tc2.c[i]);
30.for(inti=0;i<4;i++)
31.tc2.c[i]=i+4;
32.for(inti=0;i<4;i++)
33.System.out.println(“tc2.c[”+i+“]=”+tc2.c[i]);
34.for(inti=0;i<4;i++)
35.System.out.println(“tc1.c[”+i+“]=”+tc1.c[i]);
36.}
37.}
Output:
tc1.c[0]=0
tc1.c[1]=1
tc1.c[2]=2
tc1.c[3]=3
tc2.a=8
tc2.b=4.5
tc2.c[0]=0
tc2.c[1]=1
tc2.c[2]=2
tc2.c[3]=3
tc2.c[0]=4
tc2.c[1]=5
tc2.c[2]=6
tc2.c[3]=7
tc1.c[0]=4
tc1.c[1]=5
tc1.c[2]=6
tc1.c[3]=7
Example20.9:Thefollowingcodeeliminatestheproblemfacedinthepreviousexamplebyimplementingdeepcloning.
1.classTestDeepCloneimplementsCloneable
2.{
3.inta;
4.floatb;
5.intc[];
6.publicObjectclone()throwsCloneNotSupportedException
7.{
8.TestDeepClonetc=(TestDeepClone)super.clone();
9.intd[]=newint[4];
10.for(inti=0;i<4;i++)
11.d[i]=c[i];
12.tc.c=d;
13.return(tc);
14.}}
16.classDeepCloneDemo
17.{
18.publicstaticvoidmain(Stringarg[])throwsCloneNotSupportedException
19.{
20.TestDeepClonetc1=newTestDeepClone();
21.TestDeepClonetc2;
22.tc1.a=8;
23.tc1.b=4.5;
24.intc[]=newint[4];
25.for(inti=0;i<4;i++)
26.c[i]=i;
27.tc1.c=c;
28.for(inti=0;i<4;i++)
29.System.out.println(“tc1.c[”+i+”]=”+tc1.c[i]);
30.tc2=(TestDeepClone)tc1.clone();
31.System.out.println(“tc2.a”+tc2.a);
32.System.out.println(“tc2.b”+tc2.b);
33.for(inti=0;i<4;i++)
34.System.out.println(“tc2.c[”+i+“]=”+tc2.c[i]);
35.for(inti=0;i<4;i++)
36.tc2.c[i]=i+4;
37.for(inti=0;i<4;i++)
38.System.out.println(“tc2.c[”+i+“]=”+tc2.c[i]);
39.for(inti=0;i<4;i++)
40.System.out.println(“tc1.c[”+i+“]=”+tc1.c[i]);
41.}}
Output:tc1.c[0]=0
tc1.c[1]=1
tc1.c[2]=2
tc1.c[3]=3
tc2.a=8
tc2.b=4.5
tc2.c[0]=0
tc2.c[1]=1
tc2.c[2]=2
tc2.c[3]=3
tc2.c[0]=4
tc2.c[1]=5
tc2.c[2]=6
tc2.c[3]=7
tc1.c[0]=0
tc1.c[1]=1
Methodsusefulinmulti-threadedenvironment:
Inadditiontomethodsdiscussedabove,objectclassprovidessupportforthread
communication in synchronized code through the following methods: Causes current
threadtowaituntilanotherthreadinvokesthenotify()methodorthenotifyAll()method
forthisobject.
8.finalvoidwait(longtimeout)throwsInterruptedException
9.finalvoidwait(longtimeout,longnanos)throwsInterruptedException
Causes current thread to wait until either another thread invokes the notify()
method or the notifyAll() method for this object. or some other thread interrupts the
currentthread,orthespecifiedamountoftimehaselapsed.
10.finalvoidnotify()
Wakesupasinglethreadthatiswaitingonthisobject’smonitor.
11.finalvoidnotifyAll()
Wakesupallthreadthatarewaitingonthisobject’smonitor.Athreadwaitsonan
object’smonitorbycallingoneofthewaitmethods.
Athreadinvokesthesemethodsontheobjectwhoselockitholds.Athreadwaits
fornotificationbyanotherthread.
CHAPTER
∞21∞
(CollectionFramework)
Introduction-
TheJavaCollectionsframeworkstandardizesthewayinwhichgroupofobjects
arehandledbyyourprograms.PriortoJava2,JavaprovidedadhocclassessuchasVector,
Stack,Dictionary,HashtableandPropertiestostoreandmanipulategroupsofobjects.
Althoughtheseclasseswere quiteuseful,theylackedacentralunifyingtheme.
ThewaythatweuseVectorwasdifferentfromthewaythatweusepropertiesclass,Also,
the previous ad hoc approach was not designed to be easily extensible or adaptable.
Collectionsareananswertothese(andother)problems.
The Collection framework was designed keeping into consideration the following
objectives:
The Framework has to be high-performance. The implementations for the
fundamentalcollections(dynamicarrays,linkedlists,trees,andhashtables)are
highlyefficient.
TheFrameworkhastoallowdifferenttypesofcollectionstoworkinasimilar
mannerandwithahighdegreeofinteroperability.
Extendingand/oradaptingtoacollectionhadbeeneasy.
Toachievetheabovegoals,thecollectionframeworkdesignthefollowingfeatures:
EntireCollectionframeworkisdesignedaroundasetofstandardinterfaces.The
severalstandardimplementationsoftheseinterfacesareprovided.Wemayalso
implementourowncollection.
Anotheritemcreatedby thecollectionsframeworkisthe Iteratorinterface.An
Iteratorgivesyouageneral-purpose,standardizedwaysofaccessingtheelement
withinacollection,oneatatime.
Thus,anIteratorprovidesameansofenumeratingthecontentsofacollection.
BecauseeachcollectionimplementIterator,theelementsifanycollectionclass
canbeaccessedthroughthemethodsdefinedbyIterator.This,withonlysmall
changes,thecodethatcyclethroughasetcanalsobeusedtocyclethroughalist,
forexample.
In addition to collections, the framework defines several map interfaces and
classes. Maps store key/value pairs. Although maps are not “collection” in the
properuseoftheterm,theyarefullyintegratedwithcollections.
Inthelanguageofthecollectionframework,wecanobtainacollectionviewof
map. Such a view contains the elements form the map stored in a collection.
Thus,wecanprocessthecontentsofamapasacollection,ifyouchoose.
Thecollectionmechanismwasretrofittedtosomeoftheoriginalclassesdefined
byjava.utilpackage,sothattheytoocouldbeintegratedintothenewsystem.
Itisimportanttounderstandthatalthoughtheadditionofcollectionsalteredthe
architecture of many of the original utility classes, it did not cause the
deprecation of any. Collections simply provide a better way of doing several
things.
TheCollectionInterfaces:
Thecollections framework defines several interfaces. The concrete classes
simply provide different implementations of the standard interfaces. The interfaces that
underpincollectionsare:
Collection
Enableyoutoworkwithgroupofobjects;itisatthetopofthecollectionshierarchy.
List
Extendscollectiontohandlesequences(listsofobjects).
Set
Extendscollectiontohandlesets,whichmustcontainuniqyeelements.
SortedSet
Extendscollectiontohandlesortedsets.
In addition to the collection interfaces, collections also use the Comparator,
Iterator and RandomAccess interfaces. The comparator defines how two objects are
compared;IteratorandListIteratorenumeratetheobjectswithinacollection.
By implementing RandomAccess, a list indicates that it supports efficient,
randomaccesstoitselements.Toprovidethegreatestflexibilityintheiruse,thecollection
interfacesallowsomemethodstobeoptional.
The optional methods enable you to modify the contents of a collection.
Collectionsthatsupportthesemethodsarecalledmodifiable.Collectionsthatdonotallow
theircontentstobechangedarecalledunmodifiable.
Ifanattemptismadetouseoneofthesemethodsonanunmodifiablecollection
anUnsupportedOperationExceprinisthrown.Allthebuilt-incollectionsaremodifiable.
TheIteratorInterface:Iteratorinterfacedefinesthefollowingmethods:
Boolean hasNext()
returnstrueiftheiterationhasmoreelements.
Object next()
returnsthenextelementintheiteration.
void remove()
Removesfromtheunderlyingcollectionthelastelementreturnedbythe
iterator(maynotallowtodosoinsomecircumstancesasinEJB’s).itis
anoptionaloperation,soitmaythrowUnsupportedOperationException,
ifiteratordoesnotsupportthisoperation.
Iteratorsdifferfromenumerationsintwoways:
Iterators allow the caller to remove elements from the underlying collection
duringtheiterationwithwell-definedsemantic.
Methodnameshavebeenimproved.
TheListIteratorInterface:
ThisisasubinterfaceofIterator.
publicinterfaceListIteratorextendsIterator
Itisaniteratorforliststhatallowstheprogrammertotraverse4thelistineither
direction,modifythelistduringiteration,andobtaintheiteator’scurrentpositioninthe
list.
Methodsummary:
voidadd(Objectobj)
Insertsthespecifiedelementintothelist(optionaloperation).
booleanhasNext()
Returnstrueifthislistiteratorhasmoreelementswhentraversingthelistintheforward
direction.
booleanhasPrevious()
Returnstrueifthislistiteratorhasmoreelementswhentraversingthelistinthereverse
direction.
Objectnext()
Returnthenextelementinthelist.
intnextIndex()
Returnstheindexiftheelementthatwouldbereturnedbyasubsequentcalltonext.
Objectprevious()
Returnthepreviouselementinthelist.
intpreviousIndex()
Returns the index if the element that would be returned by a subsequent call to
previous.
voidremove()
Removefromthelistthelastelementthatwasreturnedbynextorprevious(optional
operation).
voidset(Objectobj)
Replaces the last element returned by next or previous with the specified element
(optionaloperation).
RandomAccessInterface:
Thisis amarker interfaceused byList implementto indicatethat theysupport
randomaccess.TheArrayListandVectorimplementthisinterface.
TheComparatorInterface:
Comparators are used to control the order of certain data structures(such as TreeSet of
TreeMap).
Methods:
Int compare(Objecto1,Objecto2)
Comparesitstwoargumentsfororder.
Boolean equal(Objectobj)
Indicatewhathersomeotherobjectis“equalto”thisComparator.
TheCollectionInterface:
Thecollectioninterfaceisthefoundationuponwhichthecollectionsframework
isbuilt.Itdeclaresthecoremethodsthatallcollectionswillhave.Becauseallcollections
implement collection interface, familiarity with its methods is necessary fir a clear
understanding of the framework. Several if thse methods can throw an
UnsupportedOperationException. A ClassCastException is generated when one object is
incompatiblewithanother,suchaswhenanattemptismadetoaddanincompatibleobject
toacollection.
MethodsintheCollectionInterface:
booleanadd(Objectobj)
Ensures that this collection contains the specified element (optional operation). Adds
object to the invoking collection. Returns trueif ekement obj was added to the
collection.Returnsfalseifelementobjiosalreadyamemberofthecollectionandthe
collectiondoesnotallowduplicate.
booleanaddAll(Collectionc)
Addsalloftheelementsinthespecifiedcollectiontothiscollection(optionaloperation)
voidclear()
Removesalliftheelementfromthiscollection(optionaloperation).
booleancontain(Objecto)
Returntrueifthiscollectioncontainsthespecifiedcollection.
booleancontainAll(Collectionc)
Returntrueifthiscollectioncontainsalloftheelementsinthespecifiedcollection.
booleanequal(Objecto)
Comparesthespecifiedobjectwiththiscollectionforequality.
inthashCode()
Returnsthehashcidevalueforthiscollection.
booleanisEmpty()
Returnstrueifthiscollectioncontainsnoelements.
Iteratoriterator()
Returnsaniteratorovertheelementsinthiscollection.
booleanremove(Objecto)
Removesasingleinstanceofthespecifiedelementfromthiscollection,ifitispresent
(optionaloperation)
booleanremoveAll(Collectionc)
Removesall the elementthat are alsocontained in thespecified collection(optional
operation)
booleanretainAll(Collectionc)
Retains the element of this collection that are contained in the specified collection
(optionaloperation).
intsize()
Returnsthenumberofelementsinthiscollection.
Object[]toArray()
Returnsanarraycontainingalloftheelementsinthiscollection.
Two collections can be compared for equalityby calling equals() method. The
precisemeaningof“equality”maydifferfromcollectiontocollection.
For example, you can implement equals() so that it compares the values of
elemensstoredinthecollection. Alternatively,equals() cancompare referencestothese
elements.
TheListInterface:
Alistisanorderedcollectionaksiknownassequence.TheListinterfaceextends
Collectionanddeclaresthebehaviorofacollectionthatstoresasequenceofelements.
Elements can be inserted or accessed by their position in the list, using a zero
basedindex.Alistmaycontainduplicateelements.Inadditiontothemethodsdefiedby
collection,Listdefinessomeofitsown.
MethodsintheListInterface:
booleanadd(Objecto)
Appendsthespecifiedelementtotheendofthislist(optionaloperation).Themethodis
defined in the Collection interface but as part of the List interface it should be
implementedsoastoalwaysaddtheelementattheendofthelist.
voidadd(intindex,Objectelement)
Insertsthe specified elementatthe specified positionin this list(optional operation).
Any pre-existing elements at or beyond the point of insertion are sifted up. Thus, no
elementsareoverwritten.
booleanaddAll(Collectionc)
Appendsalloftheelementinthespecifiedcollectiontotheendofthislist,intheorder
that thet are returned by the specified collections iterator(optional operation). The
methodisdefinedintheCollectioninterfacebutaspartoftheListinterfaceitshouldbe
implementedsoastoalwaysaddtheelementattheendofthelist.
booleanaddAll(intindex,Collectionc)
inserts all of the elements in the specified collection into this list at the specified
position(optionaloperation).Returnstrueiftheinvokinglistchangesandreturnsfalse
otherwise.
booleanaddAll(intindex,Collectionc)
Inserts all of the elements in the specified collection into this list at the specitied
position(optionaloperation).Returnstrueiftheinvokinglistchangesandreturnsfalse
otherwise.
Objectget(intindex)
Returnstheelementatthespecifiedpositioninthislist.
intindexOf(Objecto)
Returnstheindexinthislistofthefirstoccurrenceofthespecifiedelement,or-1iflist
doesnotcontaintheelement.
intlastIndexOf(Objecto)
Returnstheindexinthislistofthelastoccurrenceofthespecifiedelement,or-1iflist
doesnotcontaintheelement.
ListIteratoriterator()
Returnsalistiteratorofelementsinthislist(inpropersequence).
ListIteratoriterator(intindex)
Returns a list iterator of elements in this list (in proper sequence), starting at the
specifiedpositioninthislist.
Objectremove(intindex)
Removestheelementsatthespecifiedposition(optionaloperation)andreturnsdeleted
element.Theresultinglistiscompacted.Thatis,theindexesofsubsequentelementare
decrementedbyone.
Objectset(intindex,Objectelement)
Replaces the element at the specified position in this list with the specified element
(optionaloperation).
ListsubList(intfromIndex,inttoIndex)
Returnsalistthatincludeselementsfromstarttoend-1intheinvokinglist.Elementsin
thereturnedlistarealsoreferencedbytheinvokingobject.
Note:thatseveralofthesemethodswillthrowanUnsupportedOperationExceptionifthe
collectioncannotbemodified,andaClassCastExceptionisgenerated,whenanobjectis
incompatibleobjecttoacollection.
Semantics of add(Object o) and addAll(Collection c) methods defined by collection
interfaceischangedbylistsothattheyaddelementstotheendofthelist.
TheSetinterface:
TheSetinterfacedefinesaset.ItextendsCollectionanddeclaresthebehaviorof
acollectionthatdoesnotallowduplicateelements.
Therefore,add()methodreturnfalseifanattemptismadetoaddduplicateelementstoa
set.Itdoesnotdefineanyadditionalmethodsofitsown.
TheSortedSetInterface:
TheSortedSetinterfaceextendsSetanddeclaresthebehaviorofasetsortedinascending
order.
Comparatorcomprator()
Returns the coparator associated with this sorted set, or null if it uses its elements
naturalordering.
Objectfirst()
Returnthefirstelementinthissortedset.
SortedSetheadSet(ObjecttoElement)
Returns a view of the portion of this sorted set whose elements are strictly less than
toElement.
Objectlast()
Returnsthelastelementinthissortedset.
SortedSetsubSet(ObjectfromElement,ObjecttoElement)
Returns a view of the portion of this sorted set whose elements range from
fromElement,inclusive,totoElement,exclusive.
SortedSettailSet(ObjectfromElement)
Returnsaviewoftheportionofthissortedsetwhoseelementsaregreaterthanorequal
tofromElement.
Several methods throw a NoSuchElementException when no items array
contained in the invoking set. A ClassCastException is thrown when an object is
incompatiblewiththeelementsinaset.ANullPointerExceptionisthrownifanattempt
ismadetouseanullobjectandnullisnotallowedintheset.
CollectionClasses:
Someof thecollection classesprovede fullimplementationthatcan used asis.
Othersareabstract,providingskeletonimplementationthatareusedasstartingpointsfor
creatingconcretecollection
Noneofthecollectionclassesaresynchronizedversions.
Thestandardcollectionclassesare:
AbstractCollectionImplementsmostoftheCollectioninterface.
AbstractListExtendsAbstractCollectionandimplementmostoftheListinterface.
AbstractSequenceListExtendsAbstractListforusebyacollectionthatusessequential
ratherthanrandomaccessofitselements.
AbstractSetExtendsAbstractCollectionandimplementstheSetinterface.
LinkedListImplementsalinkedlestbyextendingAbsractSuquentialList.
ArrayList Impelments a dynamic array by extending AbstractList. It uses random
accessofelements.
HashSetExtendAbstractSetforusewithahashtable.
LinkedHashSetExtendsHashSettoallowinsertion-orderiterations.
TreeSetExtendsAbstractSetandimplementSortedSetinterface.Itusesbinarysearch
treetostoreelementsinsortedorder.
Note:- In addition to collection classes, several legacy classes, such as Vector Stack,
Hashtablehavebeenreengineeredtosupportcollections.
AccessinganCollectionviaIteratorandListIterator:
Often, you will want to cycle through the elements in a collection. By far, the
easiestwaytodothisistoemployaniterator,anobjectthatimplementseithertheIterator
ortheListIteratorinterface.
Iterator enables you to cycle through a collection obtaining or removing elements.
ListIteratorextendsIteratortoallowbi-directionaltraversalofalist,andthemodification
ofelements.
Beforeyoucanaccessacollectionthroughaniterator,youmustobtainone.Each
ofthecollectionclassesprovidesaniterator()methodthatreturnsaniteratortothestarof
thecollection.Byusingthisiteratorobject,youcanaccesseachelementinthecollection,
oneelementatatime.
For collections that implement List, you can also obtain an iterator by calling
ListIterator. A list iterator gives you the ability to access the collection in either the
forwardorbackwarddirectionandyoucanmodifyanelement.Otherwise,ListIteratoris
usedjustlikeIterator.
ArrayListClass:
TheArrayListclassextendsAbstractListandimplementstheListinterface.The
ArrayListsupportsdynamicarraysthatcangrowasneeded.Injava,standardarrayareof
afixedlength.
Afterarraysarecreated,theycannotgroworshrink,whichmeansthatwemust
knowinadvancehowmanyelementsanarraywillhold.But,sometimes,wedon’tknow
sizeofanarrayuntilrun-time.Tohandlethissituation,thecollectionsframeworkdefines
ArrayList.
AnArrayListisavariable-lengtharrayofobjectreferencesthatis,anArrayList
candynamicallyincreaseordecreaseinsize.Arraylistsarecreatedwithaninitialsize.
Whenthesizeisexceeded,thecollectionisautomaticallyenlarged,whenobjects
are removed, the array may shrunk. Using generics feature introduced in J2SE 5, it is
possibletorestrictthetypeofelementstobeaddedintheArrayList.
Note:-ThelegacyclassVectoralsosupportsdynamicarrays.
Constructors&MethodsofArrayListclass:
publicArrayList(int);
Constructs an empty list with the specified initial capacity. The capacity grows
automaticallyaselementsareaddedtoanarraylist.
publicArrayList();
Constructsanemptylistwithaninitialcapacityoften.
publicArrayList(Collection);
Constructsalistcontainingtheelementsofthespecifiedcollection.Intheorderthey
arereturnedbythecollection’sIterator.
publicvoidtrimToSize();
Conversely, if we want to reduce the size of the array that underlines an ArrayList
objectsothatitispreciselyaslargeasthenumberofitemsthatitiscurrentlyholding
calltrimTosize()method.
publicvoidensureCapacity(int);
Although the capacity of an ArrayList object increases automatically as objects are
stored in it, we can increase the capacity of an ArrayList object manually by calling
ensureCapacity()method.Byincreasingitscapacityonce,atthestart,wecanprevent
severalreallocationlater.Becausereallocationarecostlyin termsoftime,preventing
unnecessaryonesimprovesperformance.
publicintsize();
publicBooleanisEmpty();
publicObjectclone();
publicObject[]toArray();
ObtaininganarrayfromanArrayListwhenworkingwithArrayList,wewillsometimes
wanttoobtainanactualarraythatcontainthecomtentsifthelist.Wecandothisby
callingtoArray()method.
Severalreasonsexistwhywemightwanttoconvertacollectionintoanarraysuchas:
Toobtainfasterprocessingtimesforcertainoperations.
Topassanarraytoamethodthatisnotoverloadtoacceptacollection.
To integrate our newer, collection-based code with legacy code that does not
understandcollection.
publicObject[]toArray(Object[]);
publicObjectget(int);
publicObjectset(int,Object);
publicbooleanadd(Object);
publicvoidadd(int,Object);
publicObjectremove(int);
publicbooleanremove(Object);
publicvoidclear();
publicbooleanaddAll(Collection);
publicbooleanaddAll(int,Collection);
publicbooleancontains(Object);
publicintindexOf(Object);
publicintlastIndexOf(Object);
Example21.1
1.importjava.util.*;
2.classArrayListTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.ArrayLista1=newArrayList();//canstoredifferenttypeofobjectscapacityis10
7.System.out.println(“Initialsizeofa1:“+a1.size());
8.a1.add(“A”);
9.a1.add(“C”);
10.a1.add(newInteger(56));
11.a1.add(“E”);
12.a1.add(“F”);
13.a1.add(1,“B”);
14.System.out.println(“Sizeofa1afteradditions:“+a1.size());
15.System.out.println(“Contentsofa1:“+a1);
16.a1.remove(“F”);
17.a1.remove(2);
18.System.out.println(“Sizeofa1afterdeletions:“+a1.size());
19.System.out.println(“Contentofa1“+a1);
20.ArrayList<String>a2=newArrayList<String>(20);
21.//canaddonlyStringobjectscapacityis20
22.a2.ensureCapacity(25);//increasethecapacityfrom20to25.
23.a2.ensureCapacity(22);//capacitywillnotchangeasalreadymorethan
24.a2.add(“A”);
25.a2.add(“B”);
26.a2.add(“C”);
27.a2.add(“D”);
28.a2.add(“E”);
29.//a2.add(newInteger(5));//willnotcompile
30.System.out.println(“Contentsofa2:“+a2);
31.a2.remove(“D”);
32.System.out.println(a2);
33.a2.remove(0);
34.System.out.println(a2);
35.a2.clear();
36.System.out.println(a2);
37.
38.ArrayList<Integer>a3=newArrayList<Integer>();//canaddonlyIntegerobjects
39.a3.add(newInteger(1));
40.a3.add(newInteger(2));
41.a3.add(newInteger(3));
42.a3.add(4);//AutoBoxing
43.System.out.println(“Contentsofa3:“+a3);
44.for(inti=0;i<a3.size();i++)
45.System.out.print(a3.get(i)+”“);
46.System.out.println();
48.Objectb[]=a3.toArray();
49.for(inti=0;i<b.length;i++)
50.System.out.print((Integer)b[i]+”“);
51.System.out.println();
52.System.out.println(“Contentsofa3usingiterator:“);
53.Iteratoritr=a3.iterator();
54.while(itr.hasNext())
55.{
56.intx=((Integer)itr.next()).intValue();
57.System.out.print(x+”“);
58.}
59.System.out.println();
60.
61.//ChangingthelistusingListIterator
62.ListIterator<Integer>litr=a3.listIterator();
63.while(litr.hasNext())
64.{
65.Integerelement=litr.next();
66.litr.set(element+10);
67.}
68.
69.//PrintingthelistinreverseOrderwillworkonlyafterreachingtheend.
70.while(litr.hasPrevious())
71.{
72.Integerelement=litr.previous();
77.System.out.print(element+”“);
74.}
75.System.out.println();
76.System.out.println(“Contentsofa3usingforeachloop”);
77.for(inti:a3)//AutoUnboxing
78.System.out.print(i+”“);
79.System.out.println();
80.
81.Integeria[]=newInteger[a3.size()];
82.a3.toArray(ia);
83.intsum=0;
84.for(inti=0;i<ia.length;i++)
85.sum=sum+ia[i].intValue();
86.System.out.println(“Sumis”+sum);
87.a3.trimToSize();
88.}
89.}
Output:
Initialsizeofa1:0
Sizeofa1afteradditions:6
Contentsofa1:[A,B,C,56,E,F]
Sizeofa1afterdeletions:4
Contentofa1[A,B,56,E]
Contentsofa2:[A,B,C,D,E]
[A,B,C,E]
[B,C,E]
[]
Contentsofa3:[1,2,3,4]
1234
1234
Contentsofa3usingiterator:
1234
14131211
Contentsofa3usingforeachloop
11121314
Sumis50
TheLinkedListClass:
The LinkedList class extends AbstractSequentialList and implements the List interfaces. It provides a
linked-listdatastructure.
Constructors&Methods
publicLinkedList();
Constructsanemptylist.
publicLinkedList(Collection);
Constructsalistcontainingtheelementsifthespecifiedcollection,intheordertheyare
returnedbythecollection’sIterator.
publicObjectgetFirst();
publicObjectgetLast();
publicObjectremoveFirst();
publicObjectremoveLast();
publicvoidaddFirst(Object);
publicvoidaddLast(Object);
publicbooleancontains(Object);
publicintsize();
publicbooleanadd(Object);
publicbooleanremove(Object);
publicbooleanaddAll(Collection);
publicbooleanaddAll(int,Collection);
publicvoidclear();
publicObjectget(int);
publicObjectset(int,Object);
publicvoidadd(int,Object);
publicObjectremove(int);
publicintindexOf(Object);
publicintlastIndexOf(Object);
publicObjectelement();
publicObjectremove();
publicbooleanremoveFirstOccurrence(Object);
publicbooleanremoveLastOccurrence(Object);
publicListIteratorlistIterator(int);
publicIteratordescendingIterator();
publicObjectclone();
publicObject[]toArray();
publicObject[]toArray(java.lang.Object[]);
Example21.2
1.importjava.util.*;
2.classLinkedListTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.//Createalinkedlist.
7.LinkedList<String>l1=newLinkedList<String>();
8.
9.//Addelementstothelinkedlist.
10.l1.add(“F”);
11.l1.add(“B”);
12.l1.add(“D”);
13.l1.add(“E”);
14.l1.add(“C”);
15.l1.addLast(“Z”);
16.l1.addFirst(“A”);
17.l1.add(1,“A2”);
18.System.out.println(“OriginalContentsofl1:“+l1);
20.//Removeelementfromthelinkedlist.
21.l1.remove(“F”);
22.l1.remove(2);
23.System.out.println(“Contentsofl1afterdeletion:”+l1);
25.//Removethefirstandlastelements.
26.l1.removeFirst();
27.l1.removeLast();
28.System.out.println(“l1afterdeletingfirstandlast:”+l1);
30.//Getandsetavalue.
31.Stringval=l1.get(2);
32.l1.set(2,val+“Changed”);
33.System.out.println(“l1afterchange:”+l1);
35.Iteratoritr=l1.descendingIterator();
36.while(itr.hasNext())
37.{
38.System.out.println(itr.next());
39.}}}
Output:-OriginalContentsofl1:[A,A2,F,B,D,E,C,Z]
Contentsofl1afterdeletion:[A,A2,D,E,C,Z]
l1afterdeletingfirstandlast:[A2,D,E,C]
l1afterchange:[A2,D,EChanged,C]
C
EChanged
D
A2
Note-BecauseLinkedListimplementstheList interface,calltoadd(Objectobj) append
itemstotheendofthelist,asdocallstoaddLast().Toinsertitemsataspecificlocation
usetheadd(intindex,Objectobj)formofadd.
TheHashSetClass:
The HashSet class extends AbstractSet and implements the Set interface. It
createsacollectionthatusesahashtableforstorage
Theadvantageofhashingisthatitallowstheexecutiontimeofbasicoperations,
suchasadd(),contains(),remove(),andsize()toremainconstantevenforlargesets.
Constructors&OtherMethods:
HashSet()
Constructs a new, empty set, the backing HashMap instance has default initial
capacity(16)andloadfactor(0.75).
HashSet(Collectionc)
Constructsanewsetcontainingtheelementsinthespecifiedcollection.
HashSet(intinitialCapacity)
Constructsanew,emptyset,thebackingHashMapinstancehasspecifiedinitialcapacity
andloadfactorwhichis0.75.
HashSet(intinitialCapacity,floatfillRatio)
Constructsanew,emptyset,thebackingHashMapinstancehasspecifiedinitialcapacity
andthespecifiedloadfactor.Thefillratiomustbebetween0.0and1.0
publicjava.util.Iteratoriterator();
publicintsize();
publicbooleanisEmpty();
publicbooleancontains(java.lang.Object);
publicbooleanadd(java.lang.Object);
publicbooleanremove(java.lang.Object);
publicvoidclear();
publicjava.lang.Objectclone();
TheHashSetdoesnotguaranteetheorderofitselements,becausetheprocessof
hashing does not usually lend itself to the creation of sorted sets. If you need sorted
storage,thenanothercollectionsuchasTreeSet,isabetterchoice.
Example21.3
1.importjava.util.*;
2.classHashSetTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.HashSet<String>hs=newHashSet<String>();
7.hs.add(“B”);
8.hs.add(“A”);
9.hs.add(“E”);
10.hs.add(“C”);
11.hs.add(“F”);
12.System.out.println(hs);
13.}
14.}
Output:
[E,F,A,B,C]
Theelementsarenotstoredinsortedorder,andthepreciseoutputmayvery.
TheLinkedHashSetClass:
TheLinkedHashSetclassextendsHashSetandaddsnomembersofitsown.The
LinkedHashSetclassmaintainsalinkedlistoftheentriesintheset,intheorderinwhich
theywereinserted.
This is also the order in which they are contained in the string returned by
toString() method when called on a LinkedHashSet object. To see the effect of
LinkedHashSet, try substituting LinkedHashSet for HashSet in the preceding program.
Theoutputwillbe:[B,A,E,C,F]Whichistheorderinwhichtheelementswereinserted.
TheTreeSetClass:
TheTreeSetprovidesanimplementationoftheSetinterfacethatusesatreefor
storage.Objectsarestoredinsorted,ascendingorder.Accessandretrievaltimesarequite
fast, which makes TreeSet an excellent choice when storing large amounts of sorted
informationthatmustbefoundquickly.
Constructors
Ithasthefollowingconstructors:
TreeSet()
Constructsanew,emptyset,sortedaccordingtotheelementsnaturalorder.
TreeSet(Collectionc)
Constructs a new set containing the elements in the specified collection sorted
accordingtotheelements’naturalorder.
TreeSet(Comparatorc)
Constructsanew,emptyset,sortedaccordingtothecomparator.
TreeSet(SortedSetss)
Constructsanewsetcontainingtheelementsinthespecifiedsortedaccordingto
thesameordering.
publicjava.util.Iteratoriterator();
publicjava.util.IteratordescendingIterator();
publicintsize();
publicbooleanisEmpty();
publicbooleancontains(java.lang.Object);
publicbooleanadd(java.lang.Object);
publicbooleanremove(java.lang.Object);
publicvoidclear();
publicbooleanaddAll(java.util.Collection);
publicjava.lang.Objectclone();
Example21.4
1.importjava.util.*
2.classTreeSetTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.TreeSet<String>hs=newTreeSet<String>();
7.ts.add(“C”);
8.ts.add(“A”);
9.ts.add(“D”);
10.ts.add(“E”);
11.ts.add(“F”);
12.ts.add(“B”);
13.System.out.println(ts);
14.}
15.}
Output:[A,B,C,D,E,F]
Both TreeSet and TreeMap store elements in sorted order. However, it is the
comparatorthatdefinespreciselywhat“sortedorder”means.
By default, these classes store their elements by using what java refers to as
“naturalordering”,whichisusuallytheorderingthatwewouldexpect.Ifwewanttoorder
elementsinadifferentway,thenspecifyacomparatorobjectwhenyouconstructthesetor
map. Doing so gives us the ability to govern precisely how elements are stored within
sortedcollectionsmaps.
The comparator interface defines two methods: compare() and equals () as
discussedearlier.Thecompare()method,comparestwoelementsfororder:
intcompare(Tobj1,Tobj2)
obj1andobj2aretheobjectstobecompared.
Thismethodreturnszeroiftheobjectsareequal.
Itreturnsapositivevalueifobj1isgreaterthanobj2.
Itreturnsanegativevalueifobj1islessthanobj2.
ThemethodscanthrowaClassCastExceptionifthetypeofobjectsarenotcompatiblefor
comparison.
Byoverridingcompare(),youcanalterthewaythatobjectsareordered.
For example, to sort in reverse order, you can create a comparator that reverses the
outcomeofacomparison.
Theequals()method,testswhetheranobjectequaltheinvokingcomparator.
booleanequals(Objectobj)
Example21.5
1.importjava.util.*;
2.classCompTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.TreeSetts=newTreeSet(newMyComp());
7.ts.add(“C”);
8.ts.add(“A”);
9.ts.add(“D”);
10.ts.add(“E”);
11.ts.add(“F”);
12.ts.add(“B”);
13.//Displaytheelements.
14.Iteratori=ts.iterator();
15.while(i.hasNext())
16.{
17.Objecto=i.next();
18.System.out.println(o+“”);
19.}
20.}
21.}
22.classMyCompimplementsComparator
23.{
24.publicintcompare(Objecta,Objectb)
25.{
26.StringaStr,bStr;
27.aStr=(String)a;
28.bStr=(String)b;
29//Reversethecomparison.
30.returnbStr.compareTo(aStr);
31.}
32.}
Output:FEDCBA
WorkingwithMaps:
Amapisanobjectthatstoresassociationsbetweenkeysandvalues,orkey/value
pairs.Givenakey,wecanfinditsvalue.
Bothkeysandvaluesareobjects.Thekeysmustbeunique,butthevaluemaybe
duplicated.Somemapscanacceptanullkeyandnullvalues,othercannot
MapInterfaces:
Mapclassesbasedonthefollowinginterfaces:
MapMapsuniquekeystovalues.
Map.EntryDescribesanelement(akey/valuepair)inamap.
SortedMapExtendsMapsothatthekeysaremaintainedinascendingorder.
TheMapInterface:
TheMapinterfacemapsuniquekeystovalues.Givenakeyandvalueyoucanstorethe
valueinaMapobject.Afterthevalueisstored,youcanretrieveitbyusingitskey.
Methodsummary:
voidclear()
Removesallmappingsfromthismap(optionaloperation).
booleancontainsKey(Objectkey)
Returnstrueifthismapcontainsamappingforthespecifiedkey.
booleancontainsValue(Objectvalue)
Returnstrueifthismapmapsoneormorekeystothespecifiedvalue.
SetentrySet()
Returns a set that contains the entries in the map. The set contains objects of type
Map.Entry.thismethodprovidesasetviewoftheinvokingmap.
booleanequals(Objecto)
ReturnstrueifoisMapandcontainstheentries,otherwise,returnsfalse.
Objectget(Objectkey)
Returnsthevaluetowhichthismapmapsthespecifiedkey.
inthashCode()
Returnsthehashcodevalueforthismap.
booleanisEmpty()
Returnstrueifthismapcontainsnokey-valuemappins.
SetkeySet()
Returnsasetviewofthekeyscontainedinthismap.
Objectput(Objectkey,Objectvalue)
Associatesthe specifiedvalue with thespecified keyin this map(optionaloperation),
overwritinganypreviousvalueassociatedwiththekey.Retrunsnullifthekeydidnot
alreadyexist.Otherwise,theperviousvaluelinkedtothekeyisreturned.
voidputAll(Mapm)
Copiesallofthemappingsfromthespecifiedmaptothismap(optionaloperation).
Objectremove(Objectkey)
Removesthemappingforthiskeyfromthismapifitispresent(optionaloperation).
intsize()
Returnsthenumberofkey-valuemappingsinthismap.
Collectionvalues()
Returnsacollectionviewofthevaluescontainedinthismap.
SeveralmethodsthrowaNoSuchElementExceptionwhennoitemsexistinthe
invokingmap.AClassCastExceptionisthrownwhenanobjectisincompatiblewiththe
elementsinamap.
ANullPointerExceptionisthrownifanattemptismadetouseanullobjectand
nullisnotallowedintheMap.AnUnsupportedOperationExceptionisthrownwhenan
attemptismadetochangeanunmodifiablemap.
Mapresolvearoundtwobasicoperationsget()andput().
MapsarenotcollectionsbecausetheydonotimplementtheCollectioninterface,
butwecanobtainacollection-viewofthemap.Collection-viewmeansbywhichmapsare
integratedintothecollectionsframework..
TheSortedMapInterface:
TheSortedMapinterfaceextendsMap.Inensuresthattheentriesaremaintained
inascendingorder.
MethodSummary:
Comparatorcomparator()
Returns the xomparator associated with this sorted map, or null if it uses its keys’
naturalordering.
ObjectfirstKey()
Returnsthefirstkeyinthissortedmap.
SortedMapheadMap(ObjecttoKey)
ReturnsaviewoftheportionofthissortedmapwhosekeysarestrictlylessthantoKey.
ObjectlastKey()
Returnsthelastkeyinthissortedmap.
SortedMapsubMap(ObjectfromKey,ObjecttoKey)
Returnsaviewoftheportionofthissortedmapwhosekeysaregreaterthanequaltoto
Key.,exclusive
SortedMaptailMap(ObjectfromKey)
Returnsaviewoftheportionofthissortedmapwhosekeysaregreaterthanorequalto
fromKey.
SeveralmethodsthrowaNoSuchElementExceptionwhenno itemsarein theinvoking
map.AClassCastExceptionisthrownwhenanobjectisincompatiblewiththeelements
inamap.
ANullPointerExceptionisthrownifanattemptismadetouseanullobjectand
nullisnotallowedintheMap.
TheMap.EntryInterface:
TheMap.Entryinterfaceenablesyou toworkwithamapentry.Recallthat the
entrySet()methoddeclaredbytheMapinterfacereturnsasetcontainingthemapentries.
EachofthesesetelementsisaMap.Entryobject.
MethodSummary:
booleanequals(Objecto)
Compares the specified object with this entry for equality. Returns true if o is a
Map.Entryobject,whosekeyandvalueareequaltothatoftheinvokingobject.
ObjectgetKey()
Returnsthekeycorrespondingtothisentry.
ObjectgetValue()
ReturnstheValuecorrespondingtothisentry.
inthashCode()
Returnsthehashcodevalueforthismapentry.
ObjectsetValue(Objectvalue)
Replaces the value corresponding to this entry with the specified value (optional
operation). A ClassCastException is thrown if value is not of the correct type of the
map.
ANullPointerExceptionisthrownifvalueisnullandthemapdoesnotpermitnullkey.
AnUnsupportedOperationExceptionisthrownifthemapcannotbechanged.
TheMapclasses:
Severalclassesprovideimplementationofthemapinterfaces.
AbstractMapThis classprovidesa skeletonimplementation ofthe map interface,to
minimizetheeffortsrequiredtoimplementthisinterface.
HashMapHashtablebasedimplementationofthemapinterface.ExtendsAbstractMap
class.
TreeMapExtendsAbstractMapandimplementsSortedMapinterfacetouseatree.
LinkedHashMapExtendsHashMaptoallowinsertion-orderiteration.
AbstractMapisasuperclassforallconcretemapimplementations.
TheHashMapclass:
TheHashMapclassusesahashtabletoimplanttheMapinterface.Thisallows
theexecutiontimeofbasicoperations,suchasget()andput()toremainconstantevenfor
largesets.
Constructors:
TheHashMaphasthefollowingconstructors:
HashMap()
Constructs an empty HashMap with the default capacity(16) and default load
factor(0.75)
HashMap(intinitialCapacity)
ConstructsanemptyHashMapwiththespecifiedinitialcapacityanddefaultload
factor(0.75)
HashMap(Mapm)
ConstructanewHashMapwiththesamemappingasthespecifiedMap.
The HashMap class extends AbstractMap and implements Map. It does not add any
methodsofitsown.Youshouldnotethatahashmapdoesnotguaranteetheorderofits
elements.
Example21.6
1.importjava.util.*;
2.classHashMapTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.HashMap<String,Integer>hm=newHashMap<String,Integer>();
7.hm.put(“C”,1000);
8.hm.put(“C++”,1000);
9.hm.put(“Java”,1500);
10.Sets=hm.entrySet();
11.Iteratoritr=s.iterator();
12.while(itr.hasNext())
13.{
14.Map.Entryme=(Map.Entry)itr.next();
15.System.out.print(me.getKey()+“:”);
16.System.out.println(me.getValue());
17.}
18.System.out.println();
19.intfees=((Integer)hm.get(“Java”)).intValue();
20.hm.put(“Java”,fees+1000);
21.System.out.println(“NewFeesofJava:”+hm.get(“Java”));
22.}
23.}
Output:C:1000
C++:1000
Java:1500
NewFeesofJava:2500
TheTreeMapclass:
TheTreeMapclassimplementstheMapinterfacebyusingatree.ATreeMapprovides
anefficientmeansofstoringkey/valuepairinsortedorder,andtreemapguaranteesthat
itselementswillbesortedinascendingkeyorder.
Constructors:
TheTreeMaphasthefollowingconstructors:
TreeMap()
Constructsanemptymap,sortedaccordingtothekey’snaturalorder.
TreeMap(Comparatorc)
Constructsanew,emptymap,sortedaccordingtothegivencomparator.
TreeMap(Mapm)
Constructanewmapwithcontainingthesamemappingasthegivenmap,sorted
accordingtothekeys’naturalorder.
TreeMap(SortedMapm)
ConstructanewmapwithcontainingthesamemappingasthegivenSortedMap,
sortedaccordingtothesameordering.
TreeMap implements SortedMap and extends AbstradtMap. It does not define any
additionalmethodsofitsown.
Example21.7
ThefollowingprogramreworkstheprecedingexamplesothatitusesTreeMap.Thekeys
willbesortedbyfirstname.itispossibletoalterthisbehaviorbyspecifyingacomparator
when the map is created, so that keys may be sorted on last name or any other desired
order.
1.importjava.util.*;
2.classTreeMapTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.TreeMap<String,Integer>tm=newTreeMap<String,Integer>();
7.tm.put(“C”,1000);
8.tm.put(“C++”,1000);
9.tm.put(“Java”,1500);
10.Set<Map.Entry<String,Integer>>s=tm.entrySet();
11.for(Map.Entry<String,Integer>me:s)
12.{
13.System.out.print(me.getKey()+“:”);
14.System.out.println(me.getValue());
15.}
16.System.out.println();
17.intfees=tm.get(“Java”);
18.tm.put(“Java”,fees+1000);
19.System.out.println(“NewfeesofJava:”+tm.get(“Java”));
20.}
21.}
Output:
C:1000
C++:1000
Java:1500
NewfeesofJava:2500
TheLinkedHashMapClass:
Java2,version1.4addstheLinkedHashMapclass.ThisclassextendsHashMap.
LinkedHashMap maintains a linked list of the entries in themap, in the order in which
theywereinserted.
This allows insertion-order iteration over the map. That is, when iterating a
LinkedHashMap,theelementswillbereturnedintheorderinwhichtheywereinserted.
LegacyClassesandInterfaces
The original version of java.util did not include the collection framework.
Instead, it defined several classes and an interface that provided an ad hoc method of
storingobject. With theaddition ofCollection by Java2, severalofthe originalclasses
werereengineeredtosupporttheCollectioninterfaces.
Thus, they are fully compatible with the framework. While no classes have
actuallybeendeprecated,onehasbeenobsolete.Ofcourse,whereacollectionduplicates
thefunctionalityoflegacyclass,youwillusuallywanttousethecollectionfornewcode.
Ingeneral,thelegacyclassesaresupportedbecausethereisstillcodethatusesthem.
Someofthecollectionclassesaresynchronized,butallthelegacyclassesare
synchronized.Thisactionmaybeimportantinsomesituations.Ofcourse,wecaneasily
synchronizecollectionstoo.
TheEnumerationInterface:
Enumerationinterfacedefinesthemethodsbywhichyoucanenumerate(obtain
one at a time) the elements in a collection of objects. The legacy interface has been
supercededbyIterator.
Although not deprecated, Enumeration is considered obsolete for new code.
However, it is used by several methods used by legacy classes (such as Vector and
Properties), is used by several other API classes, and is recently in wide spread use in
applicationcode.
Enumerationspecifiersthefollowingtwomethods:
BooleanhasMoreElements()
Testsifthisenumerationcontainsmoreelements.Thismethodmustreturntrue
whiletherearestillmoreelementstoextract.Andfalsewhenalltheelementshavebeen
enumerated.
ObjectnextElement()
Returns the next element of this enumeration if this enumeration object has at
leastonemoreelementtoprovide.
TheVectorclass
Vector implements a dynamic array. It is similar to ArrayList, but with two
differences:
Vectorissynchronized,andVectorcontainsmanylegacymethodsthatarenotpartofthe
collectionsframework.
With the advent of collections, Vector was reengineered to extend AbstractList and to
implementtheListinterface.
This means that Vector is fully compatible with collections, and a vector can have its
contentsiteratedbytheenhancedforloop.
Constructors:
TheVectorhasthefollowingconstructors:
Vector()
Constructoranemptyvectorsothatitsinternaldataarrayhassize10anditsstandard
capacityincrementiszero.
Vector(Collectionc)
Constructsavectorcontainingtheelementsofthespecifiedxollectionintheorderthey
arereturnedbythecollection’siterator.
Vector(intinitialCapacity)
Constructs an empty vector with the specified initial capacity and with its capacity
incrementequaltozero.
Vector(intinitialCapacity,intcapacityIncrement)
Constructsanemptyvectorwiththespecifiedinitialcapacityandcapacityincrement.
Thesizeofextraspaceallocatedduringeachreallocationisdeterminedbythespecified
increment. If you do not specify an increment, the vector’s size is doubled by each
allocationcycle.Vectordefinesthreeprotecteddatamembers:
protectedintcapacityIncrement
Theamountbywhichthecapacityofthevectorisautomaticallyincrementedwhenits
sizebecomesgreaterthanitscapacity.
protectedintelementCount
ThenumberofvalidcomponentsinthisVectorobject.
protectedObject[]elementData
Thearraybufferintowhichthecomponentsofthevectorarestored.
Inadditiontothecollectionmethodsdefinedbylist,Vectorclassdefinesseverallegacy
methods.
MethodSummary:
voidaddElement(Objectobj)
Addsthespecifiedcomponentstotheendofthisvector,increasingitssizebyone.
intcapacity()
Returnsthecurrentcapacityofthisvector.
Objectclone()
Returnsacloneofthisvector.
voidcopyInto(Object[]anArray)
Copiesthecomponentsofthisvectorintothespecifiedarray.
ObjectelementAt(intindex)
Returnsthecomponentatthespecifiedindex.
Enumerationelements()
Returnsanenumerationofthecomponentsofthisvector.
voidensureCapacity(intminCapacity)
Increasethecapacityofthisvector,ifnecessary,toensurethatitcanholdatleastthe
numberofcomponentsspecifiedbytheminCapacityArgument.
ObjectfirstElement()
Returnsthefirstcomponent(theitematindex0)ofthisvector.
intindexOf(Objectelement)
Searchesforthefirstoccurrenceofthegivenargument,testingforequalityusingthe
equalsmethods.
intindexOf(Objectelement,intindex)
Searchesforthefirstoccurrenceofthegivenargument,beginningthesearchatindex,
andtestingforequalityusingtheequalsmethods.
voidinsertElementAt(Objectobj,intindex)
Insertsthespecifiedobjectasacomponentinthisvectoratthespecifiedindex.
booleanisEmpty()
Testsifthisvectorhasnocomponents.
ObjectlastElement()
Returnsthelastcomponentsofthevector.
intlastIndexOf(Objectelement)
Returnstheindexofthelastoccurrenceofthespecifiedobjectinthisvector.
intlastIndexOf(Objectelement,intindex)
Searches backwards for the specified object, starting from the specified index, and
returnsanindextoit.
voidremoveAllElements()
Removesallcomponentsfromthisvectorandsetsitssizetozero.
booleanremoveElement(Objectobj)
Removesthefirst(lowest-indexed)occurrenceoftheargumentfromthisvector.
voidremoveElementAt(intindex)
Deletesthecomponentatthespecifiedindex.
protectedvoidremoveRange(intfromIndex,inttoIndex)
RemovesfromthislistalloftheelementswhoseindexisbetweenfromIndexinclusive
andtoIndexexclusive.
voidsetElementAt(Objectobj,intindex)
Setsthecomponentatthespecifiedindexofthisvectortobethespecifiedobject.
voidsetSize(intnewSize)
Setsthesizeofthisvector.Ifthenewsizeislessthantheoldsize,elementsarelost.If
thenewsizeislargerthantheold,nullelementsareadded.
intsize()
Returnsthenumberofcomponentsinthisvector.
ListsubList(intfromIndex,inttoIndex)
Returns a view of the portion of this list between fromIndex inclusive, and toIndex
exclusive.
Object[]toArray()
Retumsanarraycontainingalloftheelementsinthisvectorinthecorrectorder.
StringtoArray()
Returnsastringrepresentationofthisvector,containingthestringrepresentationofeach
element.
voidtrimToSize()
Setsthevector’scapacityequaltothenumberofelementsthatitcurrentlyholds.
Because vector implement List, you can use a vector just like you use an ArrayList
instance.Youcanalsomanipulateavectorusinglegacymethods.
Example21.8
1.importjava.util.*;
2.classVectorTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Vector<Integer>v1=newVector<Integer>();
7. System.out.println(“Size is ” + v1.size() + ” Capacity is ” +
v1.capacity());
8.for(inti=1;i<=15;i++)
9.v1.addElement(i);
10. System.out.println(“Size is ” + v1.size() + ” Capacity is ” +
v1.capacity());
11.Iteratoritr=v1.iterator();
12.while(itr.hasNext())
13.{
14.System.out.print(itr.next()+”“);
15}
16.System.out.println();
17.for(inti:v1)
18.System.out.print(i+”“);
19.System.out.println();
20.Enumeratione=v1.elements();
21.while(e.hasMoreElements())
22.{
23.System.out.print(e.nextElement()+””);
24.}
25.System.out.println();
26.Integera[]=newInteger[v1.size()];
27.v1.copyInto(a);
28.for(inti=0;i<a.length;i++)
29.System.out.print(a[i]+”“);
30.System.out.println();
31.System.out.println(“FirstElement=”+v1.firstElement());
32.System.out.println(“LastElement=”+v1.lastElement());
33.}
34.}
Output:
Sizeis0Capacityis10
Sizeis15Capacityis20
123456789101112131415
123456789101112131415
123456789101112131415
123456789101112131415
FirstElement=1
LastElement=15
TheStackClass:
The stack is a subclass of Vector that implements a standard LIFO stack. The Stack
only defines the default constructor, which creates an empty stack. Stack includes all
methodsdefinedbyVector,andaddsseveralofitsown.
MethodsSummary:
booleanempty()
Testsifthestackisempty.
Objectpeek()
Returnstheobjectatthetopofthisstackwithoutremovingitfromthestack.
Objectpop()
Removestheobjectatthetopofthisstackandreturnsthatobjectasthevalueofthis
methods.AnEmptyStackExceptionisthrownifthestackisempty.
Objectpush(Objectitem)
Pushesanitemontothetopofthisstack.
intsearch(Objecto)
Returnsthe1-basedpositionwhereanobjectisonthisstack.
Example21.9:
The following example creates a stack, pushes several Integer objects onto it and pops
themoffagain:
1.importjava.util.*;
2.classStackTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Stack<Integer>st=newStack<Integer>();
7.st.push(10);
8.st.push(20);
9.st.push(30);
10.System.out.println(“Stackis”+st);
11.System.out.println(“30isatpos”+st.search(30));
12.try
13.{
14.Integeriobj=st.pop();
15.System.out.println(“Poppedvalueis”+iobj.intValue());
16.iobj=st.peek();
17.System.out.println(“Peekvalueis”+iobj.intValue());
18.}
19.catch(EmptyStackExceptione)
20.{
21.System.out.println(e);
22.}
23.}
24.}
Output:
Stackis[10,20,30]
30isatpos1
Poppedvalueis30
Peekvalueis20
TheDictionaryClass:
Dictionary is an abstract class that represents a key/value storage repository and
operates much like Map. Given a key and value pair, you can store the value in a
dictionaryobjectoncethevalueisstored,youcanretrieveitbyusingitskey.
Thus,likeamap,dictionarycanbethoughtofasalistofkey/valuepairs.Althoughnot
actuallydeprecatedbyjava2,Dictionaryisclassifiedasobsolete,becauseitissuperceded
byMap.
TheabstractmethodsdefinedbyDictionaryclassare:
Enumerationelements()
Returnsanenumerationofthevaluesinthisdictionary.
Objectget(Objectkey)
Returnsthevaluetowhichthekeyismappedinthisdictionsry.
booleanisEmpty()
Testsifthisdictionarymapsnokeystovalue.
Enumerationkeys()
Returnsanenumerationofthekeysinthisdictionary.
Objectput(Objectkey,Objectvalue)
Mapsthespecifiedkeytothespecifiedvalueinthisdictionary.
Objectremove(Objectkey)
Removesthekey(anditscorrespondingvalue)fromthisdictionary.
intsize()
Returnsthenumberofentries(distinctkeys)inthisdictionary.
TheHashtableClass:
TheHashtablewaspartoftheoriginaljava.utilandisaconcreteimplementationofa
Dictionary.However, Java2 reengineeredHashtableso thatitalsoimplementsthe Map
interface.
Thus, Hashtable is now integrated into the collections framework. It is similar to
HashMap,butissynchronized.LikeHashMap.
Hashtablestoreskey/valuepairsinahashtable.WhenusingaHashtable,youspecifyan
objectthatisusedasakey,andthevaluethatyouwanttolinkedtothatkey.
Thekeyisthenhashed,andtheresultinghashcodeisusedastheindexatwhichthevalue
isstoredwithinthetable.
Ahashtablecanonlystoreobjectsthatoverridethehashcode()andequals()methods
thataredefinedbytheObjectclass.Mostlystringobjectisusedasthekey,whichalready
implementsbothhashCode()andequals().
Constructors:
TheHashtablehasthefollowingconstructors:
Hashtable()
Constructs a new, empty Hashtable with the default initial capacity(11) and
loadfactor,whichis0.75.
Hashtable(intinitialCapacity)
Constructsanew,emptyHashtablewiththespecifiedinitialcapacityanddefault
loadfactor(0.75)
Hashtable(intinitialCapacity,floatloadFactor)
Constructs a new, empty Hashtable with the specified initial capacity and
specifiedloadfactor.
Hashtable(Mapm)
ConstructanewhashtablewiththesamemappingasthespecifiedMap.
Hashtablealsodefinesthelegacymethods:
voidclear()
Clearsthishashtablewiththatitcontainsnokeys.
Objectclone()
Createsashallowcopyofthishashtable.
booleancontains(Objectvalue)
Testsifsomekeymapsintothespecifiedvalueinthishashtable.
booleancontainsKey(Objectkey)
Testsifthespecifiedobjectisakeyinthishashtable.
booleancontainsValue(Objectvalue)
ReturnstrueifthisHashtablemapsoneormorekeystothisvalue.
Enumerationelements()
Returnsanenumerationofthevaluesinthishashtable.
SetentrySet()
ReturnsaSetviewoftheentriescontainedinthisHashtable.
booleanequals(Objecto)
ComparesthespecifiedObjectwiththismapforequality.
Objectget(Objectkey)
Returnsthevaluetowhichthespecifiedkeyismappedinthishashtable.
inthashCode()
ReturnsthehashcodevalueforthisMapasperthedefinitionintheMapinterface.
booleanisEmpty()
Testsifthishashtablemapsnokeystovalue.
Enumerationkeys()
Returnsanenumerationofthekeysinthishashtable.
SetkeySet()
Returnsasetviewofthekeyscontainedinthishashtable.
Objectput(Objectkey,Objectvalue)
Mapsthespecifiedkeytothespecifiedvalueinthishashtable.
voidputAll(Mapm)
CopiesallofthemappingsfromthespecifiedMaptothisHashtablethesemappings
willreplaceanymappingsthatthisHashtablehadforanyofthekeyscurrentlyinthe
specifiedMap.
Protectedvoidrehash()
Increasethesizeofthehashtableandrehashesallofitskeys.
Objectremove(Objectkey)
Removesthekey(anditscorrespondingvalue)fromthishashtable.
intsize()
Returnsthenumberofentries(distinctkeys)inthishashtable.
StringtoString()
Returnsastringrepresentationofthishashtableobjectintheformofasetofentries,
enclosedinbracesandseparatedbytheASCIIcharacter“,”(commaandspace).
Collectionvalues()
ReturnsacollectionofthevaluescontainedinthisHashtable.
Example21.10:
ThefollowingexampleusesaHashtabletostorethenameofdepositorsandtheircurrent
balance.
1.importjava.util.*;
2.classHashtableTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Hashtable<String,Integer>ht=newHashtable<String,Integer>();
7.ht.put(“C”,1000);
8.ht.put(“Java”,1500);
9.ht.put(“Vb”,1500);
10.//DisplayListusingEnumeration
11.Enumeration<String>courses;
12.courses=ht.keys();
13.while(courses.hasMoreElements())
14.{
15.Strings1=courses.nextElement();
16.System.out.println(“Course=”+s1+”Fees=”+ht.get(s1));
17.}
18.//DisplayListusingforeach
19.Sets=ht.keySet();
20.for(Objectob:s)
21.System.out.println(“Course=”+(String)ob+”Fees=”+ht.get((String)ob));
22.Integerfees=ht.get(“Java”);
23.ht.put(“Java”,fees+1000);
24.System.out.println(“AfterUpdate“);
25.//DisplayListusingIterator
26.Iteratoritr=s.iterator();
27.while(itr.hasNext())
28.{
29.Strings1=(String)itr.next();
30.System.out.println(“Course=”+s1+“Fees=”+ht.get(s1));
31.}
32.}}
Output:
Course=JavaFees=1500
Course=VbFees=1500
Course=CFees=1000
Course=JavaFees=1500
Course=VbFees=1500
Course=CFees=1000
AfterUpdate
Course=JavaFees=2500
Course=VbFees=1500
Course=CFees=1000
ThePropertiesClass:
ThePropertiesisasubclassofHashtable.Itisusedtomaintainlistofvaluesin
whichthekey is aString and the valueis also astring.The properties classis used by
manyotherJavaclasses.
For example, it is the type of object returned by System getProperties() when
obtainingenvironmentalvalues.
Propertiesclassdefinesthefollowinginstancevariable:
Propertiesdefaults
ThevariableholdsadefaultpropertylistassociatedwithaPropertiesobject.
Constructors:
ThePropertieshasthefollowingconstructors:
Properties()
Createsanemptypropertylistwithnodefaultvalues.
Properties(Propertiesdefaults)
Createsanemptypropertylistwiththespecifieddefaults.
InadditiontothemethodsthatpropertiesinheritsfromHashtable,Propertiesdefinessome
moremethods.Propertiesalsocontainsonedeprecatedmethodsave().Thiswasreplaced
bystore()becausesave()didnothandleerrorscorrectly.
Methodsummary:
StringgetProperty(Stringkey)
Returnsthevalueassociatedwithkey.Anullobjectisreturnedifkeyisneitherinthe
listnorinthedefaultpropertylist.
StringgetProperty(Stringkey,StringdefaultValue)
Returnsthevalueassociatedwithkey.Adefaultpropertyisreturnedifkeyisneither
inthelistnorinthedefaultpropertylist.
voidlist(PrintStreamout)
Printsthispropertylistouttothespecifiedoutputstream.
voidlist(PrintWriterout)
Printsthispropertylistouttothespecifiedoutputstream.
voidload(InputStreaminStream)
Readsapropertylist(keyandelementpairs)fromtheinputstream.
EnumerationpropertyNames()
Returnsanenumerationofallthekeys.Thisincludesthosekeysfoundinthedefault
property,too.
voidsave(OutputStreamout,Stringcomments)
Deprecated.ThismethoddoesnotthrowanIOExceptionifanI/Oerroroccurswhile
saving the property list. The preferred way to save a properties list is via the store
(OutputStreamout,Stringcomments)method.
ObjectsetProperty(Stringkey,Stringvalue)
CallstheHashtablemethodput.Returnspreviousvalueassociatedwithkey,ornullif
nosuchassociationexists.
voidstore(OutputStreamout,Stringcomments)
Writesthispropertylist(keyandelementpairs)inthispropertiestabletotheoutput
streaminaformatsuitableforloadingintoaPropertiestableusingtheloadmethod.
Example21.11:
Thefollowingprogramcreatesapropertylistinwhichthekeysarethecoursenamesand
thevaluesarethedurationofthecourses.
1.importjava.util.*;
2.classPropertiesTest
3.{
4.publicstaticvoidmain(Stringargs[])
5.{
6.Propertiesdef=newProperties();
7.def.put(“C”,“2months”);
8.def.put(“C++”,“3months”);
9.Propertiescourses=newProperties(def);
10.courses.put(“Java”,“4months”);
11.courses.put(“DotNet”,“6months”);
12.System.out.println(“DurationofJavais”+courses.getProperty(“Java”,“NotFound”));
13.System.out.println(“DurationofCis”+courses.getProperty(“C”,“NotFound”));
14.System.out.println(“DurationofVBis”+
courses.getProperty(“VB”,“NotFound”));
15.System.out.println(“ListofallCourses:-“);
16.Sets=courses.keySet();
17.for(Objectob:s)
18.{
19.System.out.println(“DurationofCourse”+(String)ob+”is”+
courses.getProperty((String)ob,“notfound”));
20.}
21.Iteratoritr=s.iterator();
22.while(itr.hasNext())
23.{
24.Strings1=(String)itr.next();
25.System.out.println(“DurationofCourse”+s1+”is”+
courses.getProperty(s1,“NotFound”));
26.}
27.}
28.}
Output:
DurationofJavais4months
DurationofCis2months
DurationofVBisNotFound
ListofallCourses:-
DurationofCourseJavais4months
DurationofCourseDotNetis6months
DurationofCourseJavais4months
DurationofCourseDotNetis6months
Usingstore()andload()
OneofthemostusefulaspectsofPropertiesisthattheinformationcontainedina
Propertiesobjectcanbeeasilystoredtoorloadedfromdiskwiththestore()andload().
Atanytime,youcanwriteaPropertiesobjecttoastreamorreaditback.This
makespropertylistsespeciallyconvenientforimplementingsimpledatabases.
For example, the following program use a property list to create a simple
computerized telephone book that stores names and phone numbers. To find a person’s
numberyouenterhisorhername.
The program uses the store() and load() methods to store and retrieve the list.
Whentheprogramexecutes,itfirsttriestoloadthelistfromafilecalledphonebook.dat.
ifthisfileexists,thelistisloaded.Youcanthenaddtothelist.
CHAPTER
∞22∞
Java8FeaturesforDevelopers
Lambdas,Functionalinterface,
Java8isreleasedin18thMarch2014,soit’shightimetolookfortheJava8featuresfor
thedevelopers.Andnoenoghmaterialisavailableforjava8.Buthereafteralotsofhard
workiamwritingSomeoftheimportantfeaturesintroducedinJava8thatIamlooking
forwardtoare:
1.forEach()methodinIterableinterface.
2.defaultandstaticmethodsinInterfaces.
3.FunctionalInterfacesandLambdaExpressions.
4.JavaStreamAPIforBulkDataOperationsonCollections.
5.JavaTimeAPI.
6.CollectionAPIimprovements.
7.ConcurrencyAPIimprovements.
8.JavaIOimprovements.
9.MiscellaneousCoreAPIimprovements.
Let’s have a brief look on these Java 8 features. I will provide some code snippets for
betterunderstanding,soifyouwanttorunprogramsinJava8,youwillhavetosetupJava
8environmentbyfollowingsteps.
Download JDK8 and install it. Installation is simple like other java versions. JDK
installationisrequiredtowrite,compileandruntheprograminJava.
NOTE: Current Eclipse IDE doesn’t support Java8, so you will have to download it
fromefxclipse.orgEclipseforJava8.TherearedifferentversionsforMacOS,Windows
andLinuxsystemswithstablebuilds,sodownloadthelatestoneformostfeatures.
Ijustcheckedtoday(28-July-2014)andEclipseKepler4.3.2SR2packagecanbeusedfor
Java8.Youneedtodownloaditfirstandtheninstall“Java8supportforEclipseKepler
SR2″pluginfromEclipseMarketplace.Ihavetriedthisanditseemstobeworkingfine.
1.forEach()methodinIterableinterface-
WheneverweneedtotraversethroughaCollection,weneedtocreateanIteratorwhose
wholepurposeistoiterateoverandthenwehavebusinesslogicinaloopforeachofthe
elementsintheCollection.WemightgetConcurrentModificationExceptionifiteratoris
notusedproperly.
Java 8 has introduced FOREACH method in java.lang.Iterable interface so that while
writing code we focus on business logic only. FOREACH method
takes java.util.function.Consumer object as argument, so it helps in having our business
logic at a separate location that we can reuse. Let’s see forEach usage with simple
example.
Java8ForEachExample.java
package com.journaldev.java8.foreach;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
import java.lang.Integer;
public class Java8ForEachExample{
public static void main(String[]args){
//creatingsampleCollection
List<Integer>myList=new ArrayList<Integer>();
for(int i=0;i<10;i++)myList.add(i);
//traversingusingIterator
Iterator<Integer>it=myList.iterator();
while(it.hasNext()){
Integeri=it.next();
System.out.println(“IteratorValue::”+i);
}
//traversingthroughforEachmethodofIterablewithanonymousclass
myList.forEach(new Consumer<Integer>(){
public void accept(Integert){
System.out.println(“forEachanonymousclassValue::”+t);
}
});
//traversingwithConsumerinterfaceimplementation
MyConsumeraction=new MyConsumer();
myList.forEach(action);
}
}
//Consumerimplementationthatcanbereused class MyConsumerimplements Consumer<Integer>{
public void accept(Integert){
System.out.println(“ConsumerimplValue::”+t);
}
}
The number of lines might increase but forEach method helps in having the logic for
iterationandbusinesslogicatseparateplaceresultinginhigherseparationofconcernand
cleanercode.
2.defaultandstaticmethodsinInterfaces-
IfyoureadforEachmethoddetailscarefully,youwillnoticethatit’sdefinedinIterable
interfacebutweknowthatinterfacescan’thavemethodbody.FromJava8,interfacesare
enhanced to have method with implementation. We can use ‘DEFAULT‘ and ‘STATIC‘
keywordtocreateinterfaceswithmethodimplementation.
ForeachmethodimplementationinIterableinterfaceis:
default void forEach(Consumer<?super T>action){
Objects.requireNonNull(action);
for (Tt:this){
action.accept(t);
}
}
Remember:
WeknowthatJavadoesn’tprovidemultipleinheritanceinClasses because it
leads to Diamond Problem. So how it will be handled with interfaces now, since
interfacesarenowsimilartoabstractclasses.
Thesolution is thatcompiler will throwexception in thisscenario and wewill
havetoprovideimplementationlogicintheclassimplementingtheinterfaces.
Interface1.java
package com.journaldev.java8.defaultmethod;
@FunctionalInterface
public interface Interface1{
void method1(Stringstr);
default void log(Stringstr){
System.out.println(“I1logging::”+str);
}
static void print(Stringstr){
System.out.println(“Printing“+str);
}
//tryingtooverrideObjectmethodgivescompiletimeerroras
//“Adefaultmethodcannotoverrideamethodfromjava.lang.Object”
//defaultStringtoString(){
//return“i1”;
//}
}
Interface2.java
package com.journaldev.java8.defaultmethod;
@FunctionalInterface
public interface Interface2{
void method2();
default void log(Stringstr){
System.out.println(“I2logging::”+str);
}
}
Noticethatboththeinterfaceshaveacommonmethodlog()withimplementationlogic.
MyClass.java
package com.journaldev.java8.defaultmethod;
public class MyClassimplements Interface1,Interface2{
@Override
public void method2(){
}
@Override
public void method1(Stringstr){
}
//MyClasswon’tcompilewithouthavingit’sownlog()implementation
@Override
public void log(Stringstr){
System.out.println(“MyClasslogging::”+str);
Interface1.print(“abc”);
}
}
AsyoucanseethatInterface1hasstaticmethodimplementationthatisusedin
MYCLASS.LOG() method implementation. Java 8 uses default and static methods
heavily in Collection API and default methods are added so that our code remains
backwardcompatible.
If any class in the hierarchy has a method with same signature, then default
methodsbecomeirrelevant.SinceanyclassimplementinganinterfacealreadyhasObject
assuperclass,ifwehaveequals(),hashCode()defaultmethodsininterface,itwillbecome
irrelevant. Thats why for better clarity, interfaces are not allowed to have Object class
defaultmethods.
ForcompletedetailsofinterfacechangesinJava8,pleasereadJava8interface
changesBelow.
Java 8 Interface Changes – static methods, default methods, functional
Interfaces-
OneofthebiggestdesignchangeinJava8iswiththeconceptofinterfaces.Prior
toJava7,wecouldhaveonlymethoddeclarationsintheinterfaces.ButfromJava8,we
canhavedefaultmethodsandstaticmethodsintheinterfaces.
Designing interfaces have always been a tough job because if we want to add
additionalmethodsintheinterfaces,itwillrequirechangeinalltheimplementingclasses.
Asinterfacegrowsold,thenumberofclassesimplementingitmightgrowtoan
extent that it’s not possible to extend interfaces. That’s why when designing an
application, most of the frameworks provide a base implementation class and then we
extenditandoverridemethodsthatareapplicableforourapplication.Let’slookintothe
defaultandstaticinterfacemethodsandthereasoningoftheirintroduction.
InterfaceDefaultMethod-
Forcreatingadefaultmethodintheinterface,weneedtouse“default”keywordwiththe
methodsignature.Forexample,
Interface1.java
packagecom.journaldev.java8.defaultmethod;
publicinterfaceInterface1{
voidmethod1(Stringstr);
defaultvoidlog(Stringstr){
System.out.println(“I1logging::”+str);
print(str);
}
}
Noticethatlog(Stringstr)isthedefaultmethodintheInterface1.Nowwhenaclasswill
implementInterface1,itisnotmandatorytoprovideimplementationfordefaultmethods.
Thisfeaturewillhelpusinextendinginterfaceswithadditionalmethods,allweneedisto
provide a default implementation. Let’s say we have another interface with following
methods:
Interface2.java
packagecom.journaldev.java8.defaultmethod;
publicinterfaceInterface2{
voidmethod2();
defaultvoidlog(Stringstr){
System.out.println(“I2logging::”+str);
}
}
We know that Java doesn’t allow us to extend multiple classes because it will
resultinthe“DiamondProblem”wherecompilercan’tdecidewhichsuperclassmethodto
use.Withthedefaultmethods,thediamondproblemwouldariseforinterfacestoo.
Because if a class is implementing both Interface1 andInterface2 and doesn’t
implementthecommondefaultmethod,compilercan’tdecidewhichonetochose.
ExtendingmultipleinterfacesareanintegralpartofJava,youwillfinditinthe
corejavaclassesaswellasinmostofthe enterpriseapplicationandframeworks.Soto
make sure, this problem won’t occur in interfaces, it’s made mandatory to provide
implementationforcommondefaultmethods.
Soif a classis implementingboth the aboveinterfaces, itwillhave toprovide
implementationforlog()methodotherwisecompilerwillthrowerror.Asimpleclassthat
isimplementingbothInterface1andInterface2willbe:
MyClass.java
packagecom.journaldev.java8.defaultmethod;
publicclassMyClassimplementsInterface1,Interface2{
@Override
publicvoidmethod2(){
}
@Override
publicvoidmethod1(Stringstr){
}
@Override
publicvoidlog(Stringstr){
System.out.println(“MyClasslogging::”+str);
Interface1.print(“abc”);
}
}
Importantpointsaboutinterfacedefaultmethods:
Defaultmethodswillhelpusinextendinginterfaceswithouthavingthefear
ofbreakingimplementationclasses.
Defaultmethodshas bridge downthe differencesbetween interfacesand
abstractclasses.
Default methods will help us in avoiding utility classes, such as all the
Collectionsclassmethodcanbeprovidedintheinterfacesitself.
Defaultmethodswillhelpusinremovingbaseimplementationclasses,we
can provide default implementation and the implementation classes can chose
whichonetooverride.
Oneofthemajorreasonforintroducingdefaultmethodsistoenhancethe
CollectionsAPIinJava8tosupportlambdaexpressions.
Ifanyclassinthehierarchyhasamethodwithsamesignature,thendefault
methods become irrelevant. A default method cannot override a method
fromjava.lang.Object.
Thereasoningisverysimple,it’sbecauseObjectisthebaseclassforall
the java classes. So even if we have Object class methods defined as default
methodsininterfaces,itwillbeuselessbecauseObjectclassmethodwillalways
beused.That’swhytoavoidconfusion,wecan’thavedefaultmethodsthatare
overridingObjectclassmethods.
Default methods are also referred to as Defender Methods or Virtual
extensionmethods.
Interfacestaticmethods-
Staticmethodsaresimilartodefaultmethodsexceptthatwecan’toverridethem
intheimplementationclasses.Thisfeaturehelpsusinavoidingundesiredresultsincaseof
poorimplementationinchildclasses.Let’slookintothiswithasimpleexample.
MyData.java
packagecom.journaldev.java8.staticmethod;
publicinterfaceMyData{
defaultvoidprint(Stringstr){
if(!isNull(str))
System.out.println(“MyDataPrint::”+str);
}
staticbooleanisNull(Stringstr){
System.out.println(“InterfaceNullCheck”);
returnstr==null?true:””.equals(str)?true:false;
}
}
Now let’s see an implementation class that is having isNull() method with poor
implementation.
MyDataImpl.java
packagecom.journaldev.java8.staticmethod;
publicclassMyDataImplimplementsMyData{
publicbooleanisNull(Stringstr){
System.out.println(“ImplNullCheck”);
returnstr==null?true:false;
}
publicstaticvoidmain(Stringargs[]){
MyDataImplobj=newMyDataImpl();
obj.print(””);
obj.isNull(“abc”);
}
}
Note that isNull(String str) is a simple class method, it’s not overriding the interface
method.
For example, if we will add @Overrideannotation to the isNull() method, it
will result in compiler error. Now when we will run the application, we get following
output.
InterfaceNullCheck
ImplNullCheck
Ifwemaketheinterfacemethodfromstatictodefault,wewillgetfollowingoutput.
1
2
3
ImplNullCheck
MyDataPrint::
ImplNullCheck
The static methods are visible to interface methods only, if we remove the
isNull() method from theMyDataImpl class, we won’t be able to use it for
the MyDataImpl object. However like other static methods, we can use interface static
methodsusingclassname.Forexample,avalidstatementwillbe:
1 booleanresult=MyData.isNull(“abc”);
Importantpointsaboutinterfacestaticmethods:
Interfacestaticmethodsarepartofinterface,wecan’tuseitfor
implementationclassobjects.
Interfacestaticmethodsaregoodforprovidingutilitymethods,forexample
nullcheck,collectionsortingetc.
Interfacestaticmethodhelpsusinprovidingsecuritybynotallowing
implementationclassestooverridethem.
Wecan’tdefinestaticmethodsforObjectclassmethods,wewillgetcompiler
erroras“ThisstaticmethodcannothidetheinstancemethodfromObject”.This
isbecauseit’snotallowedinjava,sinceObjectisthebaseclassforallthe
classesandwecan’thaveoneclasslevelstaticmethodandanotherinstance
methodwithsamesignature.
Wecanusestaticinterfacemethodstoremoveutilityclassessuchas
Collectionsandmoveallofit’sstaticmethodstothecorrespondinginterface,
thatwouldbeeasytofindanduse.
FunctionalInterfaces-
Before I conclude the topic, I would like to provide a brief introduction to
Functional interfaces. An interface with exactly one abstract method is known as
FunctionalInterface.
Anewannotation@FunctionalInterfacehasbeenintroducedtomarkaninterface
asFunctionalInterface.@FunctionalInterfaceannotationisafacilitytoavoidaccidental
additionofabstractmethodsinthefunctionalinterfaces.It’soptionalbutgoodpracticeto
useit.
Functional interfaces are long awaited and much sought out feature of Java 8
because it enables us to use lambda expressions to instantiate them. A new
packagejava.util.functionwithbunchoffunctionalinterfacesareaddedtoprovidetarget
typesforlambdaexpressionsandmethodreferences.
3.FunctionalInterfacesandLambdaExpressions-
If you notice above interfaces code, you will notice
@FunctionalInterface annotation. Functional interfaces are new concept introduced in
Java8.AninterfacewithexactlyoneabstractmethodbecomesFunctionalInterface.
We don’t need to use @FunctionalInterface annotation to mark an interface as
Functional Interface. @FunctionalInterface annotation is a facility to avoid accidental
additionofabstractmethodsinthefunctionalinterfaces.
You can think of it like @Override annotation and it’s best practice to use
it. java.lang.Runnablewith single abstract method run() is a great example of functional
interface.
Oneofthemajorbenefitsoffunctionalinterfaceisthepossibilitytouselambda
expressionstoinstantiatethem.Wecaninstantiateaninterfacewithanonymousclassbut
thecodelooksbulky.
Runnabler=new Runnable(){
@Override
public void run(){
System.out.println(“MyRunnable”);
}};
Sincefunctionalinterfaceshaveonlyonemethod,lambdaexpressionscaneasily
providethemethodimplementation.
Wejustneedtoprovidemethodargumentsandbusinesslogic.Forexample,we
canwriteaboveimplementationusinglambdaexpressionas:
Runnabler1=()->{
System.out.println(“MyRunnable”);
};
Ifyouhavesinglestatementinmethodimplementation,wedon’tneedcurlybracesalso.
For example above Interface1 anonymous class can be instantiated using lambda as
follows:
Interface1i1=(s)->System.out.println(s);
i1.method1(“abc”);
So lambda expressions are means to create anonymous classes of functional
interfaceseasily.Therearenoruntimebenefitsofusinglambdaexpressions,soIwilluse
itcautiouslybecauseIdon’tmindwritingfewextralinesofcode.
A new package java.util.function has been added with bunch of functional
interfacestoprovidetargettypesforlambdaexpressionsandmethodreferences.
Lambdaexpressionsareahugetopic,Iwillwriteaseparate+(Note)onthatin
future(NextEditionofthisBook).YoucanreadcompletetutorialbelowJava8Lambda
ExpressionsTutorial.
Java8LambdaExpressionsandFunctionalInterfacesTutorial-
Java has always been an Object Oriented Programming language. What is
means that everything in java programming revolves around Objects (except some
primitivetypesforsimplicity).Wedon’thaveonlyfunctionsinjava,theyarepartofClass
andweneedtousetheclass/objecttoinvokeanyfunction.
IfwelookintosomeotherprogramminglanguagessuchasC++,JavaScript;they
are called functional programming language because we can write functions and use
themwhen required.Someof theselanguages supportObjectOriented Programmingas
wellasFunctionalProgramming.
Being object oriented is not bad, but it brings a lot of verbosity to the program. For
example, let’s say we have to create an instance of Runnable. Usually we do it using
anonymousclasseslikebelow.
1
2
3
4
5
Runnabler=newRunnable(){
@Override
publicvoidrun(){
System.out.println(“MyRunnable”);
}
};
Ifyoulookattheabovecode,theactualpartthatisofuseisthecodeinsiderun()
method.Restallofthecodeisbecauseofthewayjavaprogramsarestructured.
Java8bringsustheconceptofFunctionalInterfacesandLambda
Expressionstoavoidwritingalltheuselesscodethatwecaneasilyavoidbymakingour
javacompilerintelligent.
FunctionalInterface-
An interface with exactly one abstract method is called Functional Interface.
@FunctionalInterfaceannotationis addedso thatwecan markan interfaceasfunctional
interface. It is not mandatory to use it, but it’s best practice to use it with functional
interfaces to avoid addition of extra methods accidentally. If the interface is annotated
with@FunctionalInterfaceannotationandwetrytohavemorethanoneabstractmethod,
itthrowscompilererror.
The major benefit of functional interface is that we can use lambda
expressionstoinstantiatethemandavoidusingbulkyanonymousclassimplementation.
Java8CollectionsAPIhasrewrittenandnewStreamAPIisprovidedthatusesa
lot of functional interfaces. Java 8 has defined a lot of functional interfaces
in java.util.function package, some of the useful ones
areConsumer, Supplier, Function and Predicate. You can find more detail about them
inJava8StreamExample.
java.lang.Runnable is a great example of functional interface with single abstract
methodrun().
Belowcodesnippetprovidessomeguidanceforfunctionalinterfaces:
interfaceFoo{booleanequals(Objectobj);}
//Notfunctionalbecauseequalsisalreadyanimplicit
member(Objectclass)
interfaceComparator<T>{
booleanequals(Objectobj);
intcompare(To1,To2);
}
//FunctionalbecauseComparatorhasonlyoneabstract
non-Objectmethod
interfaceFoo{
intm();
Objectclone();
}
//NotfunctionalbecausemethodObject.cloneisnot
public
interfaceX{intm(Iterable<String>arg);}
interfaceY{intm(Iterable<String>arg);}
interfaceZextendsX,Y{}
//Functional:twomethods,buttheyhavethesame
signature
interfaceX{Iterablem(Iterable<String>arg);}
interfaceY{Iterable<String>m(Iterablearg);}
interfaceZextendsX,Y{}
//Functional:Y.misasubsignature&return-type-
substitutable
interfaceX{intm(Iterable<String>arg);}
interfaceY{intm(Iterable<Integer>arg);}
interfaceZextendsX,Y{}
//Notfunctional:Nomethodhasasubsignatureofall
abstractmethods
interfaceX{intm(Iterable<String>arg,Classc);}
interfaceY{intm(Iterablearg,Class<?>c);}
interfaceZextendsX,Y{}
//Notfunctional:Nomethodhasasubsignatureofall
abstractmethods
interfaceX{longm();}
interfaceY{intm();}
interfaceZextendsX,Y{}
//Compilererror:nomethodisreturntypesubstitutable
interfaceFoo<T>{voidm(Targ);}
interfaceBar<T>{voidm(Targ);}
interfaceFooBar<X,Y>extendsFoo<X>,Bar<Y>{}
//Compilererror:differentsignatures,sameerasure
LambdaExpressions-
LambdaExpressions are the way through which we can visualize functional
programminginthejavaobjectorientedworld.Objectsarethebaseofjavaprogramming
languageandwecanneverhaveafunctionwithoutanObject,that’swhyJavalanguage
providesupportforusinglambdaexpressionsonlywithfunctionalinterfaces.
Sincethereisonlyoneabstractfunctioninthefunctionalinterfaces,thereisno
confusioninapplyingthelambdaexpressiontothemethod.LambdaExpressionssyntax
is(argument) -> (body). Now let’s see how we can write above anonymous Runnable
usinglambdaexpression.
1 Runnabler1=()->System.out.println(“MyRunnable”);
Let’strytounderstandwhatishappeninginthelambdaexpressionabove.
Runnableisafunctionalinterface,that’swhywecanuselambdaexpression
tocreateit’sinstance.
Sincerun()methodtakesnoargument,ourlambdaexpressionalsohaveno
argument.
Justlikeif-elseblocks,wecanavoidcurlybraces({})sincewehaveasingle
statement in the method body. For multiple statements, we would have to use
curlybraceslikeanyothermethods.
WhydoweneedLambdaExpressions-
1.ReducedLinesofCode–
Oneoftheclearbenefitofusinglambdaexpressionisthattheamountofcodeisreduced,
wehavealreadyseenthathoweasilywecancreateinstanceofafunctionalinterfaceusing
lambdaexpressionratherthanusinganonymousclass.
2.SequentialandParallelExecutionSupport-
Anotherbenefitofusinglambdaexpressionisthatwecan benefitfromtheStreamAPI
sequential and parallel operations support. To explain this, let’s take a simple example
whereweneedtowriteamethodtotestifanumberpassedisprimenumberornot.
Traditionally we would write it’s code like below. The code is not fully optimized but
goodforexamplepurpose,sobearwithmeonthis.
1
2
3
4
5
6
7
8
//Traditionalapproach
privatestaticbooleanisPrime(intnumber){
if(number<2)returnfalse;
for(inti=2;i<number;i++){
if(number%i==0)returnfalse;
}
returntrue;
}
Theproblemwithabovecodeisthatit’ssequentialinnature,ifthenumberisveryhuge
thenitwilltakesignificantamountoftime.Anotherproblemwithcodeisthatthereareso
manyexitpointsandit’snotreadable.Let’sseehowwecanwritethesamemethodusing
lambdaexpressionsandstreamAPI.
1
2
3
//Declarativeapproach
privatestaticbooleanisPrime(intnumber){
returnnumber>1
4
5
6
&&IntStream.range(2,number-1).noneMatch(
index->number%index==0);
}
IntStreamisasequenceofprimitiveint-valuedelementssupportingsequentialandparallel
aggregate operations. This is the int primitive specialization of Stream. For more
readability,wecanalsowritethemethodlikebelow.
1
2
3
4
5
6
7
privatestaticbooleanisPrime(intnumber){
IntPredicateisDivisible=index->number%index==0;
returnnumber>1
&&IntStream.range(2,number-1).noneMatch(
isDivisible);
}
If you are not familiar with IntStream, it’s range() method returns a sequential ordered
IntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental
step of 1. noneMatch() method returns whether no elements of this stream match the
providedpredicate.
It may not evaluate the predicate on all elements if not necessary for determining the
result.
3.PassingBehaviorsintomethods-
Let’sseehowwecanuselambdaexpressionstopassbehaviorofamethodwithasimple
example.Let’ssaywehavetowriteamethodtosumthenumbersinalistiftheymatcha
givencriteria.WecanusePredicateandwriteamethodlikebelow.
1
2
3
4
5
publicstaticintsumWithCondition(List<Integer>numbers,Predicate<Integer>
predicate){
returnnumbers.parallelStream()
.filter(predicate)
.mapToInt(i->i)
.sum();
6 }
Sampleusage:
1
2
3
4
5
6
//sumofallnumbers
sumWithCondition(numbers,n->true)
//sumofallevennumbers
sumWithCondition(numbers,i->i%2==0)
//sumofallnumbersgreaterthan5
sumWithCondition(numbers,i->i>5)
4.HigherEfficiencywithLaziness-
Onemoreadvantageofusinglambdaexpressionisthelazyevaluation,forexample
let’ssayweneedtowriteamethodtofindoutthemaximumoddnumberintherange3to
11andreturnsquareofit.Usuallywewillwritecodeforthismethodlikethis:
1
2
3
4
5
6
7
8
9
privatestaticintfindSquareOfMaxOdd(List<Integer>numbers){
intmax=0;
for(inti:numbers){
if(i%2!=0&&i>3&&i<11&&i>max){
max=i;
}
}
returnmax*max;
}
AboveprogramwillalwaysruninsequentialorderbutwecanuseStreamAPItoachieve
this and get benefit of Laziness-seeking. Let’s see how we can rewrite this code in
functionalprogrammingwayusingStreamAPIandlambdaexpressions.
publicstaticintfindSquareOfMaxOdd(List<Integer>numbers){
returnnumbers.stream()
.filter(NumberTest::isOdd)//Predicateisfunctionalinterfaceand
.filter(NumberTest::isGreaterThan3)//weareusinglambdastoinitializeit
.filter(NumberTest::isLessThan11)//ratherthananonymousinnerclasses
.max(Comparator.naturalOrder())
.map(i->i*i)
.get();
}
publicstaticbooleanisOdd(inti){
returni%2!=0;
}
publicstaticbooleanisGreaterThan3(inti){
returni>3;
}
publicstaticbooleanisLessThan11(inti){
returni<11;
}
Ifyouaresurprisedwiththedoublecolon(::)operator,it’sintroducedinJava8andused
formethodreferences.JavaCompilertakescareofmappingtheargumentstothecalled
method. It’s short form of lambda expressions i -> isGreaterThan3(i) or i ->
NumberTest.isGreaterThan3(i).
LambdaExpressionExamples-
BelowIamprovidingsomecodesnippetsforlambdaexpressionswithsmallcomments
explainingthem.
1
2
3
4
5
6
7
()->{}//Noparameters;voidresult
()->42//Noparameters,expressionbody
()->null//Noparameters,expressionbody
()->{return42;}//Noparameters,blockbodywithreturn
()->{System.gc();}//Noparameters,voidblockbody
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//Complexblockbodywithmultiplereturns
()->{
if(true)return10;
else{
intresult=15;
for(inti=1;i<10;i++)
result*=i;
returnresult;
}
}
(intx)->x+1//Singledeclared-typeargument
(intx)->{returnx+1;}//sameasabove
(x)->x+1//Singleinferred-typeargument,sameasbelow
x->x+1//Parenthesisoptionalforsingleinferred-typecase
(Strings)->s.length()//Singledeclared-typeargument
(Threadt)->{t.start();}//Singledeclared-typeargument
s->s.length()//Singleinferred-typeargument
t->{t.start();}//Singleinferred-typeargument
(intx,inty)->x+y//Multipledeclared-typeparameters
(x,y)->x+y//Multipleinferred-typeparameters
(x,finaly)->x+y//Illegal:can’tmodifyinferred-typeparameters
(x,inty)->x+y//Illegal:can’tmixinferredanddeclaredtypes
MethodandConstructorReferences-
A method reference is used to refer to a method without invoking it; a constructor
referenceissimilarlyusedtorefertoaconstructorwithoutcreatinganewinstanceofthe
namedclassorarraytype.
Examplesofmethodandconstructorreferences:
1
2
3
System::getProperty
System.out::println
“abc”::length
4
5
ArrayList::new
int[]::new
That’sallforFunctionalInterfacesandLambdaExpressionTutorial,Iwouldstrongly
suggesttolookintousingitbecausethissyntaxisnewtoJavaanditwilltakesometime
tograspitanduseitinabetterway.
4.JavaStreamAPIforBulkDataOperationsonCollections-
Anewjava.util.streamhasbeenaddedinJava8toperformfilter/map/reducelike
operations with the collection. Stream API will allow sequential as well as parallel
execution.
ThisisoneofthebestfeatureformebecauseIworkalotwithCollectionsand
usuallywith BigData, weneed tofilteroutthembasedonsomeconditions.Collection
interface has been extended with STREAM() and PARALLELSTREAM() default
methodstogettheStreamforsequentialandparallelexecution.Let’sseetheirusagewith
simpleexample.
StreamExample.java
package com.journaldev.java8.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class StreamExample{
public static void main(String[]args){
List<Integer>myList=new ArrayList<>();
for(int i=0;i<100;i++)myList.add(i);
//sequentialstream
Stream<Integer>sequentialStream=myList.stream();
//parallelstream
Stream<Integer>parallelStream=myList.parallelStream();
//usinglambdawithStreamAPI,filterexample
Stream<Integer>highNums=parallelStream.filter(p->p>90);
//usinglambdainforEach
highNums.forEach(p->System.out.println(“HighNumsparallel=”+p));
Stream<Integer>highNumsSeq=sequentialStream.filter(p->p>90);
highNumsSeq.forEach(p->System.out.println(“HighNumssequential=”+p));
}
}
Ifyouwillrunaboveexamplecode,youwillgetoutputlikethis:
HighNumsparallel=91
HighNumsparallel=96
HighNumsparallel=93
HighNumsparallel=98
HighNumsparallel=94
HighNumsparallel=95
HighNumsparallel=97
HighNumsparallel=92
HighNumsparallel=99
HighNumssequential=91
HighNumssequential=92
HighNumssequential=93
HighNumssequential=94
HighNumssequential=95
HighNumssequential=96
HighNumssequential=97
HighNumssequential=98
HighNumssequential=99
Noticethatparallelprocessingvaluesarenotinorder,soparallelprocessingwillbevery
helpfulwhileworkingwithhugecollections.CoveringeverythingaboutStreamAPIisnot
possibleinthistopic,youcanreadeverythingaboutStreamAPIatJava8StreamAPI
Tutorialinnextchapter.
CHAPTER
∞23∞
Java8StreamAndTimeAPI
Java8StreamAPIExampleTutorial-
Inthelasttopics,welookedintoJava8InterfaceChangesandFunctionalInterfaces
andLambdaExpressions.
NowwewilllookintooneofthemajorAPIintroducedinJava8–JavaStreamAPI.
1.StreamAPIOverview.
2.CollectionsandStreams.
3.CommonlyusedFunctionalInterfacesinStream.
1.FunctionandBiFunction.
2.PredicateandBiPredicate.
3.ConsumerandBiConsumer.
4.Supplier.
4.java.util.Optional.
5.java.util.Spliterator.
6.IntermediateandTerminalOperations.
7.ShortCircuitingOperations.
8.JavaStreamExamples.
1.CreatingStreams.
2.ConvertingStreamtoCollectionorArray.
3.StreamIntermediateOperations.
4.StreamTerminalOperations.
9.JavaStreamAPILimitations.
StreamAPIOverview-
BeforewelookintoJava8StreamAPIExamples,let’sseewhyitwasrequired.Suppose
wewanttoiterateoveralistofintegersandfindoutsumofalltheintegersgreaterthan
10.PriortoJava8,theapproachtodoitwouldbe:
1
2
3
4
5
6
7
8
9
10
11
privatestaticintsumIterator(List<Integer>list){
Iterator<Integer>it=list.iterator();
intsum=0;
while(it.hasNext()){
intnum=it.next();
if(num>10){
sum+=num;
}
}
returnsum;
}
Therearethreemajorproblemswiththeaboveapproach:
1)Wejustwanttoknowthesumofintegersbutwewouldalsohavetoprovide
howtheiterationwilltakeplace,thisisalsocalledexternaliterationbecause
clientprogramishandlingthealgorithmtoiterateoverthelist.
2)The program is sequential in nature, there is no way we can do this in
paralleleasily.
3)Thereisalotofcodetodoevenasimpletask.
To overcome all the above shortcomings, Java 8 introduces Stream API. We can use
StreamAPI to implementinternaliteration, that is better because java framework is in
controloftheiteration.Internaliterationprovidesseveralfeaturessuchassequentialand
parallelexecution,filteringbasedonthegivencriteria,mappingetc.
Most of the Stream API method arguments are functional interfaces, so lambda
expressionsworkverywellwiththem.Let’sseehowcanwewriteabovelogicinasingle
linestatement.
1
2
3
privatestaticintsumStream(List<Integer>list){
returnlist.stream().filter(i->i>10).mapToInt(i->i).sum();
}
Notice that above program utilizes java framework iteration strategy, filtering and
mapping methods and would increase efficiency. First of all we will look into the core
concepts of Stream API and then we will go through some examples for understanding
mostcommonlyusedmethods.
CollectionsandStreams-
A collection is an in-memory data structure to hold values and before we start
usingcollection,all thevaluesshould havebeenpopulated. WhereasaStream isadata
structurethatiscomputedon-demand.
Streamdoesn’tstoredata,itoperatesonthesourcedatastructure(collectionand
array)andproducepipelineddatathatwecanuseandperformspecificoperations.Suchas
wecancreateastreamfromthelistandfilteritbasedonacondition.
Stream operations use functional interfaces, that makes it a very good fit for
functionalprogrammingusinglambdaexpressions.Asyoucanseeintheaboveexample
thatusinglambdaexpressionsmakeourcodereadableandshort.
Streaminternaliterationprinciplehelpsinachievinglazy-seekinginsomeofthe
stream operations. For example filtering, mapping, or duplicate removal can be
implementedlazily,allowinghigherperformanceandscopeforoptimization.
Streamsare consumable,sothere isno way tocreate a referenceto streamfor
future usage. Since the data is on-demand, it’s not possible to reuse the same stream
multipletimes.
Streamsupportsequentialaswellasparallelprocessing,parallelprocessingcan
beveryhelpfulinachievinghighperformanceforlargecollections.
All the Stream API interfaces and classes are in the java.util.stream package.
Since we can use primitive data types such as int, long in the collections using auto-
boxingandtheseoperationscouldtakealotoftime,therearespecificclassesforthese–
IntStream,LongStreamandDoubleStream.
CommonlyusedFunctionalInterfacesinStream-
SomeofthecommonlyusedfunctionalinterfacesintheStreamAPImethodsare:
1.FunctionandBiFunction:
Function represents a function that takes one type of argument and returns another
type of argument. Function is the generic form where T is the type of the input to the
functionandRisthetypeoftheresultofthefunction.Forhandlingprimitivetypes,there
arespecificFunctioninterfaces-
ToIntFunction, ToLongFunction, ToDoubleFunction, ToIntBiFunction,
ToLongBiFunction,ToDoubleBiFunction, LongToIntFunction, LongToDoubleFunction,
IntToLongFunction,IntToDoubleFunctionetc.
SomeoftheStreammethodswhereFunctionorit’sprimitivespecializationisusedare:
<R>Stream<R>map(Function<?superT,?extendsR>mapper)
IntStreammapToInt(ToIntFunction<?superT>mapper)–similarlyforlong
anddoublereturningprimitivespecificstream.
IntStreamflatMapToInt(Function<?superT,?extendsIntStream>mapper)–
similarlyforlonganddouble
<A>A[]toArray(IntFunction<A[]>generator)
<U>Ureduce(Uidentity,BiFunction<U,?superT,U>accumulator,
BinaryOperator<U>combiner)
2.PredicateandBiPredicate:
Itrepresentsapredicateagainstwhichelementsofthestreamaretested.Thisisused
tofilterelementsfromthestream.JustlikeFunction,thereareprimitivespecificinterfaces
forint,longanddouble.
SomeoftheStreammethods-wherePredicateorBiPredicatespecializationsareusedare:
Stream<T>filter(Predicate<?superT>predicate)
booleananyMatch(Predicate<?superT>predicate)
booleanallMatch(Predicate<?superT>predicate)
booleannoneMatch(Predicate<?superT>predicate)
3.ConsumerandBiConsumer:
Itrepresentsanoperationthatacceptsasingleinputargumentandreturnsnoresult.Itcan
be used to perform some action on all the elements of the stream.Some of the Stream
methodswhereConsumer,BiConsumerorit’sprimitivespecializationinterfacesareused
are:
Stream<T>peek(Consumer<?superT>action)
voidforEach(Consumer<?superT>action)
voidforEachOrdered(Consumer<?superT>action)
4.Supplier:Supplierrepresentanoperationthroughwhichwecangeneratenewvaluesin
thestream.SomeofthemethodsinStreamthattakesSupplierargumentare:
publicstatic<T>Stream<T>generate(Supplier<T>s)
<R> R collect(Supplier<R> supplier,BiConsumer<R, ? super T>
accumulator,BiConsumer<R,R>combiner)
java.util.Optional-
Optionalisacontainerobjectwhichmayormaynotcontainanon-nullvalue.Ifavalueis
present,isPresent() will return true and get() will return the value. Stream terminal
operationsreturnOptionalobject.Someofthesemethodsare:
Optional<T>reduce(BinaryOperator<T>accumulator)
Optional<T>min(Comparator<?superT>comparator)
Optional<T>max(Comparator<?superT>comparator)
Optional<T>findFirst()
Optional<T>findAny()
java.util.Spliterator-
For supporting parallel execution in Stream API, Spliterator interface is used.
SpliteratortrySplitmethodreturnsanewSpliteratorthatmanagesasubsetoftheelements
oftheoriginalSpliterator.
IntermediateandTerminalOperations-
Stream API operations that returns a new Stream are called intermediate
operations.Mostofthetimes,theseoperationsarelazyinnature,sotheystart
producingnewstreamelementsandsendittothenextoperation.Intermediate
operationsareneverthefinalresultproducingoperations.
Commonly used intermediate operations are filter and map.Stream API
operations that returns a result or produce a side effect. Once the terminal
method is called on a stream, it consumes the stream and after that we can’t
use stream. Terminal operations are eager in nature i.e they process all the
elementsinthestreambeforereturningtheresult.
Commonly used terminal methods are forEach, toArray, min, max, findFirst,
anyMatch, allMatch etc. You can identify terminal methods from the return
type,theywillneverreturnaStream.
ShortCircuitingOperations-
An intermediate operation is called short circuiting, if it may produce finite
stream for an infinite stream. For example limit() and skip() are two short circuiting
intermediateoperations.
Aterminaloperationiscalledshortcircuiting,ifitmayterminateinfinitetime
forinfinitestream.For exampleanyMatch,allMatch,noneMatch,findFirstandfindAny
areshortcircuitingterminaloperations.
JavaStreamExamples-
IhavecoveredalmostalltheimportantpartsoftheJavaStreamAPI.It’sexcitingtouse
thisnewAPIfeaturesandlet’sseeitinactionwithsomeexamples.
CreatingStreams-
Thereareseveralwaysthroughwhichwecancreateastreamfromarrayandcollections.
Let’slookintothesewithsimpleexamples.
1.WecanuseStream.of()tocreateastreamfromsimilartypeofdata.Forexample,we
cancreateStreamofintegersfromagroupofintorIntegerobjects.
1 Stream<Integer>stream=Stream.of(1,2,3,4);
2. We can use Stream.of() with an array of Objects to return the stream. Note that it
doesn’tsupportautoboxing,sowecan’tpassprimitivetypearray.
1
2
3
4
5
Stream<Integer>stream=Stream.of(newInteger[]{1,2,3,4});
//worksfine
Stream<Integer>stream1=Stream.of(newint[]{1,2,3,4});
//Compiletimeerror,Typemismatch:cannotconvertfromStream<int[]>to
Stream<Integer>
3. We can use Collection stream() to create sequential stream and parallelStream() to
createparallelstream.
1
2
3
4
5
6
List<Integer>myList=newArrayList<>();
for(inti=0;i<100;i++)myList.add(i);
//sequentialstream
Stream<Integer>sequentialStream=myList.stream();
//parallelstream
Stream<Integer>parallelStream=myList.parallelStream();
4.WecanuseStream.generate()andStream.iterate()methodstocreateStream.
1
2
Stream<String>stream1=Stream.generate(()->{return“abc”;});
Stream<String>stream2=Stream.iterate(“abc”,(i)->i);
5.UsingArrays.stream()andString.chars()methods.
1
2
LongStreamis=Arrays.stream(newlong[]{1,2,3,4});
IntStreamis2=“abc”.chars();
ConvertingStreamtoCollectionorArray-
ThereareseveralwaysthroughwhichwecangetaCollectionorArrayfromaStream.
1.WecanuseStreamcollect()methodtogetList,MaporSetfromstream.
1
2
3
4
5
6
Stream<Integer>intStream=Stream.of(1,2,3,4);
List<Integer>intList=intStream.collect(Collectors.toList());
System.out.println(intList);//prints[1,2,3,4]
intStream=Stream.of(1,2,3,4);//streamisclosed,soweneedtocreateitagain
Map<Integer,Integer>intMap=intStream.collect(Collectors.toMap(i->i,i->i+10));
System.out.println(intMap);//prints{1=11,2=12,3=13,4=14}
2.WecanusestreamtoArray()methodtocreateanarrayfromthestream.
1
2
3
Stream<Integer>intStream=Stream.of(1,2,3,4);
Integer[]intArray=intStream.toArray(Integer[]::new);
System.out.println(Arrays.toString(intArray));//prints[1,2,3,4]
StreamIntermediateOperations-Let’slookintocommonlyusedStream
intermediateoperationsexample.
1. Stream filter() example: We can use filter() method to test stream elements for a
conditionandgeneratefilteredlist.
1
2
3
4
5
6
List<Integer>myList=newArrayList<>();
for(inti=0;i<100;i++)myList.add(i);
Stream<Integer>sequentialStream=myList.stream();
Stream<Integer>highNums=sequentialStream.filter(p->p>90);//filternumbers
greaterthan90
System.out.print(“HighNumsgreaterthan90=”);
highNums.forEach(p->System.out.print(p+”“));
7 //prints“HighNumsgreaterthan90=919293949596979899“
2.Streammap()example:Wecanusemap()toapplyfunctionstoanstream.Let’ssee
howwecanuseittoapplyuppercasefunctiontoalistofStrings.
1
2
3
4
5
Stream<String>names=Stream.of(“aBc”,“d”,“ef”);
System.out.println(names.map(s->{
returns.toUpperCase();
}).collect(Collectors.toList()));
//prints[ABC,D,EF]
3.Streamsorted()example:Wecanusesorted()tosortthestreamelementsbypassing
Comparatorargument.
1
2
3
4
5
6
7
Stream<String>names2=Stream.of(“aBc”,“d”,“ef”,“123456”);
List<String>reverseSorted=
names2.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println(reverseSorted);//[ef,d,aBc,123456]
Stream<String>names3=Stream.of(“aBc”,“d”,“ef”,“123456”);
List<String>naturalSorted=names3.sorted().collect(Collectors.toList());
System.out.println(naturalSorted);//[123456,aBc,d,ef]
4.StreamflatMap()example:WecanuseflatMap()tocreateastreamfromthestreamof
list.Let’sseeasimpleexampletoclearthisdoubt.
1
2
3
4
5
6
Stream<List<String>>namesOriginalList=Stream.of(
Arrays.asList(“Pankaj”),
Arrays.asList(“David”,“Lisa”),
Arrays.asList(“Amit”));
//flatthestreamfromList<String>toStringstream
Stream<String>flatStream=namesOriginalList
7
8
.flatMap(strList->strList.stream());
flatStream.forEach(System.out::println);
StreamTerminalOperations-
Let’slookatsomeoftheterminaloperationsexample.
1.Streamreduce()example:Wecanusereduce()toperformareductionontheelements
ofthestream, using anassociative accumulation function,and return an Optional.Let’s
seehowwecanuseitmultiplytheintegersinastream.
1
2
3
Stream<Integer>numbers=Stream.of(1,2,3,4,5);
Optional<Integer>intOptional=numbers.reduce((i,j)->{returni*j;});
if(intOptional.isPresent())System.out.println(“Multiplication=“+intOptional.get());
//120
2.Streamcount()example:Wecanusethisterminaloperationtocountthenumberof
itemsinthestream.
1
2
Stream<Integer>numbers1=Stream.of(1,2,3,4,5);
System.out.println(“Numberofelementsinstream=”+numbers1.count());//5
3.StreamforEach()example:Thiscanbeusedforiteratingoverthestream.Wecanuse
thisinplaceofiterator.Let’sseehowtouseitforprintingalltheelementsofthestream.
1
2
Stream<Integer>numbers2=Stream.of(1,2,3,4,5);
numbers2.forEach(i->System.out.print(i+”,”));//1,2,3,4,5,
4.Streammatch()examples:Let’ssee someof theexamplesfor matchingmethods in
StreamAPI.
1
2
3
4
5
6
Stream<Integer>numbers3=Stream.of(1,2,3,4,5);
System.out.println(“Streamcontains4?“+numbers3.anyMatch(i->i==4));
//Streamcontains4?true
Stream<Integer>numbers4=Stream.of(1,2,3,4,5);
System.out.println(“Streamcontainsallelementslessthan10?“+numbers4.allMatch(i->
i<10));
7
8
9
10
//Streamcontainsallelementslessthan10?true
Stream<Integer>numbers5=Stream.of(1,2,3,4,5);
System.out.println(“Streamdoesn’tcontain10?“+numbers5.noneMatch(i->i==10));
//Streamdoesn’tcontain10?true
5.StreamfindFirst()example:Thisisashortcircuitingterminaloperation,let’sseehow
wecanuseittofindthefirststringfromastreamstartingwithD.
1
2
3
4
5
Stream<String>names4=Stream.of(“Pankaj”,“Amit”,“David”,“Lisa”);
Optional<String>firstNameWithD=names4.filter(i->i.startsWith(“D”)).findFirst();
if(firstNameWithD.isPresent()){
System.out.println(“FirstNamestartingwithD=”+firstNameWithD.get());//David
}
JavaStreamAPILimitations-
Stream API brings a lot of new stuffs to work with list and arrays, but it has some
limitationstoo.
1.Statelesslambdaexpressions:Ifyouareusingparallelstreamandlambdaexpressions
arestateful,itcanresultinrandomresponses.Let’sseeitwithasimpleprogram.
StatefulParallelStream.java
1
2
3
4
5
6
7
8
9
10
11
12
13
packagecom.journaldev.java8.stream;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.List;
importjava.util.stream.Stream;
publicclassStatefulParallelStream{
publicstaticvoidmain(String[]args){
List<Integer>ss=Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
List<Integer>result=newArrayList<Integer>();
Stream<Integer>stream=ss.parallelStream();
stream.map(s->{
synchronized(result){
if(result.size()<10){
14
15
16
17
18
19
20
result.add(s);
}
}
returns;
}).forEach(e->{});
System.out.println(result);
}}
If we run above program, you will get different results because it depends on the way
streamisgettingiteratedandwedon’thaveanyorderdefinedforparallelprocessing.If
weusesequentialstream,thenthisproblemwillnotarise.
2.OnceaStreamisconsumed,itcan’tbeusedlateron.Asyoucanseeinaboveexamples
thateverytimeIamcreatingastream.
3.TherearealotofmethodsinStreamAPIandthemostconfusingpartistheoverloaded
methods.Itmakesthelearningcurvetimetaking.
That’sallforStreamAPIinJava.Iamlookingforwardtousethisfeatureandmakethe
codereadablewithbetterperformancethroughparallelprocessing.
5.JavaTimeAPI-
IthasalwaysbeenhardtoworkwithDate,TimeandTimeZonesinjava.There
was no standard approach or API in java for date and time in Java. One of the nice
additioninJava8isthejava.timepackagethatwillstreamlinetheprocessofworkingwith
timeinjava.
JustbylookingatJavaTimeAPIpackages,Icansensethatitwillbeveryeasyto
use. It has some sub-packages java.time.format that provides classes to print and parse
datesandtimesandjava.time.zoneprovidessupportfortime-zonesandtheirrules.
ThenewTimeAPIprefersenumsoverintegerconstantsformonthsanddaysof
theweek.OneoftheusefulclassisDateTimeFormatterforconvertingdatetimeobjectsto
strings.
6.CollectionAPIimprovements-
We have already seen forEach() method and Stream API for collections. Some
newmethodsaddedinCollectionAPIare:
Iteratordefaultmethodfor-EachRemaining(Consumeraction)toperformthe
givenactionforeachremainingelementuntilallelementshavebeenprocessed
ortheactionthrowsanexception.
Collectiondefaultmethod-removeIf(Predicatefilter)toremoveallofthe
elementsofthiscollectionthatsatisfythegivenpredicate.
Collection spliterator() method- returning Spliterator instance that can be
usedtotraverseelementssequentiallyorparallel.
MapreplaceAll(),compute(),merge()methods.
7.ConcurrencyAPIimprovements-
SomeimportantconcurrentAPIenhancementsare:
a)ConcurrentHashMapcompute(), forEach(),forEachEntry(), forEachKey(),
forEachValue(),merge(),reduce()andsearch()methods.
b)CompletableFuturethatmaybeexplicitlycompleted(settingitsvalueand
status).
c)ExecutorsnewWorkStealingPool()methodtocreateawork-stealingthread
poolusingallavailableprocessorsasitstargetparallelismlevel.
8.JavaIOimprovements-
SomeIOimprovementsknowntomeare:
d)Files.list(Pathdir)thatreturnsalazilypopulatedStream,theelementsof
whicharetheentriesinthedirectory.
e)Files.lines(Pathpath)thatreadsalllinesfromafileasaStream.
f)Files.find() that returns a Stream that is lazily populated with Path by
searchingforfilesinafiletreerootedatagivenstartingfile.
g)BufferedReader.lines()thatreturnaStream,theelementsofwhicharelines
readfromthisBufferedReader.
9.MiscellaneousCoreAPIimprovements-
SomemiscAPIimprovementsthatmightcomehandyare:
h)ThreadLocalstaticmethodwithInitial(Suppliersupplier)tocreateinstance
easily.
i)Comparator interface has been extended with a lot of default and static
methodsfornaturalordering,reverseorderetc.
j)min(), max() and sum() methods in Integer, Long and Double wrapper
classes.
k)logicalAnd(),logicalOr()andlogicalXor()methodsinBooleanclass.
l)ZipFile.stream()methodtogetanorderedStreamovertheZIPfileentries.
EntriesappearintheStreamintheordertheyappearinthecentraldirectoryof
theZIPfile.
m)SeveralutilitymethodsinMathclass.
That’sallformajorimprovementsinJava8.
BothPhysicalPaperbackandDigitalEditionsAreAvailableonLuLu.com&
Amazon.com(PaperbackEditions)
GoogleBooks&GooglePlayBookStores(PDF)
OrdertodayandGetaDiscountedCopy.
JoinmeonFacebook-https://www.facebook.com/harry.novelist
https://www.facebook.com/CaptainHarrychoudhary?ref=hl
CHAPTER
∞24∞
KeyFeaturesthatMakeJava
MoreSecurethanOtherLanguages.
Today,Javaisdrivingmorethan$100billionofbusinessannually.Ifwetakealookatthe
enterprise side, more than $2.2 billion are being spent by the enterprises in Java
applicationserver.
ThereisnodenyingthatJavaisusedextensivelyfordevelopingJavaenterprise
applicationsreason being Security. Java bringssome of the mostfascinating features or
benefitsthatareimpossibletofindinanyotherprogramminglanguagesorplatforms.
SecurityisanimportantaspectandJava’ssecuritymodelisoneofthekeyarchitectural
features that make it most trustful choice when it comes to developing enterprise-level
applications.Securitybecomescriticalwhensoftwareisdownloadedacrossnetworkand
executedlocally,andJavaeasilymitigatesthesecurityvulnerabilitiesassociatedwiththe
projects or applications. Don’t believe this? Have a look at a few arguments (security
measures/features)thatshowcasehowsecureJavaplatformis.
Java’ssecuritymodel
Java’s security model is intended to help and protect users from hostile programs
downloadedfromsomeun-trustedresourcewithinanetworkthrough“sandbox”.Itallows
alltheJavaprogramstoruninsidethesandboxonlyandpreventsmanyactivitiesfromun-
trustedresourcesincludingreadingorwritingtothelocaldisk,creatinganynewprocess
orevenloadinganynewdynamiclibrarywhilecallinganativemethod.
Nouseofpointers
C/C++languageusespointers, whichmaycauseunauthorizedaccess tomemoryblocks
whenother programsgetthe pointervalues. UnlikeconventionalC/C++language,Java
neverusesanykindofpointers.Javahasitsinternalmechanismformemorymanagement.
Itonlygivesaccesstothedatatotheprogramifhasappropriateverifiedauthorization.
Exceptionhandlingconcept
The concept of exception handling enables Java to capture a series of errors that helps
developerstogetridofriskofcrashingthesystem.
Definedorderexecution
Alltheprimitivesaredefinedwithapredefinedsizeandalltheoperationsaredefinedina
specific order of execution. Therefore, the code executed in different Java Virtual
Machineswon’thaveadifferentorderofexecution.
BytecodeisanotherthingthatmakesJavamoresecure
EverytimewhenausercompilestheJavaprogram,theJavacompilercreatesaclassfile
withBytecode,whicharetestedbytheJVMatthetimeofprogramexecutionforviruses
andothermaliciousfiles.
Testedcodere-usability
The Java object encapsulation provides support for the concept of “programming by
contract”.Thisallowsthedeveloperstore-usethecodethathasalreadybeentestedwhile
developingJavaenterpriseapplications.
AccessControlfunctionality
Java’s access-control functionality on variables and methods within the objects provide
secureprogrambypreventingaccesstothecriticalobjectsfromtheun-trustedcode.
Protectionfromsecurityattacks
ItallowsdeveloperstodeclareclassesormethodsasFINAL.Weallknowthatanyclass
ormethoddeclaredasfinalcan’tbeoverridden,whichhelpsdeveloperstoprotectcode
fromsecurityattackslikecreatingasubclassandreplacingitwiththeoriginalclassand
overridemethods.
Garbagecollectionmechanism
GarbagecollectionmechanismaidsmoretothesecuritymeasuresofJava.Itprovidesa
transparentstorageallocationandrecoveringunutilizedmemoryratherthande-allocating
memory through manual action. It will help developers to ensure the integrity of the
program during its execution and avoids any JVM crash due to incorrect freeing of
memory.
Type-safereferencecastinginJVM
Whenever you use an object reference, the JVM monitors you. If you try to cast a
referencetoadifferenttype,itwillmakethecastinvalid.
Apartfromallthese,structured errorhandlingcontributesalottothesecuritymodelof
Java by helping to enhance the robustness of the programs. The above arguments
definitelyprove thatthe projectsdevelopedinJavaare moresecure ascompared tothe
otherprogramminglanguage.However,itistheresponsibilityofthedeveloperstofollow
somebestpracticeswhiledevelopingenterprise-levelJavaapplications.