Introduction to Java Programming

605

Transcript of Introduction to Java Programming

IntroductiontoJavaProgramming

AdvancedFeatures(CoreSeries)

UpdatedToJava8.

-Harry.H.Chaudhary.

(ITManager&AnonymousHacktivist@AnonymousInternational)

Publisher’sNote:

Everypossibleefforthasbeenmadetoensurethattheinformationcontainedinthisbook is accurate, and the publisher or the Author–Harry. H. Chaudhary can’t acceptresponsibility for any errors or omissions, however caused. All liability for loss,disappointment, negligence or other damage caused by the reliance of the TechnicalProgrammingorotherinformationcontainedinthisbook,ofintheeventofbankruptcyorliquidationorcessationoftradeofanycompany,individual;orfirmmentioned,isherebyexcluded.

SunMicrosystemsandOraclethetrademarks,aretheTrademarksoftheSun(NowOracle)&Oraclegroupofcompanies.SunMicrosystemsandOraclethetrademarksarelisted at their websites. All other marks are property of their respective owners. Theexamplesof companies, organizations, products, domainnames, email addresses, logos,people, places, and events depicted herein are fictitious. No association with any realcompany,organization,product,domainname,emailaddress,logo,person,place,oreventisintendedorshouldbeinferred.

Theauthorandpublisherhavetakencareinthepreparationofthisbook,butmakenoexpressedor impliedwarrantyofanykindandassumenoresponsibilityforerrorsoromissions.Noliabilityisassumedforincidentalorconsequentialdamagesinconnectionwithorarisingoutoftheuseoftheinformationorprogramscontainedherein.

This book expresses the author views and opinions. The information contained inthis book is providedwithout any express, statutory, or impliedwarranties.Neither theauthors,andPublisher,noritsresellers,ordistributorswillbeheldliableforanydamagescausedorallegedtobecausedeitherdirectlyorindirectlybythisbook.

Copyright©2010-2014.ByHarry.H.Chaudhary(CEOProgrammersMind.)PublishedByProgrammersMind||CreatespaceInc.ODPublishing,LLCUSA.

Allrightsreserved.Thisbookoranyportionthereofmaynotbereproducedorusedinanymannerwhatsoeverwithouttheexpresswrittenpermissionoftheauthorexceptfortheuseofbriefquotationsinabookrevieworscholarlyjournal.

ISBN-13:978-1500864514.

ISBN-10:1500862347.

PrintedByCreatespaceO-DPublishingLLCUSA.[SECONDEDITION 2014 ]

Marketing&DistributedBy||AmazonInc.||Programmer’sMindInc.||Lulu.com

||GoogleBooks&GooglePlayStore.||other25worldwideBookstores.

Dedication

“Thisbookisdedicatedtoallthosewhomakethedailysacrifices,

Especiallythosewho’vemadesacrifice,toensureourfreedom&security.”

ThankstoLordShivaalotforgivingmethetechnicalandallabilitiesinmylifetowrite.

DearDad,Thankyoubaauji,forteachingmebyexamplewhatitmeanstolivealifebasedonprinciples.

Dear2Mom’s,Thankyouforshowingmeinarealwayhowtoliveaccordingtothemostimp.principle,andunconditionallove.

DearSisters&Brother+Priya,ThankU,yoursmilebrightensmyeveryday.Yourzestmakesmyheartsing.IloveyouAll.

Iwouldespeciallyliketomentionthenameofbeautifulfacesinsidemylifewhohelpedmeincopingwithmysorrows:

ThankyouPriyanka,youarethemeaningofmylifeandappleofmyeyes,ILoveYoumorethanIcansay.

ThankUHemZizu,Navneet,Aman(Rajjo)Eminem-youaretheinspirationyoumademelike“Singforthemovement”,

ThankstoallAnonymousAndBlackHatHackersworldwide.

InLovingMemoriesofMyLovedOne–MyUncleLt.G.C

InLovingMemoriesofMyLovedOne–MyLt.GrandMom.

Youtoldmethateverythingwillbeokayintheend,

Youalsotoldmethat,ifit’snotokay,it’snottheend.

“I’llsearchforyouthrough1000worlds&10000lifetimesuntilIfindyou

AboutAuthor:

Harry,is an Anonymous Hacktivist, GOC Famous computer Programmer and

BestsellingJavaAuthorandscientificallyHackingProfessionalhasauniqueexperienceinthefieldofcomputersProgramming,HackingandCyberSecurity.

He has helped many Countries Governments and many multinational Software

companiesofaround theglobe to secure theirnetworksandsecurities.HehasauthoredseveralbooksonVariousComputersProgrammingLanguagesandcomputersecurity&Hacking.

HeistechnicallygraduatesoftwareengineerandMaster.HeistheleadingauthorityonCProgrammingandC++ProgrammingaswellasonCoreJavaandDataStructureandAlgorithms.His acclaimedC andC++ ,C#& Java books.He has over 5 years ofexperience as a software methodologist. His teaching and research interests are in theareasofartificialintelligence,programminglanguages.

Heislivingtwolives.Onelife,HeisaComputerprogramwriterforarespectablesoftwarecompany.Theother life is lived incomputers,wherehegoby thehackeralias“ChiefHacker–CaptainHarry”.CurrentlyheisworkingasofflineITmanager@worldfamouscommunityAnonymousinternationalCommunity.-TeamAnonymous.

Authorside:You may have noticed something missing here: no impressive of credentials. I

haven’tbeenaprofessorataPrestigiousUniversityforaquarter-century;neitheramIatopexecutiveataSiliconValleygiant. Insomeways, I’mastudentofTechnology, justlikeyouare.

Andmyexperienceovertheyearshasshownmethatmanyofthepeoplewhoknowthemostabouthowtechnologyworksalsohaveratherlimitedsuccessinexplainingwhattheyknow inaway thatwill allowme tounderstand it.My interests, and Ibelievemyskills,lienotinbeinganexpert,butaneducator,inpresentingcomplexinformationinaformthatissensible,digestibleandfuntoreadmybooks.

“Whatisreal?Howdoyoudefinereal?Ifyou’retalkingaboutwhatyoucanfeel,whatyoucansmell,whatyoucantasteandsee,thenrealissimply,electricalsignalsinterpretedbyyourbrain.”

‘‘…Iamjustnowbeginningtodiscoverthedifficultyofexpressingone’sideasonpaper. As longas itconsistssolelyofdescription it isprettyeasy;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 fromBestsellerJavaProgrammingAuthorHarry.H.Chaudhary(Morethan1,67,000BooksSold!).ThisJavaGuide,startswiththebasicsandLeadstoAdvancefeaturesofJava indetailwith thousandsofJavaCodes, Ipromise thisbookwillmakeyouexpertlevelchampionofjava.Anyonecanlearnjavathroughthisbookatexpertlevel.

Engineering Students and fresh developers can also use this book. This bookcoverscommoncoresyllabusforallComputerScienceProfessionalDegrees Ifyouarereallyseriousthengoaheadandmakeyourdaywiththisultimatejavabook.

Themainobjectiveof this javabook isnot togiveyou justJavaProgrammingKnowledge,IhavefollowedapatternofimprovingthequestionsolutionofthousandsofCodeswithcleartheoryexplanationswithdifferentJavacomplexitiesforeachjavatopicproblem,andyouwillfindmultiplesolutionsforcomplexjavaproblems.

WhatSpecial–

InthisbookIcoveredandexplainedseveraltopicsoflatestJava8FeaturesindetailforDevelopers&Fresher’s,TopicsLike–Lambdas.||Java8Functionalinterface,||StreamandTimeAPIinJava8.

If you’ve read this book, you know what to expect a visually rich formatdesigned for thewayyourbrainworks. If youhaven’t, you’re in for a treat.You’ll seewhypeoplesayit’sunlikeanyotherJavabookyou’veeverread.

Learninganewlanguageisnoeasytaskespeciallywhenit’sanObjectorientedprogramminglanguagelikeJava.Youmightthinktheproblemisyourbrain.Itseemstohaveamindofitsown,amindthatdoesn’talwayswanttotakeinthedry,technicalstuffyou’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, ifyoucomefromaCorC++programmingbackground,thenyouwillbeabletolearnfaster.

Forthisreason,thisjavabookpresentsaquickdetailedoverviewofseveralkeyfeaturesofJava.Thematerialdescribedherewillgiveyouafootholdthatwillallowyoutowriteandunderstandsimple&typicalprograms.Mostofthetopicsdiscussedwillbeexamined in greater detail in upcoming chapters with thousands of live java codeexamples.

Aswe know in the past few years document the following fact: TheWeb hasirrevocably recast the face of computing and programmers unwilling to master itsenvironmentwillbeleftbehind.Theprecedingisastrongstatement.Itisalsotrue.

More and more, applications must interface to the Web. It no longer mattersmuchwhattheapplicationis,nearuniversalWebaccessisdragging,pushing,andcoaxingprogrammerstoprogramfortheonlineworld,andJavaisthelanguagethatmanywillusetodoit.Frankly,fluencyinJavaisnolongeranoptionfortheprofessionalprogrammer,itisarequirement.Thisbookwillhelpyouacquireit.

CHAPTER∞1∞

(OverviewofJava)

Introduction-Java is a powerful object oriented programming language developed by Sun

MicrosystemsInc.in1991.Javawasdevelopedforconsumerelectronicdevicesbutlaterit was shifted towards Internet. Now Java has become the widely used programminglanguage for the Internet. Java is a platform neutral language (Machine Independent).ProgramdevelopedbyJavacanrunonanyhardwareoronanyoperatingsysteminthisworld.

SunMicrosystems (Oracle) formally announced Java at amajor conference inMay 1995. Ordinarily, an event like this would not have generated much attention.However, Java generated immediate interest in the business community because of thephenomenalinterestintheWorldWideWeb.

Java isnowused tocreateWebpageswithdynamicand interactivecontent, todeveloplarge-scaleenterpriseapplications,toenhancethefunctionalityofWorldWide

NeedforJava-

Javawasdevelopedduetotheneedforaplatformneutrallanguagethatcouldbeused tocreatesoftware tobeembedded invariousconsumerelectronicdevices, suchasmicrowaveovensandremotecontrols.TheprogramwritteninCandC++arecompiledforaparticularpieceofhardwareandsoftwareandthatprogramwillnotrunonanyotherhardware or software. So we need C/C++ compilers one for each type of hardware tocompileasingleprogram.Butcompilersareexpensiveandtime-consumingtocreate.Sothere is a need for platform neutral language. So that program compiled from thatcompilercanrunonanyhardware.ThisneedledtothecreationofJava.

JavaClassLibraries-

Javaprograms consist of pieces called classes.Classes consist of pieces calledmethods thatperform tasksand return informationwhen theycomplete their tasks.Youcan program each piece you may need to form a Java program. However, most JavaprogrammerstakeadvantageofrichcollectionsofexistingclassesinJavaclasslibraries.TheclasslibrariesarealsoknownastheJavaAPIs(ApplicationProgrammingInterfaces).

Thus, there are really two pieces to learning the Java “world.” The first islearningtheJavalanguageitselfsothatyoucanprogramyourownclasses;thesecondislearninghowtousetheclassesintheextensiveJavaclasslibraries.

Throughout the book, we discuss many library classes. Class libraries areprovided primarily by compiler vendors, but many class libraries are supplied byindependent software vendors (ISVs).Also,many class libraries are available from theInternet andWorldWideWeb as freeware or shareware. You can download free wareproductsandusethemforfreesubjecttoanyrestrictionsspecifiedbythecopyrightowner.

BasicsofaTypicalJavaEnvironment-

Java systemsgenerally consist of several parts:An environment, the language,the Java Applications Programming Interface (API) and various class libraries. Thefollowing discussion explains a typical Java program development environment, Javaprogramsnormallygothroughfivephasestobeexecuted.Theseare:edit,compile,load,verify and execute. The descriptions that follow use the standard Java SE 7DevelopmentKit(JDK7),whichisavailablefromOracle.

IfyouareusingadifferentJavadevelopmentenvironment,thenyoumayneedtofollowadifferentprocedureforcompilingandexecutingJavaprograms.Inthiscase,consultyourcompiler’sdocumentationfordetails.

Note: If you are not using UNIX/Linux, Windows 95/98/ME or WindowsNT/2000,refertothemanualsforyoursystem’sJavaenvironmentoraskyourinstructorhowtoaccomplishthesetasksinyourenvironment(whichwillprobablybesimilartotheenvironment,Phase1consistsofeditingafile.

Thisisaccomplishedwithaneditorprogram(normallyknownasaneditor).TheprogrammertypesaJavaprogram,usingtheeditor,andmakescorrections, ifnecessary.Whentheprogrammerspecifiesthatthefileintheeditorshouldbesaved,theprogramisstoredonasecondarystoragedevice,suchasadisk.Javaprogramfilenamesendwiththe.javaextension.

TwoeditorswidelyusedonUNIX/Linuxsystemsareviandemacs.OnWindows95/98/MEandWindowsNT/2000,simpleeditprogramsliketheDOSEditcommandandtheWindowsNotepadwillsuffice.

Java integrated development environments (IDEs), such as Forte for JavaCommunity Edition, NetBeans, Borland’s JBuilder, Symantec’s Visual Cafe and IBM’sVisualAgehavebuiltineditorsthatareintegratedintotheprogrammingenvironment.

We assume the reader knows how to edit a file. Languages such as Java areobject-oriented—programminginsuchalanguageiscalledobject-orientedprogramming(OOP)andallowsdesignerstoimplementtheobjectorienteddesignasaworkingsystem.Languages such as C, on the other hand, are procedural programming languages, soprogrammingtendstobeaction-oriented.

InC,theunitofprogrammingisthefunction.InJava,theunitofprogrammingistheclassfromwhichobjectsareeventuallyinstantiated(afancytermfor“created”).Javaclasses containmethods (that implement classbehaviors) andattributes (that implementclassdata).

Cprogrammersconcentrateonwritingfunctions.Groupsofactionsthatperformsome common task are formed into functions, and functions are grouped to formprograms.Dataarecertainly important inC,but theview is thatdataexistprimarily insupportoftheactionsthatfunctionsperform.TheverbsinasystemspecificationhelptheCprogrammerdeterminethesetoffunctionsneededtoimplementthatsystem.

Java programmers concentrate on creating their own user-defined types calledclassesandcomponents.Eachclasscontainsdataandthesetoffunctionsthatmanipulatethatdata.ThedatacomponentsofaJavaclassarecalledattributes.

ThefunctioncomponentsofaJavaclassarecalledmethods.Justasaninstanceofabuilt-intypesuchasintiscalledavariable,aninstanceofauser-definedtype(i.e.,aclass)iscalledanobject.Theprogrammerusesbuilt-intypesasthe“buildingblocks”forconstructinguser-definedtypes.

The focus in Java is on classes (out ofwhichwemakeobjects) rather thanonfunctions.ThenounsinasystemspecificationhelptheJavaprogrammerdeterminethesetof classes fromwhich objectswill be created thatwillwork together to implement thesystem.

Classes are to objects as blueprints are to houses.We can buildmany housesfromoneblueprint,andwecaninstantiatemanyobjectsfromoneclass.Classescanalsohaverelationshipswithotherclasses.

Forexample,inanobject-orienteddesignofabank,the“bankteller”classneedstorelatetothe“customer”class.Theserelationshipsarecalledassociations.Wewillseethat,whensoftwareispackagedasclasses,theseclassescanbereusedinfuturesoftwaresystems.Groupsofrelatedclassesareoftenpackagedasreusablecomponents.

Eachnewclassyoucreatewillhavethepotentialtobecomeavaluablesoftwareassetthatyouandotherprogrammerscanusetospeedandenhancethequalityoffuturesoftware-developmentefforts—anexcitingpossibility.

RelationofJavawithC,C++,&C#

FromCJavaderivesitssyntaxandfromC++itderivesobjectorientedfeatures.It is not an enhanced version of C++. Java is neither upwardly nor downwardlycompatiblewithC++.OneimportantthingthatIwanttotellyouisthatJavalanguagewasnotdesignedtoreplaceC++andC#.AnotherlanguagedevelopedbyMicrosofttosupportthe .NETFramework,C# isclosely related toJavabecausebothshareC++andCstylesyntax,supportdistributedprogramming,andutilizethesameobjectmodel.

PrimaryObjectiveofJavaistoachieve-

1. Security:-

ThereisnothreatofvirusinfectionwhenweuseJavacompatibleWebBrowser.Also there isno threatofmaliciousprograms that cangatherprivateinformation,suchascreditcardnumbers,bankaccountbalancesandpasswordsfromlocalmachine.

Javaprovidesafirewallbetweenanetworkedapplicationandourcomputer.

2. Portability:-

Java programs are portable from one computer to another computerrunningdifferenttypesofoperatingsystemsandhavingdifferenthardware.

JavaBytecode-

Theoutputofa Javacompiler isbytecodenot themachinecode (“.class” file).BytecodeisahighlyoptimizedsetofinstructionsdesignedtobeexecutedbytheJavarun-timesystem,whichiscalledasJVM(JavaVirtualMachine).

JVM is the interpreter which interprets the bytecode. Compiled program runsfaster but still Javauses interpreter to achieveportability so Javaprograms runs a littleslower.NowaprogramcompiledthroughaJavacompilercanruninanyenvironmentbutJVMneedstobeimplementedforeachplatform.Javaprogramsareinterpreted.ThisalsohelpstomakeitsecurebecausetheexecutionofeveryJavaprogramisunderthecontrolofJVM.

JIT(JustInTime):-

JITisatranslatorusedbyJVMtotranslatebytecodeintoactualmachinecode.Itdoesnottranslateentirebytecodesratherittranslatespiecebypieceondemandbasis.

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-AstandaloneapplicationisaprogramthatrunsonourlocalcomputerundertheoperatingsystemofthatcomputerjustlikeaCoraC++program.

2. Applets- An applet is a small program which travel across the Internet andexecuted by a Java-Compatible web browser, such as Internet Explorer orNetscapeNavigator,ontheclientmachine.

Anapplet is actuallya tiny Javaprogram,dynamicallydownloadedacross thenetwork.Appletprogramsarestoredonawebserverandtheytravelstoclientmachineonrequestfromtheclientmachine.

Anappletcannotbeexecutedlikestandaloneapplication.AppletcanbeexecutedonlybyembeddingitintoanHTMLpagelikeasoundfileoraimagefileoravideoclip.

Now thisHTMLpagewhich has applet embedded into it can be runafterdownloadingsuchHTMLpagebyawebbrowseronalocalmachine.Anapplet isaprogramthatcanreact touser inputandcanchangedynamically.Itdoesnotrunthesameanimationorsoundoverandover.

3. WebApplications-ThesearetheprogramswhichrunonWebServer.WhenweaccessawebsitebyspecifyingtheURL(UniversalResourceLocator)inawebbrowserthenthewebbrowsersendsarequesttothewebserverforaparticularWebsite.AfterreceivingthisrequestserverrunsaprogramandthisprogramiscalledasWebApplication.WeuseJavaServletsandJSP(JavaServerPages)towritesuchprograms.

Theseprogramsrunontheserverandthensendtheresult/responsetothe client. JSP pages can be thought of as a combination of HTML and JavaCode.TheWebServerconvertsJSPpagesintoJavaServletsbeforeexecution.

WhenaclientrequestforaparticularURLandtheURLcorrespondstoan HTML page the web server simply returns the HTML page to the client,which thendisplays it. If theURLcorresponds to the servlet or JSP then it isexecutedontheServerandtheresult/responseisreturnedtotheclient,whichisthendisplayedbytheclient.

4. DistributedApplications-Javaapplicationisdividedintosmallprogramswhichcan run on separate machines. The objects used in these programs cancommunicate with each other. These applications are known as DistributedApplications. This allowed objects on two different computers to executeprocedureremotely.ForthisRMI(RemoteMethodInvocation)isused.

CharacteristicsofJava:-

1. Simple- The syntax of Java is almost similar to C and C++ so that aprogrammer is familiarwithC/C++ does not have to learn the syntax fromscratch.Butmany features ofC/C++,which are either complex or result inambiguityhavebeenremovedinJava.

1. Java does not support multiple inheritance, as the concept is a bitcomplexandmayresultinambiguity.

2. Javadoesnotsupportglobalvariables,whichalsoleadtomanybugsinC/C++programs.

3. Javadoesnotusepointersanddoesnotallowpointerarithmetic,whichis cause of most of the bugs in C/C++ programs due to inherentcomplexity.

4. Javadoesnotsupportoperatoroverloadingasitmayleadtoconfusion.5. There is no concept of garbage value in Java. We have to initialize

variablesbeforeuse.

2. Secure-Javaprogramsrunwithin theJVM(JavaVirtualMachine)andtheyare inaccessible to other parts. This greatly improves the security. A Javaprogramrarelyhangsdue to this feature. It isquiteunlikeC/C++programs,whichhangfrequently.Java’ssecuritymodelhasthreeprimarycomponents:

1. Classloader.2. BytecodeVerifier.3. SecurityManager.

Java uses different class loaders to load class files (executable files)fromlocalmachineandremotemachines.Theclassesloadedfromremotemachines likeApplet classes arenot allowed to readorwrite fileson thelocalmachine.Thispreventsamaliciousprogramfromdamagingthelocalfile system.Bytecodeverifierverifies thebytecode as soonas class loadercompletes itswork. It ensures that bytecode is valid Java code. It almosteliminates the possibility of Java program doing somemalicious activitylikeaccessingthememoryoutsidetheJVM.TheSecurityManagercontrolsmany critical operations like file deletion, creation of threads etc. Theseoperations are allowed only if the Java programs have sufficientpermissionsotherwiseSecurityManagerdoesnotallowtheoperationsandgeneratesSecurityException.

3. Portable-Javaprogramsareplatformindependent.Theyfollowthepolicyofwrite-once-run-anywhere.AJavaprogramwrittenforWindowsPlatformcanrunonanyotherplatform(Unix,Linux,SunSolarisetc.)simplybycopyingthe bytecode (“.class” files). There is no need to copy the source code andcompile it again as in case of aC/C++program.This feature hasmade theJavaapowerfullanguage.WecanrunbytecodeonanymachineprovidedthatthemachinehastheJVM.JVMisitselfisplatformdependentbutitmakestheJava code platform independent. It is actually JVM which converts thebytecodeintomachinecodeandexecutesthem.

SowecansaythatJavaisaportablelanguage.OnemorefeaturewhichmakesJavahighlyportable is thatprimitivedata typesareof fixed lengthirrespectiveof theplatform.For examplean intwill alwaysbe4bytes inJava. This is unlike C/C++ where size of int can be 2 bytes on somemachinesand4bytesonothermachines.

4. ObjectOriented-Javaisalmostpureobject-orientedlanguagebutitsupportsprimitivedatatypeslikebyte,short,int,long,float,double,char,booleanfortheperformancereasons.

5. Robust:-Mostprogramsfailoneofthetworeasons:1. MemoryManagement.2. Exceptionalconditionsatruntime.

Whiledesigning the languageoneof theaimwas to ensure that Javaprograms are as robust as possible i.e. they should rarely fail. So dueimportancewasgiventotheabovetwofactorsintheJava.

InJavamemoryallocationandde-allocationishandledinthelanguageitself, which eliminates many problems caused due to dynamic memorymanagement features in C/C++. Java also supports object orientedexceptionalhandlingfeaturestohandleexceptionalconditions,whichoccuratrun-time.ThisallowsaJavaprogramtorecoverandcontinueexecutionevenafteranexceptionalconditionoccurs.

6. Multithreaded:- Java was designed to meet the real world requirement ofcreating interactive, networked programs. Java provides support for writingmulti-threadedprogramstoachievethis.Thisallowstheprogrammertowriteprogramsthatcandomanythingsconcurrently.

ForexampleaGUI(GraphicalUserInterface)basedapplicationmightbe listening tousereventsand takingappropriateaction,aseparate threadmightbedoingprintingandaseparatethreadmightbedownloadingafilefromsomemachineacrossthenetwork,allofthisbeingdoneconcurrently.ThisresultsinbetterperformanceandbetterCPUutilization.

Itispossibletowritemulti-threadedprogramsinotherlanguagesalsobutitisachievedonlybymakinguseofSystemcallswhileincaseofJavaitcanbeachievedbyusingfeaturesofthelanguageitself.

7. Architecture-neutral-Oneofthemainproblemsfacingprogrammersisthat

no guarantee exists that ifwewrite a program today, itwill run tomorrow-evenon the samemachine.Operating systemupgrades, processorupgrades,and changes in core system resources can all combine to make a programmalfunction.ButthegoalofJavaprogramsis“writeoncerunanywhere”.

8. InterpretedandHighPerformance-Javaprogramsare interpretedbutstilltheyrunfastascomparedtootherinterpreters.

9. Distributed-JavaisdesignedfordistributedenvironmentoftheInternet.Javahas built-in support for variousTCP/IP based protocols for this purpose. InfactaccessingaresourceusingaURLissimilartoaccessingafileonthelocalmachine. Java also has features for Remote Method Invocation, which issomewhat similar toRemoteProcedureCalls (RPC).This allowsobjectsondifferentcomputerstoexecuteproceduresremotely.Javahasbuilt-inAPI’sforthispurposecalledasRMI.

10. Dynamic-EveryJavaclassisaseparateunitofexecution.Aclassisloadedattheruntimeonlywhenitisneeded.DefaultmechanismforbindingmethodsinJavaisalsodynamic(run-timebinding).

RunningaStandaloneJavaApplication:-

WhenaCorC++programiscompiled,itisdirectlytranslatedintomachinecodeofaparticularprocessororaparticularplatform.ButrunningaJavaprogramisatwo-stepprocess.InJavatranslationfromsourcecodetotheexecutablecodeisachievedusingtwotranslators:

1. Java Compiler - First of all Java program is compiled into bytecode.Bytecode are just likemachine code but not for a particular processor orplatform.Bytecodescannotbedirectlyexecuted.

2. Java Interpreter (JVM) - Java interpreter by using JIT translates thebytecodeintoactualmachinecodeofaparticularplatform.

Note 1- C or C++ programs are compiled only once but Java bytecodes are translatedeverytimeweexecuteJavaprograms.SoJavaprogramsrunalittleslowerascomparedtoC/C++programs.

Note 2-To run a Java program we need a Text Editor (Notepad or Edit), JDK (JavaDevelopmentKit), and JVM (already installed inmanyoperating system).We can alsouseEcllipseorJCreaterinplaceofNotepad.

InstallingJava1.7onwinxp-

DoubleClickonMyComputer � DoubleClickonCDDrive � DoubleClickonJDK1.7JavaInstallationFile � PressNext,Next,…..

TosetthePath-

If we set the path of Java folder then we can run Java programs from anywhereotherwisewehavetorunourjavaprogramsfromthebinfolderofJava.

RightClickonMyComputer � Properties � Advanced � EnvironmentVariables � ClickonPathandthenclickonEdit � Clickonthevariablevalue � Movethecursorattheendof this line by pressing END � Now type “c:\program files\Java\jdk1.7.0_01\bin; andthenclickonOK,OK,OK.

CreatingafolderforJavaprograms:-

Double Click on My Computer � Double Click on C: Drive � RightClick � 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-WecanalsorunJavaprogramsthroughNotepadusingabovestepsbutinsteadofusingEdit commandwewilluseNotepad.After typing the JavaProgramsave it to thefolder“C:\JAVAPRG”afterchoosing“Allfiles”insaveasdialogbox.Tocompileandrunwehavetofollowabovesteps.

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()methodcanbedefinedonlyinsideaclass.

Asourcefilemayhaveanynumberofclassandorinterfacedefinitionsbuttherecanbeatthemostonepublicclassorinterface.

Asourcefilemayormaynotcontainaclasshavingmain()methodbutastandaloneJavaprogramalwaysstarts itsexecutionfrom main()method.Sothe 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 fromanywhere. Themain( )methodmust be declared public as it is called by thecode,which ispartof theJVMand isoutside theclasscontaining themain( )method.

Thekeywordstaticindicatesthatmain()isaclasslevelmethodandcanbecalledwithoutcreatinganyobjectitismustasnoobjectexistsbeforemain()iscalledandanyobjectcreationoccursonlyinsidethemain()method.

Thevoidkeywordprecedingmain()methodindicatesthatitdoesnotreturn

anyvalue.

Themain()methodtakesoneargument,whichisthearrayofStrings.Eachelementofthearrayrepresentsonecommandlineargument.

Systemisapredefinedclassthatprovidesaccesstothesystem,andoutistheoutput stream that is connected to the console. print( )method canbe used todisplayanytypeofinformation.

StructureofaJavaProgram–

All Java source filesmust endwith the extension “.Java”. Java is a case sensitivelanguage.NotethatintheaboveprogramfirstletterofclassesSum,StringandSystemiswritteninuppercase.ItisbettertosavetheJavaprogramwiththefilenamewhichissameas of class name, but it is not compulsory. But if class is declared as public then it iscompulsorytosavetheclassinafilewhosenameissameasofclassname.Aclasscancontain only one public class but may contain as many non-public classes. If a filecontainsmore thanoneclass thenaftercompilationseach individualclass isput into itsownoutputfilenamedaftertheclassandusing.classextension.

Documentation Section -The documentation section contains a set ofcomment lines giving the name of the program, the author and other details,whichtheprogrammerwouldliketorefertoatalaterstage.Commentsexplainwhyandwhatofclassesandhowofalgorithms.Inadditiontosingle,multilinecomment Java also uses a third style of comment /**…*/ known asdocumentationcomment.

Package Statement -A source file may have at the most one packagestatement.IfapackagestatementispresentitmustbethefirststatementintheJavaprogram.Onlycommentsmayappearbeforethepackagestatement.

ImportStatements-Asourcefilemayhavezeroormoreimportstatements.Import statements are just like #include statement inC/C++. If present all theimport statementsmustcomeafter thepackagestatementandbefore theclass/interfacedefinition.

InterfaceStatements-AnInterfaceislikeaclassbutincludesagroupofmethoddeclarations.Thisisalsoanoptionalsectionandisusedonlywhenwewishtoimplementthemultipleinheritancefeaturesintheprogram.

Classdefinitionnotcontainingmainmethod-AJavaprogrammaycontainmultiple class definitions. Classes are the primary and essential elements of aJavaProgram.Theseclassesareusedtomaptheobjectsofreal-worldproblems.

Classdefinitioncontainingmainmethod-SinceeveryJavastand-alone

programrequiresamainmethodas its startingpoint, thisclass is theessentialpartofaJavaprogram.AsimpleJavaprogrammaycontainonlythispart.Themainmethodcreatesobjectsofvariousclassesandestablishescommunicationsbetween them. On reaching the end of main, the program terminates and thecontrolpassesbacktotheoperatingsystem.

GarbageCollection-

MemoryallocationfortheJavaobjectsiscompletelydynamicbutJavadoesnothavesupport forpointerarithmetic likeC/C++.Wheneverwe runa Javaprogram, JVMalsoruns another program (thread) called Garbage Collector in the background. GarbageCollectorkeepscheckontheJavaobjects.

WheneveraJavaobjectisnotbeinguseditiscollectedbytheGarbageCollectori.e.thememoryallocatedfortheobjectisaddedtothepool/heapoffreememoryandcanbe reused. This simplifies the task of the programmer to a large extent. This alsoeliminates lots of bugs caused due to improper use of pointer arithmetic and memorymanagementfeatureslikefreeingmemoryexplicitly.

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?Namesomeofthesefeatures.

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 ofvariables,functionsetc.

B.Identifierreferstothenamesofvariable,arrays,functions,classes,Interfacesetc.

C.Constants/Literalsrefertofixedvaluesthatwecannotchangeinaprogram.

D.Operatorsare special symbolswhich operate on variable& constants, and form anexpression.

E.Separatorsarethespecialcharactersusedtoseparatestatementssuchas“(){}[];,.”

A.Keywords-

abstractcontinuegotopackagesynchronized

assertdefaultifprivatethis

boolean do implements protectedthrow

breakdoubleimportpublicthrows

byteelseinstanceofreturntransient

caseextendsintshorttry

catchfinalinterfacestaticvoid

charfinallylongstrictfpvolatile

classfloatnativesuperwhile

constfornewswitchenum

Note1-Thereare50reservedkeywordsinJava.Thekeywordconstandgotoarereservedbutnotused.TheassertkeywordwasaddedbyJava2version1.4.TheenumkeywordwasaddedbyJava2version1.5.

Note2- In addition to keywords, Java reserves the following literals true, false, andnull.We can’t use these reserved names as Identifiers (Variable or Class or Interfacenames).

B.Identifiers:-

Anidentifierisawordusedinaprogramtonameavariable,method(function),class,interface,packageetc.Javaidentifiersarecasesensitive.

Identifiernamingrules(wemustfollow):-

1. AJavaidentifiermustbeginwithaletter,dollarsignorunderscore.Itcan’tbeginwithanumber.

2. Thesubsequentcharactersmaybedigitsalso.3. Thereisnorestrictiononthelengthofidentifiers.4. Java allowsUnicode characters in identifiers.We can use� , � , � , � etc. in

identifiersastheyaretreatedaslettersinUnicode(ASCIIisreplacedbyUnicodeinJava).

Identifiernamingrules(weshouldfollow)-

1. Namesofalltheclassesandinterfacesstartwithaleadinguppercaseletterandeachsubsequentwordalsostartswithaleadinguppercaseletter.Restofthelettersmustbeinlowercase.(ExampleStudentTest).

2. Names of all the public datamembers andmethods start with a leading lowercasecharacter.Whenmorethanonewordareusedinaname,thesecondandsubsequentwordsstartwithaleadinguppercaseletter.(ExamplenetAnnualProfit).

3. Names of variables that represent constant values use all uppercase letters andunderscoresbetweenwords.(ExamplePI).

C.Constants/Literals:-

A Literal represents a constant value which we can’t change. A literal can’tappear on the left side of an assignment operator. A literal is a value specified in thesourcecodeitisnotdeterminedatruntime.

TypeofLiterals-

1. 5,-5,0x5A,012,5l,5LareIntegerLiteralsinwhich5,-5aredecimal,0x5Aisahexadecimal,012isaoctal,lorLisforlong.

2. 5.23,-5.23,5.4f,5.4F,5.4d,5.4D,1.2E-03areFloatingPointLiteralswherefor F is for single precision(float), d or D is for double precision, 5.23 is aStandardnotationand1.2E-03isinexponentnotation(Scientificnotation)where1.2ismantissaand-03isexponent.

3. ‘a’,‘A’,‘\n’,‘\141’,‘\u0061’areCharacterLiterals inwhich‘\n’ isanescapesequence,‘\141’isoctalcodeforcharacter‘a’and‘\u0061’ishexa-decimalcodeforcharacter‘a’.

4. “matrix”isaStringLiteral.Stringisagroupofcharacters.InJavaStringsthereis no line-continuation escape sequence as there inother languages.SoStringsmustbeginandendonthesameline.InJavastringsareofobjecttype.“\”Thisisinquotes\””.

5. True,falseareBooleanLiterals.Trueandfalsearenotequalto1or0inJava.Wecan’tconvertaBooleanvaluetointegerandvice-versa.

D.Operators-

Javaprovidesarichsetofoperators.Operatorscombineconstants,variablesandsub-expressionstoformexpressions.MostoftheoperatorsinJavabehavelikeC/C++buttherearefewdifferences,whicharecoveredhere.

Operatorscanbeclassifiedas:

ArithmeticOperators(+,-,*,/,%)

TheseoperatorsaresameasinC/C++.

%operatorcanworkonfloatingnumbersalso.

Whenbinaryoperator is appliedon twooperandsofdifferent types thenoperandoflowertypegetsconvertedtothehighertypebeforetheevaluationandthetypeoftheresultwillbesameasthatofoperandofhighertype.

DivisionormodulusbyzeroresultinArithmeticException(runtimeError)incaseofintbutnotincaseoffloatingnumbers.

Whenweapplyarithmeticoperatorsonintandtheresultisoutsidetherangeof int then extra high order bits will be truncated and this new valuewill be

assigned to the variable receiving their result but in floating type in case ofoverflow itwill result in Infinity or –Infinity and in case of underflow itwillresultin0.

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<.<=,>,>=cannotbeappliedonbooleantypesandreferencetypes.

instanceofoperator:-

The instanceof operator is used to test the class of an object. Theinstanceofoperatorhasthegeneralform:

if(objectinstanceoftype)

Here, object is an instance of a class, and type is a class type. If object is aninstanceofthespecifiedtypeorinstanceofanysub-classofthespecifiedtype,thentheinstanceofoperatorreturntrueotherwiseitsresultisfalse.

AssignmentOperators(=,+=,-=,*=,/=,%=)

TheseoperatorsaresameasinC/C++.

EqualityOperators(==,!=)

TheseoperatorsaresameasinC/C++.

LogicalOperators(&&,||,!)

TheseoperatorsaresameasinC/C++.

ConditionalOperator(?:)

ThisoperatorissameasinC/C++.

BitwiseOperators(&,|,^,~,<<,>>,>>>)

TheseoperatorsaresameasinC/C++exceptshiftoperators.Shiftoperatorsworksonlyonintegertype.

LeftShift(<<)Operator

Toobtaintheresultof<<operator,thebitsinthelefthandsideoperandareshiftedtotheleftasspecifiedbytherighthandoperandandtheemptybitpositionstotherightarefilledwithzero.Leftshiftingby1isequivalenttomultiplicationby2.Itispossiblethatsignoftheresultmaydifferfromthesignofthelefthandsideoperand.Thismayhappenbecause the sign depends on the left-most bit,which can change from0 to 1 or 1 to 0hencethechangeinsign.

Exampleb=a<<2;Toobtainthevalueofb,shiftthebitsinaby2positionstotheleftandfillthe2rightbitswithzero.

RightShift(>>)Operator(signed)

Toobtaintheresultof>>operator,thebitsinthelefthandoperandareshiftedtotherightasspecifiedbytherighthandoperandandtheemptybitpositionstotheleftarefilledwithsignbit.Rightshiftingby1isequivalenttodivisionby2.Thisoperatorneverchangesthesignoftheresulti.e.itwillbesameasthesignofthelefthandoperand.

Exampleb=a>>2;Toobtainthevalueofb,shiftthebitsinaby2positionstotherightandfillthe2rightbitswithsign(0ifaispositiveor1ifaisnegative.).

RightShiftwithzerofill(>>>)Operator(unsigned)

Rank Operators Description Associativity

1 ()

[]

.

Functioncall

SubscriptDirectmember

LefttoRight

2 ++

Increment

Decrement

RighttoLeft

Toobtain the result of>>>operator, the bits in the left hand side operand areshiftedtotherightasspecifiedbytherighthandoperandandtheemptybitpositionstotheleftarefilledwith0.Rightshiftingby1isequivalenttodivisionby2.Ifshiftingtakesplacethenresultwillalwaysbepositive,astherightmostbitwouldbecomezero.

Exampleb=a>>>2;Toobtainthevalueofb,shiftthebitsinaby2positionstotherightandfillthe2rightbitswith0.

PrecedenceofOperators:-

E.Separators:-

~

!

Bitwise unaryNOT

Logical unaryNOT

3 *

/

%

Multiplication

Division

Modulus

LefttoRight

4 +

-

Addition

Subtraction

LefttoRight

5 >>

>>>

<<

Bitwise RightShift

Bitwise LeftShift

Bitwise RightShiftZeroFill

LefttoRight

6 >

>=

<

<=

instanceof

Greaterthan

Greater thanorequalto

Lessthan

Less than orequalto

LefttoRight

7 ==

!=

EqualTo

NotEqualTo

LefttoRight

8 & BitwiseAND LefttoRight

9 ^ BitwiseXOR LefttoRight

10 | BitwiseOR LefttoRight

11 && LogicalAND,circuitAND

LefttoRight

12 || Logical OR,Short circuitOR

LefttoRight

13 ?: Conditionaloperator(Ternary)

LefttoRight

14 =

+=

-=

*=

/=

%=

&=

|=

^=

>>=

<<=

>>>=

Assignment

Additionassignment

Subtractionassignment

Multiplicationassignment

Divisionassignment

Modulusassignment

Bitwise Andassignment

Bitwise Orassignment

Bitwise XORassignment

Bitwise RightShiftassignment

Bitwise LeftShiftassignment

Bitwise RightShiftZeroFillassignment

RightToLeft

Symbol Name Purpose

() Parenthesis Used to contain list ofparameters in methoddefinition and invocation(calling). Also used fordefining precedence inexpressions, containingexpressions in controlstatements, and intypecasting.

{} CurlyBraces Used to initialize arrays,Alsousedtodefineablockof statements, for classes,interfaces, methods andlocalscope.

[] SquareBrackets

Todeclareanarray.

; Semicolon Toterminateastatement.

, Comma Separates consecutiveidentifiers in a variabledeclaration, Also used tochain statements togetherinsideadorstatement.

. Period Used to separate packagenames from sub-packagesand classes. Also used toseparate a variable ormethod from a referencevariable.

DataTypes-DatatypesinJavacanbebroadlyclassifiedintwocategories:

1.PrimitiveDataTypes/SimpleDataTypes-

Javaisanobjectorientedlanguage,buttheprimitivedatatypesarenotobjects.TheyarekeptinJavaforperformancereason.TheyformthebasisforallothertypesofdatathatwedefineinourJavaprograms.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-bitASCIIcharactersetandthefirst256charactersoftheUnicodecorrespondtothe256charactersoftheExtendedASCII(8-bitISOLatin-1)characterset.

Java characters can also be used in integer expressions. TheUnicode value of thecharacterisusedwhenitispartofanintegerexpression.

1. Non-PrimitiveDataTypes/DerivedDataTypesorReference

DataTypes-Referencedatatypesarealsocalledderiveddatatypesastheyarederivedfromtheprimitivedatatypes.

Classes

1. Built-In/LibraryClasses2. User-DefinedClasses

Interfaces

3. Built-In/LibraryClasses4. User-DefinedClasses

Arrays-ArraysarealsotreatedasobjectsinJava.

Java’sAutomaticConversionswilltakeplacewhen-

1.Thetwotypesarecompatible.

2.Thedestinationtypeislargerthanthesourcetype.

Variables-

Variablesarethenameofthememorylocationsthatcanstorevalues.Avariablemust be declared before we can store value in it. Or Variable is the place (MemoryLocation)insidethemainmemorywherewecanstoreourdataorvalues.

Therearethreekindsofvariables:

LocalVariables:-Localvariablesareusedinsideblocksormethods.Localvariables (also known as automatic variables) are not initialized by default.Alocalvariablemustbeexplicitly initializedbeforebeingused for the first timeotherwise a compile timeerror “Variablemightnothavebeen initialized”willcome.

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 thecompilerwillgiveanerror“Variableamightnothavebeeninitialized”.

In Javawecannotdefineavariable in the innerblockwith the samenameasofouterblock.

inta=5;

{

inta=7;//Error

}

InstanceVariables:-Instancevariableareusedtodefineattributesorstateofanobject.

ClassVariables:-Classvariablesareusedtodefineattributes/state,whichiscommonforalltheobjectsofaclass.

LibraryMethodsofclassMath-

publicstaticdoublesin(doublex);

Returnthesineof theanglexinradians

publicstaticdoublecos(doublex);

Returnthecosineoftheanglexinradians

publicstaticdoubletan(doublex);

Return the tan of the angle xinradians

publicstaticdoubleasin(doublex);

Returntheanglexofsine

publicstaticdoubleacos(doublex);

Returntheanglexofcosine

publicstaticdoubleatan(doublex);

Returntheanglexoftan

publicstaticdoubletoRadians(doublex);

Convertdegreesxtoradians

publicstaticdoubletoDegrees(doublex);

Convertradiansxtodegrees

publicstaticdoubleexp(doublex);

Returneraisedtox(ex)

publicstaticdoublelog(doublex);

Returnthenaturallgorithmofx

publicstaticdoublelog10(doublex);

Returnthenaturallgorithmofxbase10

publicstaticdoublesqrt(doublex);

Returnthesqrtofx

publicstaticdoubleceil(doublex);

Return the smallest wholenumber greater thanorequaltox(roundingup)

publicstaticdoublefloor(doublex);

Return the largest wholenumberlessthanorequaltox(roundeddown)

publicstaticdoublerint(doublex);

Returntheroundedvalueofx

publicstaticdoubleatan2(doublex,doubley);

Returntheanglewhosetangentisx/y

publicstaticdoublepow(doublex,doubley);

Returnxraisedtoy(xy)

publicstaticintround(floatx);

Returntheroundedvalueofxinint

publicstaticlonground(doublex);

Returntheroundedvalueofxinlong

publicstaticdoublerandom();

Returnsarandomnumberbetween0to0.999999999999999999

publicstaticintabs(intx); Returntheabsolutevalueofx.

publicstaticlongabs(longx);

Returntheabsolutevalueofx.

publicstaticfloatabs(floatx);

Returntheabsolutevalueofx.

publicstaticdoubleabs(doublex);

Returntheabsolutevalueofx.

publicstaticintmax(intx,inty);

Returnthemaximumofx&y

publicstaticlongmax(longx,longy);

Returnthemaximumofx&y

publicstaticfloatmax(floatx,floaty);

Returnthemaximumofx&y

publicstaticdoublemax(doublex,doubley);

Returnthemaximumofx&y

publicstaticintmin(intx,inty);

Returntheminimumofx&y

publicstaticlongmin(longx,longy);

Returntheminimumofx&y

publicstaticfloatmin(floatx,floaty);

Returntheminimumofx&y

publicstaticdoublemin(doublex,doubley);

Returntheminimumofx&y

publicstaticdoublesinh(doublex);

Returnsthesinhyperbolicofanglex

publicstaticdoublecosh(doubley);

Returnsthecoshyperbolicofanglex

publicstaticdoubletanh(doublex);

Returnsthetanhyperbolicofanglex

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.Whatisthebinaryvalueofzafterthesestatements: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;Theexpressiongrade==70isevaluated:

(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.Writeaprogramwhichwillsolvesomeequationsofdifferentdatatypesanddisplaytheresult.

4.Writeaprogramtoproofthatnameofainnerscopevariablecannotbesameasouterscopevariable.

5.Writeaprogramtocalculateareaofacircle.(usefinaltodeclareaconstant).

6.WriteaprogramtoconvertthechartoUnicode.

7.Writeaprogramtotypeconversioninttofloat.

8.Writeaprogramtocalculatemodulus(%)oftwofloatnumbers.

9.Writeaprogramtofindtherootsofaquadraticequation.

CHAPTER∞3∞

(ControlStatement)

Introduction-Controlstatementsareusedtochangetheflowofexecution.Java’scontrolstatements

canbeclassifiedintothreecategories.

1. SelectionStatements(DecisionControlStructure)Selectionstatementallowstheprogramtochooseanyonepathfromdifferentsetofpathsofexecutionbasedupontheoutcomeofanexpressionorthestateofavariable.

1. if2. ifelse3. nestedifelse4. if-else-if5. 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)Loopingisaprocessbywhichwecanrepeatasinglestatementoragroupofstatementsnnumberoftimes.

1. for2. while3. 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 beexecuted 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:

112

123

1234

12345

3. JumpStatements-Itallowsourprogramtoworkinanon-linearfashion.1. break.2. labeledbreak.3. continue.4. labeledcontinue.5. return.

MostofthestatementshavesamesyntaxasthecorrespondingstatementsinC/C++.Howevertherearesomesignificantdifferences.

Theconditionalexpressionsusedintheif,for,whileanddostatementsmustbevalidbooleanexpressionsi.e. theirvaluesshouldbeeithertrueorfalse.We

cannotuse0insteadoffalseoranon-zerovalueinsteadoftruethatisvalidinC/C++.

Javadoesnothaveanygotostatementalthoughgotoisareservedwordinthelanguage.Javaprovideslabeledbreakandlabeledcontinuestatementswhichareoftenreferredtoasthecivilizedformofgotoastheyaresupposedtobebettersubstitutesofgotostatement.

InJava,switchexpressioncanbeanyintegerexpressionexceptlongi.e.thetypeoftheswitchexpressioncanbebyte,short,charorint.ButtheJava’sintisof4byteswhichissameassizeoflonginC/C++.

ThecaselabelsareconstantexpressionsasinC/C++butthevaluesofthecaselabelsmustbeintherangeofthetypeoftheswitchexpressionotherwisetheprogramwillnotcompile.

Thelabeledbreakstatement isused to terminate theblockwhose label isspecified in the break statement. Unlike simple break statement, we canterminateanyblock.Forexample,itispossibletoterminatetheoutermostloopfrom inside adeeplynested for loop.Thebreak statement canalsobeused toterminateasimpleblock(i.e.theblockneednotbealooporswitchstatement)

Thelabeledcontinuestatementspecifiesthelabeloftheenclosinglooptocontinue.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.ifitiseventhentheloopwillcontinuewithoutprintinganewline.

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,multiplicationanddivisionoftwonumbers.

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-7versiontotakeinputofprimitivedata typefromtheuser. It isveryeasy to take inputusing thisclassaswehave toonlycreateanobjectofthisclassandhavetocallaparticularmethod.Thisclassisavailableinjava.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.Thememoryallocationisalwaysdynamic.Everyarray inJava is treatedasanobjectwithonespecialattributelength,whichspecifiesthenumberofelementsinthearray.

1.One-Dimensionalarray:-

Declaration-

typearray_name[];//Nomemoryallocationtakesplaceindeclaration.

Or

type[]array_name;

Itisimportanttonotethatthedeclarationdoesnotactuallycreateanarray.Itonlydeclaresareferencethatcandenoteanarrayobject.

inta1[],a2;

int[]a3,a4;

These two declarations declare a1, a3 and a4 to be reference variables that can denotearrayof int,but thevariablea2cannotdenoteanarrayof intvalue. It is simplyan intvariable.Whenthe[]notationfollowsthetype,allvariableinthedeclarationarearray.Otherwisethe[]notationmustfollowseachindividualarraynameinthedeclaration.

Memoryallocationwiththehelpofnewoperator:-

array_name=newtype[SIZE];//SIZEcanbeaconstantoravariable.

Note1-Alltheelementsofarraywillbeautomaticallyinitializedtozerobuttoinitializethe array with different values we can initialize the array in declaration itself. Arraydeclaration,memoryallocationandinitializationstepscanbecombinedintoone:-

inta[]={5,7,1};

Note2-Arrayindexstartsfromzero.

Note3:-In Java, all arrays store the allocated size in a variable named length.We canaccessthelengthofthearrayusingtheattributelength:

“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 arraywill bestored first in b & then a. So both a & b are pointing to a single array. Assigning areferencedoesnotcreateacopyoftheobject.

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.Therewillbesituationwhereatableofvaluewillhavetobestored.Considerthefollowingdatatable,whichshowthevalueofsalesofthreeitemsbysalesperson.

Thetablecontainstotal12value,threeineachline.Wecanthinkofthistableasamatrixconsistingoffourrowandthreecolumns.Eachrowrepresentsthevalueofsalesbyaparticularsalespersonandeachcolumnsrepresentthevalueofsalesofaparticularitem.

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-darrayasfollows

intarr[][]=newint[4][];

arr[0]=newint[1];

arr[1]=newint[2];

arr[2]=newint[3];

arr[3]=newint[4];

Thismeanstotal4rowsofarrayanditscolumnsstartsfrom1andincreaseonebyone.sotheyarerepresentedinthememoryasthefollows:

(Memoryallocation)

Note1-Alltheelementsofarraywillbeautomaticallyinitializedtozerobuttoinitializethe array with different values we can initialize the array in declaration itself. Arraydeclaration,memoryallocationandinitializationstepscanbecombinedintoone:-

inta[][]={{5,7,1},{1,7,9},{4,5,7},{1,1,1}};

Note2-Intheabovearraya.lengthwillshowthenumberofrowsi.e.4anda[0].lengthwillshownumberofcolumnsin0throwi.e.3

CommandLineArguments-

Sometimeswewillwanttopassinformationintoaprogramwhenwerunit.Thisis accomplished by passing command-line arguments to main(). A command lineargumentistheinformationthatdirectlyfollowstheprogram’snameonthecommandlinewhenitisexecuted.

To access the command-line arguments inside a Java programwe have to useStringarraypassedtomain().

TheJVMcallsthemain()methodandpassesthecommandlineargumenttoitasanarrayofstring.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.7Programtwoprintsumofnumbersinputthroughcommandlinearguments.

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.javawerecompiledasanapplicationandthenrunfromthecommandlineas:javaMyProgIliketestswhatwouldbethevalueofargs[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-dimensionalarrayofintegers?(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).Itactslikeatemplateusingwhichwecancreatemultipleobjects(instances).Aclassdeclarationonlycreatesatemplate, itdoesnotcreateanactualobject.Aclasscreatesanewdatatypethatcanbeusedtocreateobjects.Thatis,aclasscreatesalogicalframeworkthatdefinestherelationshipbetweenitsmembers.Whenwedeclare anobject of a class,we are creating an instanceof thatclass.Thusaclassisalogicalconstruct.Anobjecthasphysicalreality.(Thatis,anobjectoccupiesspaceinmemory.)

modifiersclass<classname>

{

modifierstypevariables;

.

.

.

modifierstypemethodName1(parameter-list)

{

<bodyofthemethod>

}

.

.

}

DeclaringObjects-

Students1;

Intheaboveexamples1isnotanobject.InC++s1willbetreatedasobjectbutinJavas1isonlyavariablewhichcanholdreferencetoanobjectoftypeStudent.Thisvariablewillholdgarbageornull referenceuntilweassign referenceof someobjectofclassStudent.

Itdoesnotyetpointtoanactualobject.Anyattempttousethisvariableatthispointwillresultinacompile-timeerror.ItisjustlikeapointertoanobjectinC/C++.Ifthisvariableisdeclaredinsideanyblockoramethodthenit isa localvariableandwillnotbeinitializedtonull,butifitisdeclaredinaclassthenitwillbeaninstancevariableandwillautomaticallybeinitializedtonull.

AllocatingMemory-

InJavamemoryisallocateddynamicallywiththehelpofnewoperator.

s1=newStudent();

In theaboveexamplenewoperatorwillallocatememoryforanobjectofclassStudentand return its reference,which is thenassigned to reference typevariable s1. Itwillalsocalladefaultconstructortoinitializemembervariables.

Theabovetwostatementscanbecombined:-

Students1=newStudent();

Note1-newallocatesmemoryforanobjectduring runtime. Ifnew isunable toallocatememory(becausememoryisfinite.)thenitgeneratearuntimeexception/error.

Note2-Ifweassignareferencevariabletoanotherreferencevariablethenonlyreference(address) will be transferred. There will not be any duplicate copy of the object. Forexample ifwecreateanotherreferencevariables2(Students2)andthen(s1=s2).Thiswillnotcreateduplicateobject,sameobjectisreferencedbys1ands2.

Any changesmade in s2will alsobe reflected in s1.Nomemory allocation isdonewiththisassign.Afterafewstepsifweassignnullins1thenthatobjectwillnotbedestroyedasitsreferenceiswithobjects2.Butifboths1ands2areassignedwithanullvaluethenthatobjectwillbedestroyedbythegarbagecollectorandthememoryoccupiedbythatobjectwillbefreed.

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 localvariables.

1. private-Ifwespecifythemodifierprivatewithamembervariableormethodthenthatmemberwillnotbevisibleoutsidetheclassinwhichitisdeclared.Thiswillhidethememberofaclassfromotherclasses.

2. public-Ifwespecifythemodifierpublicwithamembervariableormethodthen that member will be visible to all the classes. This member can beaccessedevenoutsidethepackage.main()methodisalwaysdefinedaspublicbecausethemain()methodisaccessedbytheJVMwhichisoutsidetheclassinwhichmain()methodisdefined.

3. protected- A member declared as protected can be accessed from all theclasses belonging to the same package. Protected members can also beaccessedfromanysubclassofotherpackages.

4. default/nomodifier- Ifnovisibilitymodifier isspecifiedbeforeamemberdeclarationthenthatmembercanbeaccessedfromalltheclassesinthesamepackage.Thatmembercannotbeaccessedoutsidethepackage.

VisibilityModifiersforaclassorinterface-

1. public-Ifaclassistobevisibletoalltheclassesirrespectiveoftheirpackage,then itmust be declared as public by specifying themodifier public,whichshouldappearbeforethekeywordclass.

2. default/nomodifier:-Intheabsenceofanyaccess/visibilitymodifierbeforetheclass,itsvisibilityisonlywithinthepackage(groupofclasses)inwhichitisdefined.

thisKeyword:-

thisisareferencevariablewhichstoresthereferenceoftheobjectcurrentlyusedtocallthemethod.Thereferenceofthisisreplacedbythereferenceofthecallingobjectatrun-time.Sometimesamethodwillneedtorefertotheobjectthatinvokedit.Thiscanbedonewith thehelpof this. thiscanbeused insideanymethod torefer to thecurrentobject.

Note:localvariablehidestheinstancevariable,sowehavetousethiskeywordexplicitly.

InstanceVariableHiding-

Aswe know, it is illegal in Java to declare two local variableswith the samenameinsidethesameorenclosingscopes.Butwecanhavelocalvariables(parametersofmembermethods)havingsamenameasofinstancemembervariablesofclass.

When a local variable has the same name as an instance variable, the localvariables hides the instance variable. But this keyword allows us to refer to instancevariableseveniflocalvariablehidesit.

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

Wecanhavemore thanonemethodwith thesamenameas longas theydiffereither in numbers of parameters or type of parameters or order of parameters. This iscalledmethodoverloading.

While calling an overloaded method it is possible that type of the actualparameters passed may not match exactly with the formal parameters of any of theoverloadedmethods.Inthatcaseparameterarepromotedtonexthighertypetillamatchis found. If nomatch is found even after promoting the parameters then a compilationerroroccurs.

Example 5.5 In this example there are two setdata() methods having same name buthavingdifferentarguments,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 initializethemselveswhentheyarecreatedusingconstructors.Ithasthesame

Thesyntaxoftheconstructorsisverysimilartothatofinstancemethods.Theyhavethesamenameastheclassanddonothaveanyreturntype.

This isbecause the implicit return typeofclass’sconstructor is theclass itself.Constructorscanbeoverloadedjustlikemethods.

Whenoperatornewisusedtocreateaninstance/objectofaclass,JVMallocatesmemoryfortheobject,theninitializestheinstancevariablestotheirdefaultinitialvalues,andthencallstheappropriateconstructortoinitializetheinstancevariables.

Note-

The name constructor is a bit confusing. It appears as if the purpose of theconstructoristocreateanobject/instance.Theobjectiscreatedandinstancevariablesandstaticvariablesareinitializedtotheirdefaultinitialvaluesbeforeconstructoriscalled.

Sothepurposeoftheconstructoristoinitializetheinstancevariableswithvaluesotherthanthedefaultvalues.

Typeofconstructors-

DefaultConstructor:-Everyclasshasadefaultconstructor(ifnoexplicitconstructorisdefined)thatdoesnottakeanyargumentanditsbodydoes not have any statements. The compiler generates the defaultconstructorautomatically.

The compiler stops generating default constructor as soon aswe addour own constructor.Whenwe do not create any constructor in the classthen JVM will create the default constructor and initialize the instancevariablewithdefaultvaluesnullorzero.

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:-Herewe have not created any constructor then JVMcreate automatically defaultconstructoraftercreatingobjectandinitializetheinstancevariablesfrom0ornull.

DefaultZeroargumentconstructors-Wecanreplacethedefaultconstructorwithourownzeroargumentconstructor.Thiswillallowus toinitializetheinstancevariablestoanyvalue.

ParameterizedConstructors:- A constructorwhich takesparametersiscalledasparameterizedconstructors.

Note-Itispossibletooverloadtheconstructorjustlikemethods.Itiscalledasconstructoroverloading.

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. Forexample, ifanobject isholdingsomenon-Java resourcesuchasa filehandler, thenwemightwanttomakesuretheseresourcesarefreedbeforeanobjectisdestroyed.

Tohandle such situations, Java provides amechanismcalled finalization.Byusingfinalizationwecandefinespecificactionsthatwilloccurwhenanobjectisjustabouttobe reclaimed by the garbage collector. finalize () is only called just prior to garbagecollection. It is not called when an object goes out of scope. In C++ the concept ofdestructorfunctionisusedforfinalizationbutitisnotexactlysameasfinalize()inJava.

protectedvoidfinalize()

{

//finalizationcodehere.

}

Note-Insteadofprotectedmodifierwecanalsousepublic.

TypeofVariables-

Javahasthreekindsofvariables:

1.Instancevariables-

Variabledeclaredinaclassasamemberoutsideallmembermethodsareknownasinstancevariable.Therewill be asmany copies of that variable as there are number ofobjects.

There is no need to initialize instance variable in Java because these variables areinitialized as soon as the object is created and the memory is allocated with the newoperator.

The variables are initialized according to their types.All the numeric variables areinitialized automatically with 0, Boolean variable with false, and reference variables(objects)withnullvalue.

Wecanaccessthesevariablesbyusingobjectnameandthedot(.)operator.(Objectreferencevariable.instancevariablename).Wecannotuse � operatortoseparateobjectreferencevariableandtheinstancevariableasinC/C++.

2.LocalVariables:-

VariablesdeclaredinsideamethodisknownasLocalvariable.Itisnotsameasinstancevariable.ThereisnoautomaticinitializationfortheLocalvariable.

3.StaticVariables:-

Staticvariablesarealsodeclaredoutsidemethods/blockslikeinstancevariables.But the static variables make use of the modifier static before the data type. Staticvariablesareglobaltoaclassandallofitsinstances(objects).

Theyareusefulforkeepingtrackofglobalstates.Forexample,astaticvariablecount in a class can store the number of instances/objects of the class created in theprogramatanyinstanceoftime.

The objects can communicate using static variables just like C functionscommunicate throughglobalvariables.Forstaticvariables there isonlyonecopyof thevariable irrespective of number of instances/objects created in the program, which issharedacrossalltheinstances.

Thedot(.)operatorisusedtoaccesstheclassvariablesalso,butwecanaccessthe static variable using class name as well as object name. If we declare to differentobjectsthebothwillpointtosamecopythestaticvariable.

Staticvariableisinitializedautomaticallywiththeirdefaultvalues(zero,falseornull)assoonastheclassisloaded/used.

Theycanonlycallotherstaticmethods.Theymustonlyaccessstaticdata.Theycannotrefertothisorsuperinanyway.(Thekeywordsuperrelatestoinheritanceandisdescribedlater.)

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.Instancemethodscanbeinvokedonlythroughobject.Ifwecallainstancemethodinsideastaticmethodofsameclassthenalsowehavetouseobjectname.

StaticMethods:-

Staticmethodscanbeinvokedusingobjectaswellasclassname.Staticmethodscanaccessonlystaticmembers.Staticmethodscanbecalleddirectly(withoutobjectorclassname)fromastaticmethodofsameclass.

Example5.101.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.//throughobjects32.}

33.}

Output:

11

5.5

11

Initialize&staticBlock-Initializeblockisusedtoinitializeinstancemembervariablesof theclass&staticblock isused to initialize staticmembervariablesof theclass.Butconstructoriscalledaftertheseblocks.

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-

Ifavariable isdeclaredasfinal thenwecannotchangeitsvaluefinal(doublePI=3.141;)finalvariabledonotoccupymemoryonaperinstancebasis.Afinalvariableisaconstantvariableitsvaluecannotbechange.Afinalvariablereferencetypecannotchangeitsreference.

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,itisdonebyuse of call-by-value approach. In case of objects what is actually passed is an objectreference.

An object reference is also passed by using call-by-value approach. However,sincethevaluebeingpassedreferstoanobject,thecopyofthatvaluewillstillrefertothesameobjectthatitscorrespondingargumentdoes.

For example ifwe pass a reference variable a1which stores a reference of anobjectintoafunctionandinfunctiona2istheformalparameterthena1anda2bothpointstothesameobject.

Anychangesinthevalueoftheobjectthrougha2willalsobereflectedina1.Butifweassignanewreferenceina2thenthatreferencewillnotbeautomaticallycopiedina1.

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;suchclassesareknownasnestedclasses.Thescopeofanestedclassisboundedbythescopeofitsenclosingclass.

Anestedclasshasaccesstothemembers,includingprivatemembersoftheclassinwhichit isnested.However theenclosingclassdoesnothaveaccess to themembersofthenestedclass.

Therearetwotypesofnestedclassesstaticandnonstatic.Astaticnestedclassisonewhichhasthestaticmodifierapplied.Becauseitisstatic,itmustaccessthemembersofitsenclosingclassthroughanobject.Thatis,itcannotrefertomembersofitsenclosingclassdirectly.Becauseofthisrestriction,staticnestedclassesareseldomused.

Anon-staticnestedclasshasaccess toallof thevariablesandmethodsof itsouterclassandmayrefertothemdirectlyinthesamewaythatothernon-staticmembersoftheouterclassdo.

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

ClassRandomExample5.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.Ifwewantamembervariabletonotbeaccessibleoutsidethecurrentclassatall,whatkeywordshouldprecedethenameofthevariablewhendeclaringit?

2.InJava,howareobjects/valuespassedaround.

3.Considerthecodebelow:

publicstaticvoidmain(Stringargs[]){

inta=5;System.out.println(cube(a));

}intcube(inttheNum){

returntheNum*theNum*theNum;}

Explaintheimportanceof“static”keywordWhatwillhappenwhenweattempttocompileandrunthiscode?

a)Itwillnotcompilebecausecubeisalreadydefinedinthejava.lang.Mathclass.

b)Itwillnotcompilebecausecubeisnotstatic.

c)Itwillcompile,butthrowanarithmeticexception.

d)Itwillrunperfectlyandprint“125”tostandardoutput.

4.Whatdoesastaticinnerclassmean?Howisitdifferentfromanyotherstaticmember

5.Howdowedeclareconstantvaluesinjava

6.Whatisthemeaningof“final”keyword?

7.Whatistheclassvariables?

Answer:Whenwe create a number of objects of the same class, then each objectwillshareacommoncopyofvariables.Thatmeansthat there isonlyonecopyperclass,nomatterhowmanyobjectsarecreatedfromit.Classvariablesorstaticvariablesaredeclaredwiththestatickeywordinaclass.

Thesevariablesarestoredinstaticmemory.Classvariablesaremostlyused for constants, variable that never change its initial value.Static variablesarealwayscalledbytheclassname.

Thisvariableiscreatedwhentheprogramstartsi.e.itiscreatedbeforetheinstanceiscreatedofclassbyusingnewoperatorandgetsdestroyedwhentheprogramsstops.Thescopeoftheclassvariableissameasinstancevariable.

The class variable can be defined anywhere at class level with thekeyword static. It initial value is same as instance variable. When the classvariableisdefinedasintthenit’sinitialvalueisbydefaultzero,whendeclaredbooleanitsdefaultvalue is falseandnull forobject references.Classvariablesareassociatedwiththeclass,ratherthanwithanyobject.

8.Explaingarbagecollection.

Answer: Garbage collection is one of the most important feature of Java.Garbage collection is also called automatic memory management as JVMautomatically removes the unused variables/objects (value is null) from thememory.Userprogramcann’tdirectlyfreetheobjectfrommemory,insteaditisthe job of the garbage collector to automatically free the objects that are nolongerreferencedbyaprogram.

Every class inherits finalize() method from java.lang.Object, thefinalize() method is called by garbage collector when it determines no morereferencestotheobjectexists.

InJava,itisgoodideatoexplicitlyassignnullintoavariablewhennomore in use. In Java on callingSystem.gc() andRuntime.gc(), JVM tries torecycle theunusedobjects, but there is noguaranteewhen all theobjectswillgarbagecollected.

9.Canwecalloneconstructorfromanotherifaclasshasmultipleconstructors?

Yes.Usethis()tocallaconstructorfromanotherconstructor.

10.What’sthedifferencebetweenconstructorsandnormalmethods?Constructorsmusthavethesamenameastheclassandcannotreturnavalue.Theyareonlycalledoncewhileregularmethodscouldbecalledmanytimesanditcanreturnavalueorcanbevoid.

11.Howwecanforcethegarbagecollection?Garbagecollectionautomaticprocessandcan’tbeforced.WecouldrequestitbycallingSystem.gc().JVMdoesnotguaranteethatGCwillbestartedimmediately.

12.Whichofthefollowingisnotacorrectstatement.

(a)LocalvariableinJavaarealwaysinitializedbydefaultvalues.

(b)LocalvariablesinJavamustbeinitializedbeforeuse.

(c)Localvariablesinaninnerblockcannothavethesamenameasalocalvariableinouterblock.

(d)Localvariablesintwoblocksasthesamelevelcanhavesamename.

CHAPTER∞6∞

(Inheritance)

Introduction-Whenthepropertiesoftheoneclassistransferredintoanotherclassthenit’ssaid

tobean inheritance. In thisway the inheritedclass iscalled tobeasuperclassorbaseclass or parent class and inheriting class is called to be a child class sub class derivedclass.

Inheritance allows us to extend an existing class (Base class) by adding theadditional features. It encourages the code reusability,which help in reducing the codesizealthoughitmayleadtocomplexityinsomecases.

Asanexampleifwehavecompletedthecodeofthesimplecalculator.Afteritweneedtodevelopthescientificcalculatorthenwehavetwoalternatives:

(i)Makeanewclass.(Rewritingtheclass)

(ii)Extendingtheclass.

Inthemostcasessecondalternativewillbeabetterchoice.Inthiscasewehavetowritethesmallpieceofcode.Atthesametimewewon’thavetospendmuchtimeindebuggingandtestingasthebaseclassisalreadytestedandisinuseforalongperiodoftime. 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 featuresdefined in the extended class. Java does not support the multiple-inheritance but itssupportmultipleinterfaceinheritancesosubclasscanextendsonlyonebaseclass.

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 ofmethods)asthatofasuper-classmemberthenithidesthesuper-classmember.

Althoughboththemembersmightbeavailableinthesub-classbutusingmembernamewecanonlyaccesssub-classmemberasithidesthememberofthesamenameinthesuper-class.

Usingkeywordsuper

Wheneverasubclassneedstorefertoitsimmediatesuperclass,itcandosobyuseofkeywordsuper.superhastwogeneraluses:

1. Callingsuperclass’sconstructor

Asubclasscancallaconstructormethoddefinedby itssuperclassbyuseof thefollowingformofsuper.super(parameter-list);

Here, parameter-list specifies any parameters needed by the constructor in thesuper class. In fact super()must always be the first statement executed inside asubclass’sconstructor.

2. Accessingamemberofthesuperclassthathasbeenhiddenbyamemberofasubclass.

The keyword super can be used to access the hidden members of the super asfollows:

super.member;

Here,membercanbeeitheramethodoradatamember.

MethodOverloadingandMethodOverriding:-

MethodOverloading:-

Whentwoormoremethodshavingsamenamebutdifferentparametersthenitissaidtobeamethodsoverloading.Methodoverloadingisusedwhenobjectarerequiredtoperformsimilartaskbutusingdifferentinputparameters.

Whenwe call amethod, javamatches up themethod name first and then thenumberandtypeofparameters.Todecidewhichoneofthemethoddefinitionistocalledisknownaspolymorphism.

MethodOverriding:-

Wehave seen that amethod in a super class is inheritedby its subclass and isusedby theobjectcreatedby thesubclass.Method inheritanceenablesus todefineanduse method repeatedly in subclass without having to define the method again insubclass.

Intheclasshierarchy,whenaninstancemethodinasubclasshasthesamenamesignature as an instancemethod (nonprivate) in its super class, then themethod in thesubclassissaidtooverridethemethodinthesuperclass.

Whenanoverriddenmethodiscalledfromwithinasubclass,itwillalwaysrefertotheversionofthatmethoddefinedbythesubclass.Theversionofthemethoddefinedbythesuperclasswillbehidden.

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 theclasses 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’sconstructor; thisorder is thesamewhetherornotsuper() isused. Ifsuper() isnotused,thenthedefaultorparameterlessconstructorofeachsuperclassbeexecuted.

Constructors are executed in order of derivation.Because a super class has noknowledgeofanysubclass,anyinitializationitneedstoperformisseparateandpossiblypre-requisite to any initialization performed by the sub class. Therefore it must beexecutedfirst.

Thekeywordsuperisusedsubjecttothefollowingconditions.

super()constructormayonlybecalledwithinasubclassconstructormethod.

Thecalltosuperclassconstructormustappearasthefirststatementwithinthesubclassconstructor.

The parameter in the super call must match the order and type of theargumentsofthesuperclassconstructor.

DynamicMethodBinding-

(DynamicMethodDispatchorRunTimeBinding):-

Methodoverridingformsthebasisforoneof java’spowerfulconceptDynamicmethod dispatch is the mechanism by which call to an overridden instance method isresolved at run time, rather than compile time. Dynamicmethod dispatch is importantbecausethisishowjavaimplementsruntimepolymorphism.

Asuperclassreferencevariablecanrefertoasubclassobjects.Javausesthisfactto resolvecalls tooverriddenmethodat run time.Whenanoverriddenmethod iscalledthroughasuperclassreference,javadetermineswhichversionofthatmethodtoexecutebaseduponthetypeoftheobjectbeingreferredtoatthetimethecalloccurs.

Thusthisdeterminationismadeatruntime,whendifferenttypesofobjectsarereferredtodifferentversionofanoverriddenmethodwillbecalled.Inotherwords,it isthetypeoftheobjectbeingreferredto(notthetypeofreference)thatdetermineswhichversionofanoverriddenmethodwillbeexecuted.

Overridden methods allow Java to support run-time polymorphism.Polymorphism is essential forOOP for one reason. It allows a general class to specifymethodsthatwillbecommontoallofitsderivatives,whileallowingsup-classestodefinethespecificimplementationofsomeorallofthesemethods.

Bycombininginheritancewithoverriddenmethods,asuperclasscandefinethegeneralformofmethodthatwillbeusedbyallofitssub-classes.Theabilityofexistingcode libraries to call methods on instances of new classes without recompiling whilemaintainingacleanabstractinterfaceisaprofoundlypowerfultool.

Baseclassreferencecantakethesubclassreferencebutsubclassreferencecannot takethebaseclassreference.

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:

Wehave seen that bymakingamethod finalweensure that themethod is notredefined in a subclass. Java allowsus todo something that is exactlyopposite to this.Thatiswecanindicatethatamethodmustalwaysberedefinedinasubclass,thusmakingoverridingcompulsory.Thisisdoneusingthemodifierkeywordabstract inthemethoddefinition.

Therearesituations inwhichwewillwant todefineasuperclass thatdeclaresthestructureofagivenabstractionwithoutprovidingacompleteimplementationofeverymethod.

That is, sometimes we will want to create a super class that only defines ageneralizedformthatwillbesharedbyallofitssubclasses,leavingittoeachsubclasstofillinthedetails.

Such a class determines the nature of the methods that the sub classes mustimplement.Oneway thissituationcanoccur iswhenasuperclass isunable tocreateameaningfulimplementationforamethod.

Todeclareanabstractmethod,usethisgeneralform:

abstractreturn_typename(parameter-list);

Nobody is present.Any class that contains one ormore abstractmethodsmust also bedeclaredabstract.Todeclareaclassabstract,wesimplyusetheabstractkeywordinfrontoftheclasskeywordatthebeginningofthedeclaration.

Therecanbenoobjectofanabstractclass.Thatis,anabstractclasscannotbedirectly instantiated with the new operator. Such objects would be useless, because anabstractclassisnotfullydefined.

Also we cannot declare abstract constructors or abstract static methods. Anysubclassof an abstract classmust either implement all of the abstractmethods in superclass,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’twantamethodtobeoverriddenbyaderivedclassmethodthenwecandefinethebaseclassmethodasfinal.Anyattempttooverridethatmethodwillcauseacompiletimeerror.

classA

{

finalvoidmethod1()

{

–—

}

}

classBextendsA

{

voidmethod1()//error

{

–—

}

}

Finalclass:-

Sometimeswemayliketopreventaclassbeingfurthersub-classedforsecurityreason.Aclassthatcannotbesubclassediscalledafinalclass.Thisisachievedinjavausingthekeywordfinalasfollows:

finalclassA1

{

------

------

}

classBextendsA//error

{

-------

-------

}

AnyattempttoinheritclassAwillcauseanerrorandthecompilerwillnotallowit.Declaringaclassfinalpreventsanyunwantedextensiontotheclass.

It also allows the compiler to perform someoptimizationwhen amethodof afinalclassisinvoked.

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.Therecanbetwodifferentapproachesdependinguponwhetherourmainfocusisonprocessingordata.Theproceduralprogramminglanguages(c,FORTRAN,PASCAL,COBOLetc.)focusontheprocessingparti.e.theygivemoreimportanceto“whatishappening”(process)inthesystemandlessimportanceto“whoisbeingaffected”(data).

The procedural approach becomes less and less suitable as the programsbecome large and complex. The object-oriented programming languages weredeveloped to overcome the limitations of the procedural programming languages. Theobject-orientedprogramminglanguagesarerelativelyfarlesscomplexascomparedtothesimilarprogramswithintheprocedurallanguages.

Theobject-orientedprogramsareorganizedaround thedata (i.e.objects)andasetofwelldefinedinterfaces(publicmethods)tothatdata.

Java is based on object oriented paradigm. Java is almost pure object orientedprogramming language.We have termed “almost” as Java also supports primitive datatypesduetoperformancereasons.

TheC++isnotapureobjectorientedlanguage.C++isanextensiontoCso ituses an approach, which is a mix of procedure-oriented approach and object-orientedapproach.

Thebasicdifferencesinthetwoapproachesaresummarizedbelow:

(i) Theobject-orientedprogramsaredata centricwhile theprogramswrittenintheprocedurallanguagesareprocesscentric.

(ii) The object-oriented programs are organized around data(objects)sotheymodeltherealworldobjectsinabetterway.

(iii) Thedegreeofreusabilityandextensibilityofthecodeisveryhigh in case of object-oriented approach as compared to proceduralapproach.Socodesizeisless.

(iv) Theobject-orientedprogramsareeasiertomaintain,astheyarerelativelylesscomplexandsmallerinsize.

(v) Theobject-orientedprogramsarebasedonthebottom-updesignmethodologywhile the procedural programs are based on thetop-downdesignmethodology.

BasicconceptsofOOP(Object-OrientedProgramming):-

Some of the essential elements of the object oriented programming arementionedbelow:

Abstraction

Objectsandclasses

ThreeOOPPrinciples

Encapsulation

InheritancePolymorphism

Persistence

Genericity

Composition/Aggregation

1.Abstraction:-

The abstraction is one of the essential elements of any programming languageincluding the procedural languages. The concept of built-in data type is also anabstraction. The feature of defining own data type using struct in C language furtherextendsthisabstraction.

Thebasicpurposeofabstraction is to reducecomplexitybyhidingdetails.Forexample, a building is not thought to be a collection of building material but a welldefinedobjecthavinguniquefeaturesandproperties.

Abstractioncanbedefinedasanact for identifying theessentialpropertiesandbehaviorofanobjectwithoutgoingintodetails.Thepropertiesandbehaviorsofanobjectdifferentiateitfromotherobjectsofsimilartypeandalsohelpinclassifying/groupingtheobjects.

Theobjectorientedprogramminglanguagesmodelabstractionusingclassesandobjects.

2.ObjectandClasses:-

Object:-An object is a physical or abstract entity or thing, which can bedistinguishedfromotherobjectsofsimilartypes.Anobjecthasthreecharacteristics:

(i)Identification.

(ii)Properties.(Attributes)

(iii)Behaviors.(Methods/Operations/Functions)

Theobjectcanalsobethoughtofasaninstanceofclass,whereclassislikeabuilt-indatatypeandtheobjectisthevariable.

Class:-Aclassrepresentsacategoryofobjectsbyabstractingtheirpropertiesandbehaviors.Aclasscanbethoughtofasablueprintforcreatingobjects.Anobjecthasthepropertiesandbehaviorsdefinedbyitsclass.Theclasscanbethoughtofasauser-defineddatatypeandobjectasavariable/instanceofthedatatyperepresentedbytheclass.

The properties/attributes of an object are defined by data members / fields inJava. 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 andmethodsarereferredtoasmembersoftheclass.

A classmay also be thought of as a user-defined data type and an object as avariableofthatdatatype.Onceaclasshasdefinedwecancreateanynumberofobjectsbelongingtothatclass.

3.ThreeOOPPrinciples:-

Encapsulation:-Encapsulationisthemechanismthatbindscodeanddataonwhichthecodeacts.Javaclassessupportthisastheyallowustodefinethecodeanddatatogether.Encapsulationalsohelpsinachievingdatahidingbydeclaringsomeoftheclassmembersasprivatesothattheycannotbeaccessedfromthecodethatdoesnotbelongtotheclass.

Inheritance:- In object-oriented programming, Inheritance refers to thepropertiesofaclassbeingavailabletootherclassescalledsub-classesorderivedclasses.Asub-classorderivedclassisonethatisderivedfromanexistingclass.Itinheritsallthefeatures of the existing classwhich is also referred as the base-class or super-class. Soinheritancecanbedefinedastheprocessofderivingaclassfromasuper-classorabase-class.Inheritingaclassdoesnotintroduceanychangesinthebase-class/super-class.Thederived-class/sub-class has a larger set of properties and behaviors as compared to thebase-class.

Themajoradvantageoftheinheritanceiscodereusability.Ifthebaseclassisinuseforalongtimeandthereisaneedtoaddsomeextraattributesandmethods,wecandosobyderivinganotherclass.Thederivedclasswillbeabletousecodeofthebaseclasswithoutdebuggingasitisinuseforalongtime.

ClassHierarchy:-All theclassesderivedfromacommonbaseclassbelongtoafamily and form a class hierarchy. The class hierarchy can be compared with a treestructurewhereonebaseclassisattherootanddoesnothaveasuper-class.

Allotherclassesareeitherderivedfromtheclassattherootofthehierarchyorfromsomeother class,which isderived from the root classdirectlyor indirectly.Morefeatures are added aswegodown the tree.The classes that are representedby the leafnodesdonothaveanysub-classes.Thefollowingexampleshowssomeclasshierarchies.

Polymorphism:-

Polymorphismisafeaturethatallowssameinterfacetobeusedforageneralclassofactions. Most of the object-oriented languages use polymorphism in the followingsituations.

OperatorOverloading.MethodOverloading.MethodOverriding.

OperatorOverloading:-

Mostofthelanguagesusethisformofpolymorphismforthebuilt-inoperations.Forexample,allthearithmeticoperatorsinC/C++orJavacanbeusedwithmanytypesofoperands(int,long,float,doubleetc.).Sosameadditionoperatorscanbeusedtoaddtwointegersaswellastoaddtwofloatingpointnumbers.

TheC++allowstheusertooverloadthebuiltinoperators.Forexample,wecanoverload the arithmetic operators to handle the complex numbers also.Although Javauses operator overloading for built-in operators but does not allow the user tooverloadtheoperators.

MethodOverloading:-

Thisfeatureallowsustowritemorethanonemethodswiththesamename.BothC++ and Java have this feature. The methods (function in C++) with same name aredifferentiatedbasedontheparameters(arguments).Theoverloadedmethodsmusteitherhave different number of parameters or the types of the parametersmust differ if theirnumberissame.

If the call to an overloadedmethod can be resolved at compile time i.e. if thecompiler can decide which of the overloadedmethodwill be called then this is calledstaticbinding,whichisanexampleofcompiletimepolymorphism.

Ifthecalltoanoverloadedmethodcannotberesolvedatcompiletimei.e.ifthecompilercannotdecidewhichoftheoverloadedmethodwillbecalledthenthisiscalleddynamicbinding,whichisanexampleofrun-timepolymorphism.

In general Java resolves calls to overloadedmethods at run-time but there aremanysituationswherethecallstooverloadedmethodsareresolvedatcompile-time.

MethodOverriding:-

Thesub-classcandefineamethodwiththesamenameasinthesuperclass,andthesamenumberandtypeofparameters.Thisiscalledmethodoverriding.

The compiler can not resolve calls to overriddenmethods. Java normally usesdynamicbindingtoresolvecallstooverriddenmethodsi.e.thedecisiontakesplaceatrun-time.

4.Persistence:-

Someobject-orientedlanguagesallowwetostore/retrievethestateofaprogramto / from a persistence storage media i.e. a permanent storage media like secondarystorage.Thisiscalledpersistence.

Javaallowsustostoreanyobjectonthesecondarystorageandtoretrieveitlateron.Ifweattempttostoreanobjectatthetopofanobjectgraph,alloftheotherreferencedobjectsarerecursivelylocatedandsaved.Similarlywhentheobjectisretrievedlateron,alloftheobjectsandtheirreferencesi.e.theentireobjectgraphiscorrectlycreatedinthemainmemory.

Forexample,itispossibletosaveanentiretreestructurebyjustsavingtherootofthetree.Atalaterstageitispossibletorecreatetheentiretreestructureinthememorybyjustsavingtherootofthetree.TheC++doesnotsupportthisfeature.

5.Genericity:-

Theconceptofdefininganalgorithmonce,independentlyofanyspecifictypeofdata, and then applying that algorithm to a wide variety of data types without anyadditionaleffortiscalledGenericity.C++supportsthisfeatureusingtemplates.Javaalsosupports this feature throughObject class,which is at the topof any class hierarchy inJava.

Forexample,using this feature,wecan implementagenericdata typestacksothatispossibletostoreelementofanytypeinthestack.Thisfeatureincreasesthedegreeofreusabilitytoalargeextent.

6.Composition/Aggregation

Anobjectmightbemadeupofotherobjects.SuchanobjectiscalledCompositeorAggregateobject.Forexample,itisappropriateifanobjectofclassvehicleisdefinedasacompositeobjectmadeupofobjectslikeEngine,Body,Axle,Seatsetc.

Inheritancev/sComposition:-

Therearetwobasicmechanismsforderivingnewclassesfromtheexistingones:Inheritance and composition. The class Bus can be derived by inheriting properties ofclass vehicle. Here Bus is a kind of vehicle which has some additional properties /behaviorsbesidethepropertiesandbehaviorswhicharecommonforallthevehicles.

InotherwordsclassBushasis-arelationshipwiththeclassvehicleaswecansaythatBusisavehicle.

The class vehicle itself might be derived from many other classes usingcomposition. For example, an object of class vehicle might be composed of objectsbelonging to classes like Engine, Gear Box, Seats, Driver’s Seat Body, and SteeringWheeletc.

The derived class in this case has whole-part relationship with the classesrepresentingparts of the composite object.Wecannot say that vehicle is anEngineorVehicleisaGearBoxasVehicleismadeupofanumberofparts.

SuperclassesandSubclassesOftenanobjectofoneclass“isan”objectofanotherclassaswell.A

rectanglecertainlyisaquadrilateral(asaresquares,parallelogramsandtrapezoids).Thus,class Rectangle can be said to inherit from class Quadrilateral. In this context, classQuadrilateralisasuperclass,andclassRectangleisasubclass.

Arectangleisaspecifictypeofquadrilateral,butitisincorrecttoclaimthat a quadrilateral is a rectangle (the quadrilateral could be a parallelogram). Figureshows several simple inheritance examples of superclasses and potentialsubclasses.Inheritance normally produces subclasses with more features than theirsuperclasses,sothetermssuperclassandsubclasscanbeconfusing.

Thereisanotherway,however,toviewthesetermsthatmakesperfectlygood sense.Because every subclass object “is an”object of its superclass, andbecauseonesuperclasscanhavemanysubclasses,thesetofobjectsrepresentedbyasuperclassisnormallylargerthanthesetofobjectsrepresentedbyanyofthatsuperclass’ssubclasses.

Forexample, thesuperclassVehicle represents inagenericmannerallvehicles,suchascars,trucks,boats,bicyclesandsoon.However,subclassCarrepresentsonlyasmallsubsetofalltheVehiclesintheworld.Inheritancerelationshipsformtree-likehierarchicalstructures.

Asuperclassexists inahierarchical relationshipwith its subclasses.Aclass can certainly exist by itself, but it iswhen a class is usedwith themechanismofinheritance that the class becomes either a superclass that supplies attributes andbehaviours to other classes or a subclass that inherits those attributes and behaviours.Frequently,oneclassisbothasubclassandasuperclass.

Superclass

Subclasses

Student Graduatestudent

UnderGraduatestudent

Shape Circle

Triangle

Rectangle

Loan CarLoan

HomeLoan

EducationLoan

Employee FacultyMember

StaffMember

Account CheckingAccount

SavingAccount

CHAPTER∞8∞

(PACKAGES)

Introduction-Whenweworkonaprojectwehavetobreakourprograminseveralclasses.To

organizeourclassesweusePackages.Thepackageisbothanamingandvisibilitycontrolmechanism.Packageisacollectionofclassesandinterfaceswhichareinterrelated.Withthehelpofpackageitispossibletogivesamenamestomorethanoneclassprovidedtheyaredefinedindifferentpackage.

Asinglepackagecan’tcontaintwoclasseswithsamename.

PROGRAMS are organized as sets of packages. Each package has its own set of sub-packages,whichhelpstopreventnameconflicts.Atoplevelpackageisaccessibleoutsidethe package only if it is declared as public. The naming structure for packages ishierarchical.Themembersofapackageareclassandinterfacetypesandsub-packages.Apackage in java is an encapsulationmechanism that canbeused to group related class,interfaceandsub-packages.

For small programs, a package can be unnamedor have a simple name, but ifcodeistobewidelydistributed,uniquepackagenamesshouldbechosen.

This can prevent the conflicts that would otherwise occur if two developmentgroupshappenedtopickthesamepackagenameandthesepackageswerelatertobeusedinasingleprogram.IfwedonotspecifyapackageforajavaclassthenthatclasswillbethepartofthedefaultpackageofJavacalledasunnamedpackage.Butthisrequiresthateveryclassmusthaveauniquenametoavoidcollision.

Exampleoftheunnamedpackage.

classA

{

-------

-------

}

classA_demo

{

publicstaticvoidmain(Stringargs[])

{

------

------

}

}

Howtodefineapackage

Tocreateapackage,includeapackagecommandasthefirststatementinaJavasourcefile.Anyclassdeclaredwithinthatfilewillbelongtothespecifiedpackage.Thepackage statement defines a name space in which classes are stored. If we omit thepackagestatement, theclassnamesareput intothedefaultpackage,whichhasnonameandiscalledasun-namedpackage.

Thepackagestatementhasthefollowingsyntax:

packagepackage_name;

Java uses file system directories to store packages. Remember that the case issignificant,anddirectorynamemustmatchthepackagenameexactly.Morethatonefilecanincludethesamepackagestatement.

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:-Ifwecompile the aboveprogramwith–d“javac–d .A.java” in “c:\javaprg>”thenthefolderp1willbecreatedautomaticallyandthe .classfileof theaboveprogramwillbesavedinthisfolder.Butifwedonotcompilewith–doptionthenitisourdutytocreatethep1folderandplacethe.classfileinthatfolder.(.)directsthecompilertocreatethep1folderinthecurrentfolder.Wecanalsotypethecompletepathifwewanttocreatethefolderinsomeotherfolderasjavac–dc:\javaprgA.java

Importingpackages:

All the inbuilt classes of Java are stored in some named packages; no class isstored in the unnamed default package. Since classes within packages must be fullyqualifiedwiththeirpackagenameornames.Itcouldbecometedioustotypeinthelongdot separated package path name for every classwewant to use. For this reason, javaincludestheimportstatementtobringcertainclasses,orentirepackages,intovisibility.Onceimported,aclasscanbereferredtodirectly,usingonlyitsname.

Theimportstatementisaconveniencetotheprogrammerandisnottechnicallyneededtowriteacompletejavaprogram.Ifwearegoingtorefertoafewdozenclassesinourapplication,thentheimportstatementwillsavealotoftyping.

Inajavasourcefile,importstatementoccursimmediatelyfollowingthepackagestatement (if it exists) and before any class definition. This is the general form of theimportstatement.

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:

Ifweruntheaboveprogramfromanyotherfolderotherthanthecurrentfolderthenitwillnotrun.BydefaulttheJavarun-timesystemusesthecurrentworkingdirectoryasitsstartingpoint.

Thus ifourpackage is in thecurrentdirectory,ora subdirectoryof thecurrentdirectory,itwillbefound.Buttoruntheaboveprogramfromanyotherfolderwehavetoset the class path using command SET CLASSPATH=.;C:\JAVAPRG on commandprompt. CLASSPATH is a environment variable.We have to type this command everytime when we start the computer for the first time. But if we put this command inMyComputer � properties � advanced � Environment variables then there is noneedtotypethiscommandagain&again.

WecanalsoruntheprogramwithoutsettingtheCLASSPATHenvironmentvariable.Todothistype

java–classpathc:\javaprgp1.A

Note4:-Wecan create a hierarchyof packages.Todo so, simply separate eachpackagenamefromtheoneaboveitbyuseofadot.Thegeneralformofamulti-leveledpackagestatementis:

packagepackage_name1[.package_name2][.package_name3];

ApackagehierarchymustbereflectedinthefilesystemofJavadevelopmentsystem.Forexamplepackagejava.awt.Imageneedtobestoredinjava\awt\image (WINDOWS)orjava/awt/image(UNIX)orjava:swt:image(MACINTOSH)filesystem.

Apackagehierarchyrepresentsanorganizationofthejavaclassesandinterfaces.Itdoesnotrepresentthesourcecodeorganizationoftheclassesandinterfaces.

Each java source file (also called compilation unit) can contain zero or moredefinition of classes and interfaces, but the compiler produces a separate class filecontaining the javabyte-codeforeachof them.Aclassor interfacecan indicate that itsjava-bytecodebeplacedinaparticularpackage,usingapackagedeclaration.

Thepackagejavahassub-packagesawt,applet,io,lang,net,andutil,butnoclassesorinterface.

Thepackagejava.awthasasub-packagenamedimage,aswellasanumberofclassesandinterfaces.

Becausethepackagejava.awthasasub-packageimage,itcannotcontainadeclarationofaclassorinterfacetypenamedimage.

IfthefullyqualifiednameofapackageisP,andQisasub-packageofP,thenP.Qisthefullyqualifiednameofthesub-package.

If there is a package namedmouse and amember class Button in thatpackage(whichthenmightbereferredtoasmouse.Button),thentherecannotbeanypackagewiththefullyqualifiednamemouse.Buttonormouse.Button.Click.

Atmostonepackagestatementcanappearinasourcefile,anditmustbethefirststatementintheJavasourcefile.

Visibilityofclassmember:

Class and package are both means of encapsulating and containing the namespaceandscopeofvariableandmethods.Packagesactascontainersforclassesandothersubordinatepackages.Classactasacontainerfordataandmethodcode.

Theclassisjava’ssmallestunitofabstraction.Becauseoftheinterplaybetweentheclassesandpackages,Javaaddressesfivecategoriesofvisibilityofclassmembers.

1.Visibilitywithintheclass.

2.Visibilityinsubclassinthesamepackages.

3.Visibilityinnonsubclassinthesamepackages.

4.Visibilityinsubclassesindifferentpackages.

5.Visibilityinsubclassesthatareneitherinthesamepackagenoraresubclass.

Note1:-

Toplevelclassandinterfacehasonlytwopossibleaccessdefaultandpublic.

Note2:-Ifclassisdeclaredpublicthenitisaccessiblebyusingothercode.

Note3:-Ifclasshasdefaultaccessthenitcanonlybeaccessedbyothercodewithinthesamepackage.

Note4:-The member visibility has meaning only if the class is visible. If visibilitymodifieroftheclassisdefaultthenevenpublicmembersoftheclasswillbevisibleonlywithinthepackage.

Accessspecifiers:

JARfiles:(JavaArchiveFiles)

Tocompressafileweusesomeprogramsuchaswinzipinthesamewayjava’sJAR feature can also be used to compress the entire hierarchy of a Java package. Itprovidesabetterfacilityforinstallation.

Thereisnoneedtocreatethefilestructureatthecustomerlocation.WehavetojustuseJARfileand this filewill restore theentire filestructure.All thepackage,sub-packageandclassfileswillbecreatedautomaticallyfromtheJARfile.

JAR technologymakes itmuch easier to deliver and install software.Also theelement inaJARfilearecompressed,whichmakedownloadingaJARfilemuchfasterthanseparatelydownloadingseveraluncompressedfile.Thisallowsaconsumertobesurethattheseelementswereproducedbyaspecificorganizationorindividual.

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”whichwillcontainallthefilesofpackagepack1incompressedform

ExtractJARfiles:

Thiscommandusedfortheextractthejarfiles.(suchasunzip)

c:\javaprg>jar–xfMyjar.jarTabulatingtheContentsofajarfile:

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”savedinjavaprgfolder.

Executeajarfile:

c:\javaprg>java–jarMyjar.jar

Theoryquestion’s:

1.Whatdoweunderstandaboutthepackages?

2. Explainall themodifiersand itsscope indifferentpackagesandsubpackageswithsubclassandotherclass.

3.WhatistheuseofJARfiles?

4.Whatistheuseoftheimportstatement?

SearchThisbookonAmazon.comwithISBN-978-1500730413.

CHAPTER∞9∞

(Interface)

Introduction-

An interface is basically kind of class. Like classes, interface containmethodsand variables butwith amajor difference. The difference is that interface defined onlyabstractmethods and final variables (Constants).Thismeans that interfacedonotwriteanycodetoimplementsthesemethodsanddatafieldscontainonlyconstants.

Therefore,itistheresponsibilityoftheclasstoimplementaninterfacedefiningthe code for implementation of these methods. Interfaces are syntactically similar toclasses,buttheylackinstancevariables,andtheirmethodsaredeclaredwithoutabody.Inpractice,thismeansthatwecandefineinterfaces,whichdonotmakeassumptionsabouthowtheyareimplemented.Thepurposeoftheinterfaceistoseparateaclass’sinterfacefrom its implementation. Interface just defines what a class must do without sayinganythingabouttheimplementation.Interfacesdefineonlymethodsignaturesandtheydonothaveanyinstancevariables.

Anested interface isany interfacewhosedeclarationoccurswithin thebodyofanother class or interface. A top-level interface is an interface that is not a nestedinterface.Thesyntaxfordefiningan interface isverysimilar to that fordefiningaclass.Thegeneralformofaninterfacedefinitionis:

interfaceinterface_name

{

variabledeclarations;

methodsdeclarations;

}

Here, interface is the keyword and interface_name is any valid java identifier (just likeclassname).

Note:Whenwedefineaninterfacethenbydefaultitispublicandabstract.

InterfaceModifiers:

Theonlymodifierthatcanbeusedwiththetop-levelinterfacesareabstractandpublic.Evenifwedonotuseabstractmodifier, theinterfaceisimplicitlydeclaredtobeabstractsouseofmodifierabstractisnotrequired.Thevisibilityofatop-levelinterfacecanbeeitherpackageorpublic just like top-levelclass. Ifnovisibilitymodifier isusedthenthevisibilityoftheinterfaceisassumedtobepackage.

DataVariableMemberDeclarations:

Onlyconstantscanbedefined in the interface.All thevariables inan interfaceare implicitly public, final and static meaning they cannot be changed by theimplementingclass.Theymustalsobeinitializedwithconstantvalue.

publicstaticfinaltypevariable_name=value;

Thevariabledeclared inan interface ispublic, static and final. Itmeans it is astaticvariablewithpublicaccess.Thevariableisalsodeclaredfinal,whichmeansthatitmustbeassignedavalueat thetimeofdeclaration,whichcannotbemodifiedlateron.ThekeywordfinalislikeconstinC/C++.

MethodsDeclarations:

Methods declaration will contain only a list of methods without anybodystatements. They end with a semicolon after the parameter list. They are essentially,abstract methods and there can be no default implementation of any method specifiedwithinaninterface.

All methods in the interface are always public and abstract modifiers by default. Wecannotdeclarestaticmethodsininterfaces.

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 declarationsimplyendswithasemicolon.

Anotherexampleofaninterface:

interfacearea

{

floatpi=3.142f;

floatcompute(floatx,floaty);

voidshow();

}

Extendinginterface:

Likeclasses,interfacecanalsobeextendedi.e.aninterfacecanbesub-interfacedfromotherinterface.Thenewinterfacewillinheritallthemembersofthesubinterfaceinthe manner similar to subclass. This is achieved using the keyword extends as shownbelow.

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 isallowedherebutall thevariablesintheinterfacearetreatedasconstant,public&staticalthoughthekeywordspublic,staticandfinalarenothere.

Wecancombineseveralinterfacestogetherintoasingleinterface.Followingdeclarationsarevalid.

interfaceinterface_1

{

intcode=1001;

Stringname=“Matrix”;

}

interfaceinterface_2

{

voiddisplay();

}

interfaceinterface_3extendsinterface_1,interface_2

{

-------

-------

}

Note:-

Alwaysrememberthataninterfacecannotextendclasses.Thiswouldviolatetherulethataninterfacecanhaveonlyabstractmethodsandconstants.

ImplementingInterface:

Interfacesareusedas“super-classes”whosepropertiesareinheritedbyclasses.Itisthereforenecessarytocreateaclassthatinheritsthegiveninterface.Onceinterfacehasbeendefined,oneormoreclassescanimplementthatinterface.

To implement an interface, include the implements clause in a class definition,andthencreatethemethodsdeclaredbytheinterface.

Theimplementingclassmustprovidebodyofallthemethodsinalltheinterfacesotherwiseitmustbedeclaredasabstract.

The implementing class may also extend a class and can implement multipleinterfaces.

modifierclass<class-name>implements<interface-name>

{

bodyoftheclass

}

Syntaxofaninterfaceimplementsintheclass

interfaceinterface_name

{

-------

}

classclass_nameimplementsinterface_name

{

Bodyofclass

}

Javadoesnotsupportmultipleinheritancebut it supportmultiple interface inheritancei.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. Theimplementinganinterfacemethodislikeover-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 mustdeclare stack class as a abstract class this technique is called to be a partialimplementation.

Variousformofinterfaceinheritance:-

(a)

(singlelevelinterfaceinheritance)

(b)

(multilevelinterfaceinheritance)

(c)

(hierarchicalinterfaceinheritance)

(d)

(hybridinterfaceinheritance)

AccessingImplementingClassObjectsThroughInterfaceReference:

Wecandeclarevariablesasobjectreferencesthatuseaninterfaceratherthanaclass type. Any instance of any class that implements the declared interface can bereferredtobysuchavariable.Whenwecallamethodthroughoneofthesereference,thecorrectversionwillbecalledbaseontheactualinstanceoftheinterfacebeingreferredto.

Thisisoneoftheimportantfeatureofinterfaces.Themethodtobeexecutedislookedupdynamicallyatruntime,allowingclassestobecreatelaterthanthecode,whichcallsmethodsonthem.Thecallingcodecandispatchthroughaninterfacewithouthavingto know anything about the “callee”. This process is similar to using a super classreferencetoaccessasubclassobject.

Becausedynamic lookupofamethodat run time incursa significantoverheadwhencomparedwiththenormalmethodinvocationinJava,weshouldbecarefulnot touseinterfacecasuallyinperformance-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.

Interfacecanbedeclaredasabstractbutitisabstractdefaultsothereisnoneedtoaddabstractkeyword.

Allvariablesarealwayspublicstatic&final.

Allmethodsofinterfacemustbeimplementedintheclass.

Allmethodsimplementedbytheimplementingclassmustbepublic.

Interfaceincludesdeclarationofthemethodsonly.

Interfacemethodscannotbedeclaredasstatic.Theyarealwaysdeclaredasaninstancemethods.

A class can neither narrow the accessibility of an interfacemethod norspecifynewexceptionsinmethod’sthrowsclause;asattemptingtodosowouldamount to altering the interfaces contract, which is illegal. The criteria foroverridingmethodsalsoapplywhenimplementinginterfacemethods.

Allmethodsneedtobedefinedaspublicintheimplementingclass.

Partialimplementsareallowedhereusingbyabstractkeywords.

Regardlessofhowmanyinterfacesaclassimplementsdirectlyorindirectly,itonlyprovidesasingleimplementationsofamethodthatmighthavemultipledeclarationsintheinterfaces.

Method prototype declarations can also be overloaded as in the case ofclasses.

Aninterfaceconstantcanbeaccessedbyanyclient (aclassor interface)using its fully qualified name, regardless of whether the client extends orimplements its interface. However, if a client is a class that implements thisinterfaceoraninterfacethatextendsthisinterface,thentheclientcanalsoaccesssuch constants directly without using the fully qualified name. Such a clientinheritstheinterfaceconstants.

Inthecaseofmultipleinheritanceofinterfaceconstantsanynameconflictscanberesolvedusingfullyqualifiednamesfortheconstantsinvolved.

InterfaceVariables:

Allvariablesintheinterfacearealwayspublicstaticandfinalbecausetheyarecommonpartfortheaccessofthedatatypesandmethodsfortheimplementing.

MemoryManagementoftheInterfaceVariable:

Staticvariablesalwaysget thememorywhenourprogram is tobe loaded theytaketheseparatememoryanddonotsharewiththeanyobject’smemory.Theyarealsocalledasconstantvariables.Theycanbeaccesseddirectlyusing interfacenameand the{.}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.51.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:- Herewe cannot call them3() using interface referencebecause thismethodsisnotdeclaredintheinterface.Sointerfacereferencecanaccessthosemethodswhicharedeclared in the self block.Otherwisewecancall the sameclassesobjectsorextendedclassesobjects.

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 InterfaceMethods:When any class implements themethods of the interface andalsodefinesadditionalmethodsintheclasswhicharenotdeclaredintheinterface, thenwe can say that the additional methods are non interface methods. Using referencevariableofinterfacewecan’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, namelyString andStringBuffer. Java String, as compared to C strings are more reliable andpredictable.This is basically due toC’s lack of bound checking.A javaString is not acharacterarrayandisnotNULLterminated.Ingeneral,JavadoesnotallowoperatorstobeappliedtoStringobjects.

Theoneexceptiontothisruleis+&+=operator,whichconcatenatestwostringsproducingaStringobjectasaresult.InJavacharacterarrayisnottreatedasstring.InJavaStringclass isdefined todoall stringoperations.TheclassStringandStringBuffer arepartofthejava.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 sequenceof characters,Butunlikemanyother language thatimplementsStringascharacterarrays,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 offeatures thatmake string handling convenient.Also string objects can be constructed anumberofways,makingiteasytoobtainastringwhenneeded.

[ii]Stringisimmutable:

Stringareimmutablei.e.wecannotchangethestringaftercreation.HoweveravariabledeclaredasaStringreferencecanbechangetopointsomeotherstringobjectatanytime.

Wecanstillperformall typeofstringoperation.Each timeweneedanalteredversionofanexistingstring,anewstringobjectiscreatedthatcontainsthemodifications.

The original string is left unchanged. This approach is used because fixed,immutablestringscanbeimplementedmoreefficientlythanchangeableones.

Forthosecasesinwhichamodifiedstringisdesired,thereisacompanionclasscalled StringBuffer, whose objects contain strings that can be modified after they arecreated.

[iii]Stringclassisfinal:

Both String and StringBuffer classes are final. Itmeanswe can’t extend classString in any other class.This allows certain optimization that increase performance ofcommonstringoperations.

Constructors&MethodsofStringclass:

1 publicString();

Initializes a newly createdStringobject so that it represents an empty charactersequence.

Strings1=newString();

2 publicString(Stringstr);

InitializesanewlycreatedStringobjectsothatitrepresentsthesamesequenceofcharactersas theargument; inotherwords, thenewlycreatedstringisacopyoftheargumentstring.

Strings1=newString(“Matrix”);

Strings2=newString(s1);

The string s2 is a copy of string s1.Although contents are same but s1 and s2pointstodifferentstringobjects.

3 publicString(charch[]);

AllocatedanewString so that it represents the sequenceofcharacterscurrentlycontainedincharacterarrayargument.

charch[]={‘a’,‘b’,‘c’};

Strings1=newString(ch);//s1willhold“abc”

4 publicString(charvalue[],intoffset,intcount);

AllocatesanewStringthatcontainscharactersfromasub-arrayof thecharacterarrayargument.

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 integerarrayargumentcontainingUnicodeofcharacters.

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 theplatform’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 theplatform’sdefaultcharset.

byteb[]={97,98,99};

Strings1=newString(b);//s1willhold“abc”

EventhoughJava’schartypeused16bitstorepresenttheUnicodecharacterset,thetypicalformatforstringsontheInternetusesarraysof8-bitbytesconstructedfromtheASCIIcharacterset.Because8-bitASCIIstringsarecommon,theStringclassprovidesconstructorsthatinitializeastringwhengivenabytearray.Ineachof the above constructors the byte to character conversion is done by using thedefaultcharacterencodingoftheplatform.

8 publicString(StringBuffer);

9 publicintlength();

Thiswilldisplaynumberofcharactersofthestring.

10 publicbooleanisEmpty();

Thiswilldisplaytrueifthestringisemptyotherwisefalse.

Strings1=newString();

System.out.println(s1.isEmpty());

11 publiccharcharAt(intindex);

Returnsthecharvalueatthespecifiedindex.Anindexrangesfrom0tolength()–1.Thefirstcharvalueofthesequenceisatindex0,thenextatindex1,andsoon,asforarrayindexing.ThrowsStringIndexOutOfBoundsExceptionifinvalidindexisspecified.

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 firstcharacter to be copied is at index srcBegin, the last character to be copied is atindex 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 indexdstBeginandendingatindex:dstBegin+(srcEnd–srcBegin)–1.ThismethodmaythrowArrayIndexOutOfBoundExceptionandStringIndexOutOfBoundsException.

13 publicvoidgetBytes(intsrcBegin,intserEnd,bytedst[],intdstBegin);

14 publicbyte[]getBytes();

EncodesthisStringintoasequenceofbytesusingtheplatform’sdefaultcharset,storingtheresultintoanewbytearray.Thismethodismostusefulwhenweareexportingastringvalueintoanenvironmentthatdoesnotsupport16-bitUnicodecharacter. For example, most Internet protocols and text file formats use 8-bitASCIIforalltextinterchange

15 publicbooleanequals(Object);

Compares the invokingstringwith the specifiedobject.The result is true if andonly if the argument is not null and is a String object that represents the samesequenceofcharactersastheinvokingstring.

16 publicbooleanequalsIgnoreCase(String);

Compares the invoking String with the anotherString, ignoring caseconsiderations.

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, Stringstr2,intstr2StartIndex,intlen);

Tests if twostringregionsareequal. It ignores thecasedifference if ignoreCaseflagistrue

21 publicbooleanstartsWith(Stringprefix,intstartIndex)

Tests if this string starts with the specified prefix beginning at specified index.ThismethoddoesnotreturnanyexceptionbutreturnsfalseifstartIndexisoutofbound.

22 PublicbooleanstartsWith(String);

Testsifthisstringstartswiththespecifiedprefix.

23 publicbooleanendsWith(Stringsuffix)

Testsifthisstringendswiththespecifiedsuffix.

24 publicintindexOf(charch);

Returns the index within this string of the first occurrence of the specifiedcharacter.

25 publicintindexOf(charch,intfromIndex);

Returns the index within this string of the first occurrence of the specifiedcharacter,startingthesearchatthespecifiedindex.

26 publicintindexOf(Stringstr);

Returns the index within this string of the first occurrence of the specifiedsubstring.

27 publicintindexOf(Stringstr,intfromIndex);

Returns the index within this string of the first occurrence of the specifiedsubstring,startingatthespecifiedindex.

28 publicintlastIndexOf(intch);

Returns the index within this string of the last occurrence of the specifiedcharacter.

29 publicintlastIndexOf(intch,intfromIndex);

Returns the index within this string of the last occurrence of the specifiedcharacter,searchingbackwardstartingtheatthespecifiedindex.

30 publicintlastIndexOf(Stringstr);

Returns the index within this string of the last occurrence of the specifiedsubstring.

31 publicintlastIndexOf(Stringstr,intfromIndex);

Returns the index within this string of the last occurrence of the specifiedsubstring,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.Thisfunctionisprovidedasaconvenience,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, itdoessobycallingoneoftheoverloadedversionsoftheStringconversionmethodvalueOf( ) defined byString class.The valueOf( ) is a staticmethod overloaded for all simpletypesandfortypeObject.

Forthesimpletypes,valueOf()returnsstringthatcontainsthehuman-readableequivalentofthevaluewithwhichitiscalled.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 displaysnameoftheclassfollowedbysymbol“@”andthenobject-id(e.g.Box@ab1342),whichisnormallyofnouse.Formostimportantclassesthatwecreate,wewillwanttooverridetoString()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:

StringBuffer isapeerclassofString thatprovidesmuchof thefunctionalityofString. As we know, String represents fixed length, immutable character sequence. Incontrast to String, StringBuffer represents growable and writeable character sequences.StringBuffermayhavecharactersandsubstringsinsertedinthemiddleorappendedtotheend.

StringBufferwillautomaticallygrowtomakeroomforsuchadditionsandoftenhasmore 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 javamanipulateStringBufferbehindthescenesbyusingtheoverloaded+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 theStringBufferobjectandreservesroomfor16morecharacterswithoutreallocation.

publicsynchronizedintlength();

ReturnsthecurrentlengthoftheStringBuffer.

publicsynchronizedintcapacity();

Returnsthecurrentcapacity.Thecapacityistheamountofstorageavailablefornewlyinsertedcharacters,beyondwhichanallocationwilloccur.

publicsynchronizedvoidensureCapacity(int);

Ensuresthatthecapacityisatleastequaltothespecifiedminimum.Ifwewanttopre-allocateroomforacertainno.ofcharactersafteraStringBufferhasbeenconstructed,wecanuseensureCapacity()method to set the sizeof thebuffer.This isuseful ifweknow in advance that we will be appending a large number of small strings to aStringBuffer.

publicsynchronizedvoidtrimToSize();

Thiswillremoveextrafreespace.NowCapacitywillbeequaltolength.

publicsynchronizedvoidsetLength(intnewLength);

Setsthelengthofthecharactersequence.ThenewLengthmustbenon-negative.Whenwe increase the sizeof thebuffer,nullcharactersareadded to theendof theexistingbuffer. If we call setLength() with a value less then the current value returned bylength(),thenthecharactersstoredbeyondthenewlengthwillbelost.

publicsynchronizedcharcharAt(intindex);

Returnsthecharvalueinthissequenceatthespecifiedindex.

public synchronized void getChars(int srcBegin, int srcEnd, char[] dst, intdstBegin)

Characters are copied from this sequence into thedestination character arraydst.Thefirst character to be copied is at index srcBegin; the last character to be copied is atindex srcEnd-1. The total number of characters to be coped is srcEnd-srcBegin. ThecharactersarecopiedintothesubarrayofdststartingatindexdstBegin.

Note:Ensurethatthedestinationortargetarrayislargeenoughtoholdthenumberofcharacterinthespecifiedsubstring.

publicsynchronizedvoidsetCharAt(intindex,charch);

Thecharacteratthespecifiedindexissettoch.IndexOutOfBoundsExceptionoccursifindexinnegativeorgreaterthanorequaltolength().

publicsynchronizedStringBufferappend(Object);

Theappendmethodconcatenates thestringrepresentationofanyother typeofdata totheendoftheinvokingStringBufferobject.

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 thespecifiedString.

publicsynchronizedStringsubstring(int);

ReturnsanewStringthatcontainsasubsequenceofcharactercurrentlycontainedinthischaractersequence.Thesubstringbeginsatthespecifiedindexandextendstotheendofthissequence.

publicsynchronizedStringsubstring(intstart,intend);

ReturnsanewString that contains a subsequenceof characters currently contained inthischaractersequence.Thesubstringbeginsatthespecifiedstartindexandextendstothecharacteratindexend-1.

publicsynchronizedStringBufferinsert(int,Object);

InsertoneStringintoanotherString.ItisoverloadedtoacceptvaluesofallthesimpletypesplusStringsandObjects.

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-

AnExceptionisaconditionthatiscausedbyaruntimeerrorintheprogramthatbreaksthenormalflowoftheprogram.Whenthejavainterpreterencountersanerrorsuchasdividinganintegerbyzero,itcreatesanExceptionobjectandthrowsit.(i.e.,informusthatanerrorisoccurred).

AJavaexception/errorisanobjectofclassExceptionoroneoftheirsub-classeswheneverexceptionoccursattherun-time.Theexceptionobjectcontainsdetailsaboutthe

exceptionwhichcanbeaccessedusingthepublicmethodsprovidedforthispurpose.

Insomeolderlanguageswehavetouseif,gotoandreturncodesforerrorhandling.

Anexception is anabnormal condition that arises in a code sequenceat runtime.Inotherwords,anexceptionisaruntimeerror.Incomputerlanguagesthatdonotsupport exception handling, errors must be checked and handled manually—typicallythroughtheuseoferrorcodes,andsoon.

This approach is as cumbersome as it is troublesome. Java’s exceptionhandling avoids these problems and, in the process, brings run-time errormanagementintotheobject-orientedworld.

Exception-HandlingFundamentals

AJavaexceptionisanobjectthatdescribesanexceptional(thatis,error)conditionthathasoccurredinapieceofcode.Whenanexceptionalconditionarises,anobjectrepresentingthatexceptioniscreatedandthrowninthemethodthatcausedtheerror.Thatmethodmaychoosetohandletheexceptionitself,orpassiton.

Eitherway,atsomepoint,theexceptioniscaughtandprocessed.Exceptionscanbegeneratedby the Java run- timesystem,or theycanbemanuallygeneratedbyyourcode.ExceptionsthrownbyJavarelatetofundamentalerrorsthatviolatetherules of the Java language or the constraints of the Java execution environment.Manuallygeneratedexceptionsaretypicallyusedtoreportsomeerrorconditiontothecallerofamethod.

Javaexceptionhandlingismanagedviafivekeywords:try,catch,throw,throws,andfinally.Briefly,hereishowtheywork.Programstatementsthatyouwant tomonitor for exceptions are contained within a try block. If an exceptionoccurswithinthetryblock,itisthrown.Yourcodecancatchthisexception(usingcatch)and handle it in some rational manner. System-generated exceptions are automaticallythrownbytheJavaruntimesystem.Tomanuallythrowanexception,usethekeywordthrow.Anyexceptionthatisthrownoutofamethodmustbespeci0edassuchbyathrowsclause.

Anycode that absolutely must be executed after a tryblockcompletes isput inafinallyblock.

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 belowThrowablearetwosubclassesthatpartitionexceptionsintotwodistinctbranches.OnebranchisheadedbyException.Thisclassisusedforexceptionalconditionsthatuserprogramsshouldcatch.Thisisalsotheclassthatyouwillsubclasstocreateyourowncustomexceptiontypes.

There is an important subclass of Exception, calledRuntimeException.Exceptionsofthistypeareautomaticallydefinedfortheprogramsthatyouwriteandincludethingssuchasdivisionbyzeroandinvalidarrayindexing.

The other branch is topped by Error, which defines exceptions that are notexpectedtobecaughtundernormalcircumstancesbyyourprogram.ExceptionsoftypeErrorareusedbytheJavarun-timesystemtoindicateerrorshavingtodowith the run-timeenvironment, itself.Stackoverflowisanexampleofsuchan error.ThischapterwillnotbedealingwithexceptionsoftypeError,becausethesearetypicallycreatedinresponsetocatastrophicfailuresthatcannotusuallybehandledbyyourprogram.

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 notinitializedwithnew.Theprogramgetsterminatedinthiscasealso.

Example11.3

1.classErrorTest3

2.{

3.publicstaticvoidmain(Stringargs[])

4.{

5.inta[]={10,20,30};

6.System.out.println(a[3]);//ArrayIndexOutOfBoundsExceptionoccurred

7.}

8.}

Intheabovecasethelengthofarrayis3andtheindexisfrom0to2,soifweprinta[3]then this is the 4th elementwhich is not a valid index. Thiswill generate an exceptionerror.InC/C++itisallowedbutnotinJava.

NOTE-

JDK 7 adds a new form of the try statement that supports automatic resourcemanagement. This new form of try, called try-with-resources, is described in fileChapterinthecontextofmanagingfilesbecausefilesaresomeofthemostcommonlyusedresources.

OthercasesofExceptions

1. Thefilewearetryingtoopenmaynotexist.

2. Wewanttocreateanewobjectbutnomemoryisavailable.

3. Theclassfilewewanttoloadmaybemissingorinthewrongformat.

4. The String, which we want to convert to a number, is having invalidcharacterssothatitcannotbeconvertedtoanumber.

Iftheexceptionobjectisnotcaughtandhandledproperly,theinterpreterwilldisplayanerrormessageandwillterminatetheprogram.Ifwewanttocontinuewiththeexecutionwiththeremainingcode,thenweshouldtrytocatchtheexceptionobjectthrownbytheerrorcondition.

Thistaskisknownasexceptionhandling.Thepurposeoftheexceptionhandlingmechanismistoprovideameanstodetectareportan“exceptionalcircumstance”sothattheappropriateactioncanbetaken.Thismechanismsuggestsincorporationofaseparateerrorhandlingcodethatperformsthefollowingtasks:

1.Findtheproblem.(Exceptionoccur)

2.Informthatanerrorhasoccurred.(throwtheexception)

3.Receivetheerrorinformation.(catchtheexception)

4.Thecorrectiveaction.(handletheexception)

JavaExceptionhandlingismanagedviafivekeywords:

try,catch,throw,throwsandfinally.Programstatementsthatwewanttomonitorforexceptionarecontainedwithina

tryblock,andwheneveranerroroccursthenitisthrowntothecatchblock.Ourcodecancatchthisexception(usingcatch)andhandleitinsomerationalmanner.Systemgeneratedexceptionareautomaticallythrownbythejavaruntimesystem.

Tomanually throwanexception,use thekeyword throw.Anyexception that isthrown out of a method must be specified as such by a throws clause. Any code thatabsolutelymustbeexecutedbeforeamethodreturnsisputinafinallyblock.

The try block must be enclosed between braces even if there is only onestatement in it. There can be one or more catch statements and zero or one finallystatement.Both catch and finally blocks are optional but either one catch block or onefinallyblockismust.

ThecodeinthetryblockisexecutedlikeanyotherJavacode.Ifthecodeinsidethetryblockexecutessuccessfullythenthecontrolgoestofinallyblockifitispresentandthentheexecutioncontinuesfromthestatementjustaftertheendoffinallyblock(i.e.after the end of try statement) If the finally block is not present then the executioncontinues from the statement just after the last catch block (i.e. after the end of trystatement).

If some run-time error occurswhile executing the code in try block then JVMthrowsanExceptionError.ThismeansanobjectoftypeExceptionErrororoneofitssub-classesiscreateddependingonthetypeoftherun-timeerror.ThisisthencomparedwiththeException/Errortypesofthecatchblocksintoptobottomorder.

If a matching catch block is found then the exception / error is handled i.e.programwillnotterminate.Theexecutioncontinueswiththefirststatementinthecatchblock.Oncompletionofthecatchblock,executioncontinueswiththestatementjustaftertheendoftry&catchstatement.

At the most one catch block is executed irrespective of the number of catchblocks.Ifexception/errordoesnotmatchwithexception/errortypeofanyofthecatchblocks,thenwesaythatitisnothandled.

The executionwill immediately return from try block. The code in the finallyblockwillbeexecutedeveniftheexception/errorisnothandled.

The exception / error will then be handled by outer try block if there is oneotherwiseitmustbehandledinthemethodwhichcalledthecurrentmethod.

Theexception/errormovesupthehierarchytill it ishandledor it ispassedtoJVMunhandledifnothandledeveninthemain()methodwhichisthefirstmethodfromwhichtheexecutionstarts.

TheJVMthensimplyterminatestheprogramanddisplaystheexception/errordetailsonthemonitor/console.

HerewehaverepresentsomeExceptionwhichcanbeoccurattheexecutiontimeintheprogram.

Usingtryandcatch-

Although the default exception handler provided by the Java run-time system is

usefulfordebugging,youwillusuallywanttohandleanexceptionyourself.Doingsoprovidestwobene0ts.First,itallowsyouto0xtheerror.

Second,itpreventstheprogramfromautomaticallyterminating.Mostuserswouldbeconfused(tosaytheleast)ifyourprogramstoppedrunningandprintedastacktracewheneveranerroroccurred!Fortunately,itisquiteeasytopreventthis.

Toguardagainstandhandlearun-timeerror,simplyenclosethecodethatyouwanttomonitor inside a tryblock. Immediately following the try block, include acatchclausethatspeci0estheexceptiontypethatyouwishtocatch.

Toillustratehoweasilythiscanbedone,thefollowingprogramincludesatryblockandacatchclausethatprocessestheArithmeticExceptiongeneratedbythedivision-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 anexceptionisthrown,programcontroltransfersoutofthetryblockintothecatchblock.

Putdifferently,catchisnot“called,”soexecutionnever“returns”tothetryblockfromacatch.

Thus,theline“Thiswillnotbeprinted.”isnotdisplayed.Oncethecatchstatement has executed, program control continues with the next line in the programfollowingtheentiretry/catchmechanism.

A try and its catch statement form a unit. The scope of the catch clause isrestrictedtothosestatementsspecifiedbytheimmediatelyprecedingtrystatement.

Acatchstatementcannotcatchanexceptionthrownbyanothertrystatement(exceptinthecaseofnestedtrystatements,describedshortly).Thestatementsthatareprotectedbytrymustbesurroundedbycurlybraces.(Thatis,theymustbewithinablock.)Youcannotusetryonasinglestatement.

Thegoalofmostwell-constructedcatchclausesshouldbetoresolvetheexceptionalconditionandthencontinueonasiftheerrorhadneverhappened.Forexample,inthenextprogrameachiterationoftheforloopobtainstworandomintegers.

Those two integersaredividedbyeachother,and the result isused todividethevalue12345.Thefinalresultisputintoa.Ifeitherdivisionoperationcausesadivide-by-zeroerror,itiscaught,thevalueofaissettozero,andtheprogramcontinues

//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 aprintln()statementbysimplypassingtheexceptionasanargument.Forexample,thecatchblockintheprecedingprogramcanberewrittenlikethis:catch(ArithmeticExceptione)

{

System.out.println(“Exception:”+e);

a=0;//setatozeroandcontinue

}

Whenthisversionissubstitutedintheprogram,andtheprogramisrun,eachdivide-by-zeroerrordisplaysthefollowingmessage:

Exception:java.lang.ArithmeticException:/byzeroWhile it is of no particular value in this context, theability to display a description of an exception isvaluable in other circumstances—particularlywhen youare experimenting with exceptions or when you aredebugging.

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 notallowedbythebrowser’ssecuritysetting

StackOverflowException TheSystemrunsoutofstackspace

StringIndexOutOfBoundsException Aprogramattempttoaccessanonexistentcharacterpositioninastring

Java’sBuilt-inExceptions

Insidethestandardpackagejava.lang,Javadefinesseveralexceptionclasses.Afewhavebeenusedbytheprecedingexamples.Themostgeneraloftheseexceptions

aresubclassesofthestandardtypeRuntimeException.

Aspreviouslyexplained,theseexceptionsneednotbeincludedinanymethod’sthrowslist. In the language of Java, these are called unchecked exceptions because thecompilerdoesnotchecktoseeifamethodhandlesorthrowstheseexceptions.Theuncheckedexceptionsdefinedinjava.langarelistedinTable-1.Table-2liststhoseexceptionsdefinedby java.lang thatmustbe included inamethod’s throws list if thatmethodcangenerateoneoftheseexceptionsanddoesnothandleititself.Thesearecalledcheckedexceptions.Javadefinesseveralothertypesofexceptionsthatrelatetoitsvariousclasslibraries.

GeneralformofanExceptionhandling

(Exceptionhandlingmechanism)

Syntax:

------------

------------

try

{

statement;//generatesanexception

}

catch(Exception-typee)

{

statement;//processtheexception

}

------------

------------

MultiplecatchClauses

Insomecases,morethanoneexceptioncouldberaisedbyasinglepieceofcode.Tohandlethistypeofsituation,youcanspecifytwoormorecatchclauses,eachcatchingadifferenttypeofexception.

Whenanexceptionis thrown,eachcatchstatementis inspectedinorder, andthe0rstonewhosetypematchesthatoftheexceptionisexecuted.Afteronecatchstatementexecutes,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 nocommand-line arguments, since a will equal zero. It will survive the division if youprovidea commandlineargument, settinga to something largerthanzero. But itwillcauseanArrayIndexOutOfBoundsException,sincetheintarraychasalengthof1,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,itisimportanttorememberthatexceptionsubclassesmustcomebeforeanyoftheirsuperclasses.Thisisbecauseacatchstatementthatusesasuperclasswillcatchexceptionsofthattypeplusanyofitssubclasses.

Thus,a subclass would never be reached if it came after its superclass.Further, in Java, unreachable code is an error. For example, consider the followingprogram:

/*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.”);

}

}

}

Ifyoutry tocompile thisprogram,youwill receiveanerrormessage stating that thesecond catch statement is unreachable because the exception has already beencaught. Since ArithmeticException is a subclass of Exception, the first catchstatementwillhandleallException-basederrors,includingArithmeticException.

Thismeansthatthesecondcatchstatementwillneverexecute.Tofixtheproblem,reversetheorderofthecatchstatements.

NestedtryStatements

Thetrystatementcanbenested.Thatis,atrystatementcanbeinsidetheblockofanothertry.Eachtimeatrystatementisentered,thecontextofthatexceptionispushedonthestack.

Ifaninnertrystatementdoesnothaveacatchhandlerforaparticularexception,thestackisunwoundandthenexttrystatement’scatchhandlersareinspectedforamatch.

Thiscontinuesuntiloneofthecatchstatementssucceeds,oruntilallofthenestedtrystatementsareexhausted.Ifnocatchstatementmatches,thentheJavarun-timesystemwillhandletheexception.

Hereisanexamplethatusesnestedtrystatements:

Multiplecatchstatement

Whentherearemorethanonecatchstatementthenitissaidtobeamultiplecatchstatement.

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,afterdisplayingthemessage“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/Errorspropagateupthecallstackatruntime-firstuptheenclosingtryblocksandthenbacktothecallingmethod-untilanexceptionhandlercatchthem.

The location of the exception / error is known exactly as entire stack trace isavailabletotheuser.Thisisveryhelpfulindebugging.

Programmergetsachancetorecoverfromtheerror/abnormalcondition.

Errorhandlingcode is separated from thenormalprogramflow to increase thereadabilityandmaintainability

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 animmediate subclass of the object class. Exceptions/Errors are also objects inJava.SubclassesofExceptionhavethesuffixException.

Therearetwoimmediatesubclassoftheclassthrowable.

Error:-ThesubclassesofErrorclassarebasicallyusedforsignalingabnormalsystemconditionslike:

1. OutOfMemoryError signals that the JavaVMhas run out ofmemory andthatthegarbagecollectorisunabletoclaimanyfreememory.

2. StackOverflowErrorsignalsastackoverflowintheinterpreter.

Theerrorsare,ingeneral,unrecoverableandshouldnotbehandled.

Exception:-The sub classes ofException class are, in general recoverable. Forexample,EOFExceptionsignalsthatafilewehaveopenedhasnomoredataforreading.FileNotFoundExceptionsignalsthatafilewewanttoopendoesnotexistinthefilesystem.

ExampleoftheErrorhierarchy:

Exceptioncategorizedintwotypes

-CheckedException.

-UncheckedException.

CheckedException

If it is must to catch an exception then it is called a checked exception. Theprogramwillnotcompileifthereisapossibilityofoccurringcheckedexceptioninatryblockanditisnothandled.

Thecompilerensuredthatifamethodcanthrowacheckedexception,directlyorindirectly,thenthemethodmustexplicitlydealwithit.Themethodmusteithercatchtheexceptionandtaketheappropriateaction,orpasstheexceptionontoitscaller.

Note:Exceptionandallof its sub-class (Excluding run time-exceptionand its subclass)arecheckedandmustbecaught.

UncheckedException

Ifitisnotmusttocatchanexceptionthenitscalledanuncheckedexception.Theprogramwillcompileeven if theuncheckedexception isnothandled. Ifanyuncheckedexception occurs in a program which is not handled then the program execution willterminate at that point. But if exception is handled then program will not terminatebecauseofexception.

Note:-Errorandallofitssubclassareuncheckedexceptionandneednotbecaught.Run-timeExceptionandallofitssubclassareuncheckedexceptionandneednotbecaught.AlluserdefinedExceptionarechecked.

MethodsavailableinExceptionclass-

StringgetMessage() To obtain the error message associated withexceptionorerror.

voidprintStackTrace()

To print a stack trace showing where theexception/erroroccurs.

StringtoString() To show the exception/error name along with themessagereturnedbygetMessage().

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

Ifwe use try and catch statements in another try block then it is said to be anestedtrycatch.

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 tohandle an exception that is not caught by any of the previous catch statement. finallyblockcanbeusedtohandleanyexceptiongeneratedwithinatryblock.Itwillexecutedinall the cases whether error occurred or not. It may be added immediately after the tryblockorafterthelastcatchblockshownasfollows:

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-timesystem.Howeveritspossibleforourprogramtothrowanexceptionexplicitly,usingthethrowstatement,thegeneralformofthrowisshownhere:

throwThrowableinstance;

Here,ThrowableinstancemustbeanobjectoftypeThrowableorasubclassofThrowable.Simple typesuchas intorchar, aswell asnon-Throwableclasses suchasString andObject, cannot be used as exception. There are twowayswe can obtain aThrowable object:usingaparameter intoacatch clause,or creatingonewith thenewoperator

The flow of execution stops immediately after the throw statement; anysubsequentstatementarenotexecuted.Thenearestenclosingtryblockisinspectedtoseeifithasacatchstatementthatmatchesthetypeoftheexception.Ifitdoesfindamatch,control is transferred to that statement. If not then the next enclosing try statement isinspected, and soon. If nomatchingcatch is found, then thedefault exceptionhandlerhaltstheprogramprintsthestacktrace.

Herewehavetakenaprogramthatcreatesandthrowsanexception.Thehandlerthatcatchestheexceptionrethrowsittotheouterhandler.

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 amethod is capableof causing an exception that it doesnot handle, itmustspecify this behavior so that caller of the method can guard themselves against thatexception.Wedothisbyincludingathrowsclauseinthemethod’sdeclaration.Athrowsclauseliststhetypeofexceptionthatamethodmightthrow.

This is necessary for all checked exceptions.All exceptions that amethod canthrowmust be declared in the throws clause. If they are not, a compile-time errorwillresult. This is a general form of a method declaration that includes a throwsclause:

Syntax:

typemethod-name(parameterlist)throwsexception-list

{

//bodyofmethod

}

Here,exceptionlistisacomma-separatedlistoftheexceptionthatamethodcanthrow

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.Oursubclassesdonotneed to actually implement anything.TheException/Error classdoesnotdefineanymethodsofitsown.Itdoes,ofcourse,inheritmethodsprovidedbyThrowableclass.

Although Java’s built-in exceptions handlemost common errors, you will probablywant to create your own exception types to handle situations specific to yourapplications.Thisisquiteeasytodo:justdefineasubclassofException(whichis,ofcourse,asubclassofThrowable).

Yoursubclassesdon’tneedtoactuallyimplementanything—itistheirexistenceinthetypesystemthatallowsyoutousethemasexceptions.

TheExceptionclassdoesnotdefineanymethodsofitsown.Itdoes,ofcourse,inheritthosemethods providedbyThrowable.Thus, all exceptions, including those that youcreate,havethemethodsdefinedbyThrowableavailabletothem.

Exceptiondefinesfourconstructors.Twosupportchainedexceptions,describedinthenextsection.Theothertwoareshownhere:

Exception()

Exception(Stringmsg)

Thefirstformcreatesanexceptionthathasnodescription.Thesecondformletsyouspecifyadescriptionoftheexception.

Although specifying a descriptionwhen an exception is created is often useful,sometimes it is better tooverride toString( ).Here’swhy:Theversionof toString()definedbyThrowable(andinheritedbyException)

first displays the name of the exception followed by a colon, which is thenfollowed by your description. By overriding toString( ), you can prevent theexceptionnameandcolonfrombeingdisplayed.Thismakesforacleaneroutput,whichisdesirableinsomecases.

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

ThefollowingexampledeclaresanewsubclassofExceptionandthenusesthatsubclass to signal an error condition in a method. It overrides the toString( )method,allowingacarefullytailoreddescriptionoftheexceptiontobedisplayed.

ThisexampledefinesasubclassofExceptioncalledMyException.Thissubclassisquite simple: It hasonly a constructor plus an overridden toString( ) method thatdisplaysthevalueoftheexception.

TheExceptionDemoclassdefinesamethodnamedcompute()thatthrowsaMyExceptionobject.Theexceptionisthrownwhencompute()’sintegerparameteris greater than 10. The main( ) method sets up an exception handler forMyException,thencallscompute()withalegalvalue(lessthan10)andanillegalonetoshowbothpathsthroughthecode.

Hereistheresult:

Calledcompute(1)

Normalexit

Calledcompute(20)

CaughtMyException[20]

ChainedExceptions:

Thechainedexception featureallowsus toassociateanotherexceptionwithanexception.Thissecondexceptiondescribesthecauseofthefirstexception.Forexample,imagine a situation in which a method throws an ArithmeticException because of anattempttodividebyzero.However,theactualcauseoftheproblemwasthatanI/Oerroroccurred,whichcausedthedivisortobesetimproperly.

AlthoughthemethodmustcertainlythrowanArithmeticException,sincethatistheerrorthatoccurredWemightalsowanttoletthecallingcodeknowthattheunderlyingcausewasasI/Oerror.

Toallowchainedexceptions,Java2,version1.4addedtwoconstructorsandtwomethodstoThrowableclass.Theconstructorsareshownhere:

Throwable(ThrowablecauseExc)

Throwable(Stringmsg,ThrowablecauseExc)

Inthefirstform,causeExcistheexceptionoccurred.Thesecondformallowsusto specify a description at the same time thatwe specify a cause exception.These twoconstructorshavealsobeenaddedtotheError,Exception,andRuntimeExceptionclasses.

The chained exception methods added to Throwable class are getCause() andinitCause()

ThrowablegetCause()

ThrowableinitCause(ThrowablecauseExc)

The getCause( ) method returns the exception that underlies the currentexception. If there is no underlying exception, null is returned.The initCause()methodassociatescauseExcwiththeinvokingexceptionandreturnsareferencetotheexception.Thus, we can associate a cause with an exception after the exception has created.However,thecauseexceptioncanbesetonlyonce.

ThuswecancallinitCause()onlyonceforeachexceptionobject.Furthermore,ifthecauseexceptionwassetbyaconstructor,thenwecannotsetitagainusinginitCause()method.Ingeneral, initCause()isusedtosetacauseforlegacyexceptionclasseswhichdo not support the two additional constructors described earlier.Most of Java’s built-inexceptionsdonotdefinetheadditionalconstructors.Thus,wewilluseinitCause() ifweneedtoaddanexceptionchaintotheseexceptions.

Chainedexceptionsarenotsomethingthateveryprogramwillneed.However,incasesinwhichknowledgeofanunderlyingcauseisuseful,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, the top-level exception isNullPointerException. To it is addedacause exception, ArithmeticException. When the exception is thrown out ofdemoproc(),itiscaughtbymain().There,thetop-levelexceptionisdisplayed,followedbytheunderlyingexception,whichisobtainedbycallinggetCause().

Chained exceptions can be carried on to whateverdepth isnecessary.Thus, thecause exception can, itself, have a cause. Beaware that overly long chains ofexceptionsmayindicatepoordesign.Chainedexceptionsarenotsomethingthateveryprogramwillneed.However,incasesinwhichknowledgeofanunderlyingcauseisuseful,theyofferanelegantsolution.

ThreeNewJDK7ExceptionFeatures(UPDATED)

JDK7addsthreeinterestingandusefulfeaturestotheexceptionsystem.Thefirstautomates the process ofreleasinga resource, suchasafile,when it isno longerneeded.

Itisbasedonanexpandedformofthetrystatementcalledtry-with-resources,andisdescribedinupcomingChapterwhenfilesareintroduced.

Thesecondnewfeatureiscalledmulti-catch,andthethirdissometimesreferredtoasfinalrethrowormorepreciserethrow.Thesetwofeaturesaredescribedhere.

Themulti-catchfeatureallowstwoormoreexceptionstobecaughtbythesamecatchclause.Itisnotuncommonfortwoormoreexceptionhandlerstousethesamecodesequenceeventhoughtheyrespondtodifferentexceptions.

Insteadofhavingtocatcheachexceptiontypeindividually,nowyoucanuseasinglecatchclausetohandlealloftheexceptionswithoutcodeduplication.

Touseamulti-catch, separateeachexception type in thecatch clausewith theORoperator.Eachmulti-catchparameter is implicitly final. (You can explicitly specifyfinal,ifdesired,butitisnotnecessary.)

Because eachmulti-catch parameter is implicitly final, it can’t beassignedanewvalue.

Here is a catch statement that uses the multi-catch feature to catch bothArithmeticExceptionandArrayIndexOutOfBoundsException:

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 isattempted. If you comment out the division statement and remove the commentsymbol from the next line, an ArrayIndexOutOfBoundsException is generated. Bothexceptionsarecaughtbythesinglecatchstatement.

The more precise rethrow feature restricts the type of exceptions that can berethrowntoonlythosecheckedexceptionsthattheassociatedtryblockthrows,thatarenothandledbyaprecedingcatchclause,andthatareasubtypeorsupertypeof

theparameter.

Althoughthiscapabilitymightnotbeneededoften,itisnowavailableforuse.Forthemorepreciserethrowfeaturetobeinforce, thecatchparametermustbeeithereffectively final,whichmeans that itmust not be assigned a newvalue inside thecatchblock,orexplicitlydeclaredfinal.

UsingExceptions

Exception handling provides a powerful mechanism for controlling complexprogramsthathavemanydynamicrun-timecharacteristics.Itisimportanttothinkof try, throw, and catch as clean ways to handle errors and unusual boundaryconditionsinyourprogram’slogic.Unlikesomeotherlanguagesinwhicherrorreturncodesareusedtoindicatefailure, Javausesexceptions.Thus,whenamethodcanfail,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 fornonlocalbranching.Ifyoudoso,itwillonlyconfuseyourcodeandmakeithardtomaintain.

TheoryQuestion:1.Whatisanexception?

2.Howdowedefineatryblock?

3.Howdowedefineacatchblock?

4.Listsomeofthemostcommontypesofexceptionthatmightoccurinjava.GiveExample.

5.Isitessentialtocatchalltypesofexception?

6.Howmanycatchblockscanweusewithonetryblock.

7.Createatryblockthatislikelytogeneratethreetypesofexceptionandthenincorporatenecessarycatchblocktocatchandhandlethemappropriately.

8.Whatisfinallyblock?Whenandhowisitused?Giveasuitableexample.

9.ExplainhowExceptionhandlingmechanismcanbeusedfordebuggingaprogram.

CHAPTER∞12∞

(Multi-ThreadedProgramming)

Introduction-

A thread is a single flow of control within a program. Thread is very muchsimilartoaprocess.Infactthreadisalsocalledalight-weightprocess.

Threadv/sProcess:

Normally different processes occupy different memory space. When the CPUshifts fromoneprocess to another process, the state of the currently runningprocess issavedand the stateof anotherprocess is restored.Nousefulwork isbeingdoneduringstateswitch.ThecontextswitchtimeshouldbeaslessaspossibletomaximizetheCPUutilization.

Threadsarealsolikeindependentprocessesbuttheysharethesamememoryandstate.Theseparatethreadsalsohaveseparatestatebutthestateisverysmallascomparedto process state. The state may contain just program counter and stack pointer. Soswitchingfromonethreadtoanotherthreadtakesverylittletime.Thusthecontextswitchtimeforthreadsisverysmallascomparedtotheprocess.HenceCPUutilizationishighincaseofmultiplethreadsascomparedtotheutilizationincaseofmultipleprocesses.

Multi-Threadedprogram:

Amulti-threadedprogramcontainstwoormorepartsthatcanrunconcurrently.Eachpartofsuchaprogramiscalledathread,andeachthreaddefinesaseparatepathofexecution.Thus,multi-threadingisaspecializedformofmulti-tasking.

Forexample,aprogrammayhavethreethreads:

Onehandlingtheprinting.

Onehandlingtheediting.

OnedownloadingafilefromtheInternet.

AllthesethreadsmightberunningconcurrentlythusmaximizingtheCPUutilization.

Process-basedMulti-tasking:

Mostoftheoperatingsystemsallowustoruntwoormoreprogramsatthesametime. It is referred to as process-bases multi-tasking. For example, we can run a Javaprogramand at the same timewemaybe editing aworddocument.Theprocess-basedmulti-taskingensuresthattherewillbesomeprogramtobeexecutedmostofthetimesoitincreasestheCPUutilization.

Inprocess-basedmulti-tasking,aprogramisthesmallestunitofcodethatcanbedispatchedbythescheduler.

Thread-basedmulti-tasking:

Thread is the smallest unit of execution in a thread-based multi-taskingenvironment.Aprocesscanbedivided intoanumberof threadsexecutingconcurrently.Thisallowsustohandlemorethanonetaskconcurrentlyinasingleprogram.

Forexample,wecanedit aworddocumentandat the same timeprint anotherdocument. Thread-basedmulti-tasking improvesCPUutilization just like process-basedmulti-tasking. But at the same time it effectively speeds up the execution of a singleprogrambyexecutingitsdifferentpartsconcurrentlyinseparatethreads.

Thusprocessbasedmulti-taskingdealswiththe“bigpicture”,andthread-basedmulti-taskinghandlesthedetails.

TheJavaThreadModel:

TheJavarun-timesystemdependsonthreadsformanythings,andall theclasslibrariesaredesignedwithmulti-threadinginmind.Infact,Javausesthreadstoenabletheentireenvironment tobeasynchronous.ThishelpsreduceinefficiencybypreventingthewasteofCPUcycles.

Single-threaded systems use an approach called an event loopwith polling. Inthismodel,asinglethreadofcontrolrunsinaninfiniteloop,pollingasingleeventqueuetodecidewhattodonext.Inasinglethreadedenvironment,whenathreadblocks(thatis,suspends execution) because it is waiting for some resource, the entire program stopsrunning.

ThebenefitofJava’smulti-threadingisthatthemainloop/pollingmechanismis

eliminated.WhenathreadblocksinJavaprogram,onlythesinglethreadthatisblockedpauses,allotherthreadscontinuetorun.

ThreadLifeCycle(ThreadStates):

Threadexistsinseveralstates.Athreadcanberunning.ItcanbereadytorunassoonasitgetsCPUtime.Arunningthreadcanbesuspended,whichtemporarilysuspendsitsactivity.Asuspendedthreadcanthenberesumed,allowingittopickupwhereitleftoff.A threadcanbeblockedwhenwaiting fora resource.Atany time,a threadcanbeterminated, which halts its execution immediately. Once terminated a thread cannot beresumed.

1.NewbornState:

Whenwecreateathreadobject,thethreadisbornandissaidtobeinnewbornstate.Thethreadisnotyetscheduledforrunning.

Atthisstate,wecandoonlyoneofthefollowingthingswithit:

1. Scheduleitforrunningusingstart()method.

2. Killitusingstop()method.

Ifscheduled,itmovestorunnablestate.Ifweattempttouseanyothermethodatthisstate,anexceptionwillbethrown.

2.RunnableState:

Therunnablestatemeansthatthethreadisreadyforexecutionandiswaitingfortheavailabilityoftheprocessor.Thatis,thethreadhasjoinedthequeueofthreadsthatarewaitingforexecution.Ifallthreadsareofequalpriority,thentheyaregiventimeslotsforexecutioninroundrobinfashion.

Thethreadthatrelinquishescontroljoinsthequeueattheendandagainwaitsforits run. However, if we want a thread to relinquish control to another thread of equalprioritybeforeitsturncomes,itcandosobyinvokingtheyield()method.

3.RunningState:

Running means that the processor has given its time to the thread for itsexecution.Arunningthreadmayrelinquishitscontrolinoneofthefollowingsituations:

Itstime-sliceisover.

Itispre-emptedbyahigherprioritythread.

Ityieldsi.e.voluntarilyrelinquishescontrol.

Ithascompleteditsexecution.

Itisstoppedbysomeotherthread.

It has been suspended using suspend() method. A suspended thread can berevivedbyusingtheresume()method.Thisapproachisusefulwhenwewantto

suspendathreadforsometimeduetocertainreason,butdonotwanttokillit.

It has been told towait until some event occurs.This is done using thewait()method.Thethreadcanbescheduledtorunagainusingthenotify()method.

ItisperformingsomeI/Ooperation.

4.BlockedState:

A thread is said to be blocked when it is prevented form entering into therunnable state and subsequently the running state. This happens when the thread issuspended,sleepingorwaitinginordertosatisfycertainrequirements.Ablockedthreadisconsidered“notrunnable”butnotdeadandthereforefullyqualifiedtorunagain.

5.DeadState:

Every thread has a life cycle. A running thread ends its life when it hascompleted executing its run()method. It has a natural death. However, we kill it bysendingthestopmessagetoitatanystatethuscausingaprematuredeath.Athreadcanbekilled as soonas it is born,orwhile it is running,or evenwhen it is in “not runnable”(blockedcondition).

ThreadPriorities:

Javaassignstoeachthreadaprioritythatdetermineshowthatthreadshouldbetreatedwith respect to the others.Threadpriorities are integers that specify the relativepriorityofonethreadtoanother.

Asanabsolutevalue,apriorityismeaningless;ahigherprioritythreaddoesnotrun any faster than a lower-priority thread if it is the only thread running. Instead, athread’spriorityisusedtodecidewhentoswitchfromonerunningthreadtonext.Thisiscalleda context switch.The rules thatdeterminewhena context switch takesplacearesimple:

Athreadcanvoluntarily(onitsown)relinquishcontrol.Thisisdonebyexplicitlyyielding,sleepingorblockingorpendingI/O.In thisscenario,allother threadsare examined, and normally the highest-priority thread that is ready to run isgiventheCPU.

A thread can be pre-empted by a higher-priority thread. In this case, a lowerpriority thread thatdoesnotyield theprocessor issimplypre-emptednomatterwhatitisdoing,byahigherprioritythread.Basically,assoonasahigher-prioritythreadwantstorun,itdoes.Thisiscalledpreemptivemultitasking.

SomeOSsupportnon-preemptiveprioritybasedscheduling.Insuchcaseahighprioritythreadgetschanceonlywhenlowprioritythreadcompletes.

IncaseswheretwothreadswiththesamepriorityarecompetingforCPUcycles,thesituationisabitcomplicated. ForOSsuchaswindows98, threadsofequalprioritymustvoluntarily(ontheirown)yield(giveup)control totheirpeers.If

theydonot,theotherthreadswillnotrun.

Note:- Problems can arise from the differences in the way that O.S.’s context-switchthreadsofequalpriority.

Synchronization:

Becausemulti-threading introduces as asynchronous behavior to our programs,theremustbeawayforustoenforcesynchronizationwhenweneedit.Forexample,ifwewant two threads to communicate and share a complicateddata structure, such as alinkedlist,weneedsomewaytoensurethattheydonotconflictwitheachother.

Thatis,wemustpreventonethreadfromwritingdatawhileanotherthreadisinthemiddleofreadingit.Javausesmonitorforinter-threadsynchronization.Wecanthinkof amonitor as avery small box that canholdonlyone thread.Oncea threadenters amonitorcanbeusedtoprotectasharedassetfrombeingmanipulatedbymorethanonethreadatatime.

Mostmulti-threadedsystemsexposeasobjectsthatourprogrammustexplicitlyacquireandlock.Javaprovidesacleanersolution.

Thereisnoclass“monitor”,instead,eachobjecthasitsownimplicitmonitorthatisautomaticallyenteredwhenoneoftheobject’ssynchronizedmethodiscalled.Onceathread is insideasynchronizedmethod,noother threadcancallanyothersynchronizedmethodonthesameobject.Thisenablesustowriteveryclearandconcisemulti-threadedcode,becausesynchronizationsupportisbuiltintothelanguage.

Messaging:Whenprogrammingwithmostotherlanguages,wemustdependontheO.S.toestablishcommunicationbetweenthreads.

This,ofcourse,addsoverhead.Bycontrast,Javaprovidesaclean,low-costwayfor two or more threads to talk to each other, via calls to predefined methods that allobjectshave.Java’smessagingsystemallowsathreadtoentersynchronizedmethodonanobject,andthenwaitthereuntilsomeotherthreadexplicitlynotifiestocomeout.

TheThreadclassandtheRunnableinterface:

Java’smulti-threadingsystemisbuiltupontheThreadclass,itsmethods,anditscompanioninterface,Runnable.Thisclassbelongstopackagejava.langandhencethereisnoneedofexplicitlyimportingit.

Threadencapsulatesathreadofexecution,sincewecannotdirectlyrefertotheinternalstateofarunningthread,wewilldealwithitthroughitsproxy,theThreadinstancethatspawned it. To create a new thread our program will either extend Thread class orimplement theRunnable interface. TheThread class defines severalmethods that helpmanagethreads:

StringgetName()

Returnsthisthread’sname

intgetPriority()

Returnsthisthread’spriority

booleanisAlive()

Testsifthisthreadisstillrunning

voidjoin()

Waitsforthisthreadtodie(terminate)

voidrun()

If this thread was constructed using a separate Runnable object, then that Runnableobject’srunmethodiscalled;otherwise,thismethoddoesnothingandreturns,ifthreadclassisextendedandrun()methodisoverriddeninsub-classthentheoverriddenrun()methodiscalled.

voidsetName(Stringname)

Changesthenameofthisthreadtobeequaltotheargumentname

staticvoidsleep(longmillis)throwsInterruptedException

Causes the currently executing thread to sleep (temporarily cease execution) for thespecifiednumberofmilliseconds.(1sec=1000ms)

staticvoidsleep(longmillis,intnanos)throwsInterruptedException

Causes the currently executing thread to sleep (cease execution) for the specifiednumberofmillisecondsplusthespecifiednumberofnanoseconds.

voidstart()

Causesthisthreadtobeginexecution,theJavaVirtualMachinecallstherunmethodofthisthread.

staticvoidyield()

Causes the currently executing thread object to temporarily pause and allow otherthreadstoexecute.

staticThreadcurrentThread()

Returnsareferencetothecurrentlyexecutingthreadobject.

Themainthread:

WhenaJavaprogramstartsup,onethreadbeginsrunningimmediately.This isusuallycalledthemainthreadofourprogram,becauseitistheonethatisexecutedwhenourprogrambegins.Themain thread is the threadfromwhichother“child” threadsare

created.

Althoughthemainthreadiscreatedautomaticallywhenourprogramisstarted,itcanbecontrolledthroughaThreadobject.Todoso,wemustobtainareferencetoitbycallingthemethodcurrentThread(),whichispublicstaticmemberofThreadclass.

Thismethodreturnsareferencetothethreadinwhichitiscalled.Oncewehavereferencetothemainmethod,wecancontrolitjustlikeanyotherthread.

Example12.1

The following exampledemonstrates howwe can acquire referenceofmain thread andthenaccessitspropertiesusingmethodsofThreadclass.

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,whichisachecked exception. This would happen if some other thread wanted to interrupt thissleepingone.

Note2:Notice theoutputproducedwhen t (threadreference) isusedasanargument toprintln().Thiswilldisplayinorder:thenameofthethread,itspriority,andthenameofitsgroup.Itspriorityis5,whichisthedefaultvalue,andmainisalsothenameofthegroupofthreadtowhichthisthreadbelongs.Athreadgroupisadatastructurethatcontrolsthesateofacollectionofthreadsasawhole.

CreatingaThread:

In themostgeneral sense,wecreatea threadby instantiatinganobjectof typeThread.Javaidentifiestwowaysinwhichthiscanbeaccomplished:

1. WecanimplementtheRunnableinterface

2. WecanextendstheThreadclass,itself.

ImplementingRunnable:

The easiest way to create a thread is to create a class that implements theRunnable interface. To implement Runnable, a class need only implement a singlemethodcalledrun().

publicvoidrun()

Insiderun()method,wewilldefinethecodethatconstitutesthenewthread.The

run( )cancallothermethods,useotherclassesanddeclarevariables, just like themainthread.

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,wewillinstantiateanobjectoftypeThreadfromwithinthatclassusingoneofthefollowingconstructors:

Thread(RunnablethreadObj)

Thread(RunnablethreadObj,StringthreadName)

HerethreadObjistheobjectwhoserunmethodiscalledandthreadNameisthenameofthenewthread.Afterthenewthreadiscreated,itwillnotstartrunninguntilwecallstart()method.

Thestart()methodputsthethreadinthereadyqueue(runnablestate).Wheneverthethreadgetsscheduleditsexecutionwillstartfromtherun()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:

Thesecondwaytocreatea threadis tocreateanewclassthatextendsThread,and then tocreatean instanceof thatclass.Theextendingclassmustoverride the run()method,which is the entry point for the new thread. Itmust also call start() to beingexecutionofthenewthread.

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 derivedclass.Outofthesemethods,theonlyonethatmustoverriddenisrun().Thatis,ofcoursethesamemethodrequiredwhenweimplementtheRunnableinterface.

ManyJavaprogrammersfeelthatclassesshouldbeextendedonlywhentheyarebeingenhancedormodifiedinsomeway.So,ifwewillnotbeoverridinganyofThread’sothermethods,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.Onewaytoachievethisistocallsleep()withinmain.Thisisrathercrude(rough)way.Twowaysexist todeterminewhethera threadhas finished.First,wecancall isAlive()on the thread.Thismethod isdefinedbyThread,anditsgeneralformis:

finalbooleanisAlive()

The isAlive()method returns true if the thread uponwhich it is called is stillrunning.Itreturnsfalseotherwise.WhileisAlive()isoccasionallyuseful,themethodthatwewillmorecommonlyusetowaitforathreadtofinishiscalledjoin(),shownhere:

finalvoidjoin()throwsInterruptedException

Thismethodwaits until the thread onwhich it is called terminates.Additionalformsofjoin()allowsustospecifyamaximumamountoftimethatwewanttowaitfor

thespecifiedthreadtoterminate.

Thefollowingexamplemakesuseofjoin()toensurethatthemainthreadisthelasttostop.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 decidewhen each threadshouldbe allowed to run.Higher priority threadwill be scheduled first as compared tolowerprioritythread.Ahigherprioritythreadcanalsopreemptalower-priorityone.Forinstance, when a lower-priority thread is running and a higher-priority thread resumesfromsleepingorwaitingonI/O,forexample,itwillpreemptthelower-prioritythread.

Intheory,threadsofequalpriorityshouldgetequalaccesstotheCPU.Butjavais designed to work in a wide range of environments. Some of those environmentimplements multi-tasking fundamentally different than others? For safety, threads that

sharethesamepriorityshouldyieldcontrolonceinawhile.

Thisensuresthatallthreadshaveachancetorununderanon-preemptiveOSInpractice, even in non-preemptive environments, most threads inevitably (certainly)encounter some blocking situation, such as waiting for I/O. When this happens, theblocked thread is suspended and other threads can run. For CPU intensive threads, weshouldmakesurethatityieldscontroloccasionally,sothatotherthreadscanrun.

Tosetathread’spriority,usethesetPriority()method,whichisamemberofThread.Itsgeneralformis:

finalvoidsetPriority(intlevel)

The value of level must be within the range Thread.MIN_PRIORITY andThread.MAX_PRIORITY.Currently, thesevaluesare1and10,respectively.Toreturnathreadtodefaultpriority,specifyThread.NORM_PRIORITY,whichiscurrently5.TheseprioritiesaredefinedasfinalvariableswithinThreadclass.

We canobtain the current priority setting by calling the getPriority()methodofThreadclass,shownhere:

finalvoidgetPriority()

Implementations of Java have radically different behavior when it comes toscheduling. The windows XP/98/NT/2000 versions work more or less as we wouldexpect.However,otherversionsmayworkquitedifferently.Mostof the inconsistenciesarise when we have threads that are relying on preemptive behavior, instead ofcooperativelygivingupCPU time.The safestway toobtainpredictable, cross-platformbehaviorwithJavaistousethreadsthatvoluntarilygiveupcontroloftheCPU.

Thefollowingexampledemonstratestwothreadsatdifferentpriorities,whichdonot run on a preemptive platform in the same way as they run on a non–preemptiveplatform.

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.Butthreadsdidcontext switch, even though neither voluntarily yielded the CPU nor blocked for I/O.Whenthissameprogramisrununderanon-preemptivesystem,differentresultswillbeobtained.

Note:-Variable running is preceded by the keyword volatile to ensure that the value ofrunningisexaminedeachtimethefollowingloopiterates.

while(running)

{

click++;

}

Withouttheuseofvolatile,Javaisfreetooptimizetheloopinsuchawaythatalocalcopyofrunningiscreated.Theuseofvolatilepreventstheoptimization,tellingJavathatrunningmaychangeinwaysnotdirectlyapparentintheimmediatecode.

Synchronization:

Whentwoormorethreadsneedaccesstoasharedresource,theyneedsomewaytoensurethattheresourcewillbeusedbyonlyonethreadatatime.Theprocessbywhichthisisachievediscalledsynchronization.

Keytosynchronizationistheconceptofthemonitor(alsocalledasemaphone).Amonitorisanobjectthatisusedasamutuallyexclusivelock.Onlyonethreadcanownamonitoratagiventime.

Whena threadacquiresa lock, it is said tohaveentered themonitor.Allotherthreadsattemptingtoenterthelockedmonitorwillbesuspendeduntilthefirstthreadexitsthemonitor.Theseotherthreadsaresaidtobewaitingforthemonitor.Athreadthatownsamonitorcan reenter thesamemonitor if it sodesires.wecansynchronizeourcode ineitheroftwoways:

(i)Usingsynchronizedmethods

(ii)Usingsynchronizedstatements

UsingSynchronizedMethod:

Synchronization is easy in Java, because all objects have their own implicitmonitor associatedwith them.To enter an object’smonitor, just call amethod that hasbeenmodifiedwith the synchronized keyword.While a thread is inside a synchronizedmethod,allotherthreadsthattrytocallit(oranyothersynchronizedmethod)onthesameinstancehavetowait().Toexitthemonitorandrelinquishcontroloftheobjecttothenextwaitingthread,theownerofthemonitorsimplyreturnsfromthesynchronizedmethod.

Example12.8

Followingprogramillustratesthatoutputgeneratedbythreethreadsgetsmixed-upastheyarerunningconcurrently.

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()methodallowsexecutiontoswitchtoanotherthread.Thisresultsinthemixed-upoutputofthethreemessagestrings.Inthisprogram,nothingexiststostopallthreethreadsfromcallingthesamemethod,onthesameobject,atthesametime.

Thisisknownasaracecondition,becausethesethreethreadsareracingwitheachotherto complete the method. This example uses sleep() to make the effects repeatable andobvious.Inmostsituations,araceconditionismoresubtleandlesspredictable,becausewecannotbesurewhen thecontextswitchwilloccur.Thiscancauseaprogramto runrightonetimeandwrongthenexttime.

To do this, we simply need to precede method display()’s definition with thekeyword synchronized. This prevents either threads from entering the display() whileanotherthreadisusingit.

Example12.9

The problem of mixed-up is solved simply by declaring the method call() as asynchronizedmethod.

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,nootherthreadcanenteranyothersynchronizedmethodonthesameinstance.However,non-synchronizedmethodsonthatinstancewillcontinuetobecallable.

UsingSynchronizedStatement:

Whilecreatingsynchronizedmethodswithinclassesthatwecreateisaneasyandeffectivemeansofachievingsynchronization,itwillnotworkinallcases.Tounderstandwhy,considerthefollowing.Imaginethatwewanttosynchronizeaccesstoobjectsofaclass that was not designed for multi-threaded access. That is, the class does not usesynchronizedmethods.Further,thisclasswasnotcreatedbywe,butbyathirdpart;andwedonothaveaccesstothesourcecode.Thus,wecannotaddmodifiersynchronizedtothe appropriatemethodswithin the class.How can access to an object of this class bysynchronized?

The solution is to put calls to the methods defined by this class inside asynchronizedblock.Thegeneralformofthesynchronizedstatementis:

synchronized(object)

{

//statementstobesynchronized

}

Here, object is a reference to the object being synchronized. A synchronizedblock ensures that a call to amethod that is amember of object occurs only often thecurrentthreadhassuccessfullyenteredobject’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

Threadscancallthesamesynchronizedinstancemethodondifferentobjectsofsameclassconcurrentlyaseachobjecthasadifferentlock.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 callingdisplay()method on different objects. The reason is thatmethod display() is static andhencethelockisobtainedfortheclassAasawholeandnotontheindividualobjects.

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.Pollingisusuallyimplementedbyaloopthatisusedtochecksomeconditionrepeatedly.Oncetheconditionistrue,appropriateactionistaken.

ThiswastestheCPUcycles.Forexample,considertheclassicqueuingproblem,where one thread is producing some data and another is consuming it. To make theproblemmore interacting, suppose that theproducerhas towait until the consumerhasfinishedbefore it generatesmoredata. In a polling system, the consumerwouldwastemanyCPUcycleswhile itwaited for theproducer toproduce. Once theproducerwasfinished, it would start polling, wastingmore CPU cycles waiting for the consumer tofinish,andsoon.

To avoid polling, Java includes an elegant (smart) inter-process communicationmechanism via the wait(), notify(), and notifyAll() methods. These methods areimplementedasfinalmethodsinObjectclass,soallclasseshavethem.Allthreemethodscanbecalledonlyfromwithinasynchronizedcontext.Therearecertainrulesforusingthesemethods.

Wait() tells the calling thread to give up themonitor and go to sleep until some otherthreadentersthesamemonitorandcallsnotify().

Notify()wakesuponethread(normallyfirstthread)thatcalledwaitonthesameobject.

notifyAll()wakesupallthethreadsthatcalledwait()onthesameobject.Normallythehighestprioritythreadwillrunfirst.

ThesemethodsaredeclaredwithinObjectclass,asshownhere:

finalvoidwait()throwsInterruptedException

finalvoidnotify()

finalvoidnotifyAll()

Example12.13

The following sample program incorrectly implements a simple form of theproducer/consumerproblem. Itconsists fourclasses:Q, thequeue thatweare trying tosynchronize;Producer,thethreadedobjectthatisproducingqueueentries;Consumer,thethreadedobjectthatisconsuminggqueueentries;andPC,thetinyclassthatcreatesthesingQ,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,nothingstopstheproducerfromoverrunningtheconsumer,norwillanythingstoptheconsumerfromconsumingthe

samequeuevaluetwice.Thuswemaygeterroneousoutputasshownbelow:

Output:PressControl-CtostopPut: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

Theproperway towrite thisprograminJava is tousewait()and notify() tosignal inbothdirections,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 ofsynchronizedobjects.For example, supposeone threadenters themonitoronobject Xand another thread enters themonitor on object Y. If the thread in X tries to call anysynchronizedmethodonY,itwillblockasexpected.However,ifthethreadinY,inturntriestocallanysynchronizedmethodonX,thethreadwaitsforever,becausetoaccessX,it would have to release its own lock on Y so that the first thread could complete.Deadlockisadifficulterrortodebugfortworeasongs:

(i)Ingeneral,itoccursonlyrarelywhenthetwothreadstime-sliceinjusttherightway.

(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()aredefinedbyThreadclasstopauseandrestarttheexecutionofathread.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. Itssignatureisshownhere:

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,wehavebeenusingvisibilitymodifierspublic,private,protected,packagepublicetc. tospecify thevisibilityofclassmembers.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:

Byspecifyingmemberaccessibilitymodifiersaclasscancontrolwhatinformationisaccessible to clients (i.e. other classes). These modifiers help a class to define acontractsothatclientsknowexactlywhatservicesareofferedbytheclass.

Accessibility/visibilityofmemberscanbeoneothefollowing:

public

protected

default(alsocalledpackageaccessibility)

private

Note:-Memberaccessibilitymodifiersonlyhasmeaningiftheclass(oroneitssubclasses)isaccessibletotheclient.Alsonotethatoneaccessibilitymodifierscanbespecifiedforamember.

Thediscussionappliestobothinstanceandstaticmembersofclasses.

3.Memberaccessibility/visibilitymodifiersforinterfaces:

Theonlymemberaccessibility/visibilitymodifierthatcanbeusedwithdatamembersandmethodsofaninterfaceispublic.

Thepublicisalsotheimplicitaccessibility/visibilitymodifierforinterfacemembersi.e.themembersarealwaysimplicitlyassumedtobepublicevenifwedonotusethemodifierpublic.

4.Othermodifiersfortop-levelclasses:

Besidevisibilitymodifiers,wecanalsousefollowingmodifiersbeforeatop-class:

(a)abstract

A class can be specified with the keyword abstract to indicate that it cannot beinstantiated. A class containing abstract method must be declared as abstractotherwise it won’t compile. A class not containing abstract method can also bedeclaredabstract.Suchaclasscanserveasabaseclassforanumberofsub-classes.

(b)final

Aclasscanbedeclared final to indicate that it cannotbeextended.The final classmarks the lowerboundaryof its implementation inheritancehierarchy.Onlyaclasswhosedefinitioniscompletecanbedeclaredfinal.Aclasscannotbebothfinalandabstractatthesametime.

Herearefewimportantcharacteristicsofthefinalclass.

Allthemethodsofafinalclassarealsofinali.e. theyhavetheconcreteimplementationandcannotbeover-ridden.

Some type checks become fasterwith final classes. In fact,many type checks

become compile time checks and errors can be caught earlier. If the compilerencounters a reference to a final class, it knows that the object referred to isexactlyofthattype.The compiler is able to perform certain code optimizations for finalmethods,becausecertainassumptionscanbemadeaboutsuchmembers.Whenanon-finalmethodisinvoked,theruntimesystemdeterminestheactualclassoftheobject,bindsthemethodinvocationtothecorrectimplementationofthemethodforthattype,andtheninvokestheimplementation.In case of a finalmethodwe are sure that type sub-class can not override themethodsothebindingisdoneatthecompiletimeasincaseofprivateandstaticmethods,whichwoulddefinitelyimprovetheperformance.IncaseofafinalmethodthecompilermayreplaceaninvocationwiththeactualbodyofthemethodlikeMacro.Thismechanismisknownas‘inlining’.InC++,wehave theoptionofdeclaringa functionas inline (although finaldecision istakenbythecompiler)butinJava,thecompilertakesthedecision.

5.Othermodifiersfortop-levelinterfaces:

(a)abstract

This is the only modifier other than visibility modifiers, which can be used withinterface.

Interfacesjustspecifythemethodprototypesandnotanyimplementation: theyare,bytheirnature,implicitlyabstract.(i.e.theycannotbeinstantiated).Wecandeclareaninterfaceasabstractbutitisredundantasinterfaceisalwaysabstract.

6.Othermodifiersforinterfacemembers:

Othermodifiersfordatamembers:

Besidevisibilitymodifierpublic,wecanalsousemodifiersstaticandfinal.Althoughwe can use these modifiers but it is redundant as all data members are implicitlypublic,staticandfinal.

Othermodifiersformethods:

Besidevisibilitymodifierpublic,wecanalsousemodifierabstract.Althoughwecanuse abstract modifier but it is redundant as all methods are implicitly public, andabstract.

7.Othermodifiersforclassmembers:-

Certain characteristics of fields and/or methods can be specified in theirdeclarationsbythefollowingkeywords:

1. static

2. final

3. abstract

4. synchronized

5. native

6. transient

7. volatile

A.staticmodifier:Thestaticmembersbelongtotheclassinwhichtheyaredeclared,andarenotpartofany instance of the class. Depending on the accessibility modifiers of the staticmembersinaclass,clientcanaccessthesebyusingtheclassnameorthroughobjectreferencesoftheclass.

staticvariables(alsocalledclassvariables):-

Thesevariablesonlyexistintheclasstheyaredefinedin.Whentheclassisloaded,static variables are initialized to their default values, if no explicity initializationexpressioninspecified.

Thestaticmembervariablesareoftenusedwhen trackingglobal informationabouttheinstances.

staticmethods:

Thesearealsoknownasclassmethods.Astaticmethodinaclasscandirectlyaccessotherstaticmembersintheclass.Itcannotaccessinstance(i.e.non-static)membersoftheclass,asthereisnonotionofanobjectassociatedwithastaticmethod.

However,notethatastaticmethodinaclasscanalwaysuseareferenceoftheclass’stypetoaccessitsmembersregardlessofwhetherthesemembersarestaticornot.A typical staticmethodmight perform some task on behalf of thewhole classand/orobjectsoftheclass.

Aninstanceinasubclasscannotoverrideastaticmethodinthesuperclass.Thecompilerwillflagthiswithanerror(meansastaticmethodinsuperclasscannotbeoverriddenbynonstaticmethodsinsubclass).Astaticmethodisclassspecificandnotpartofanyobject,whileoverriding,methodsareinvokedonthebehalfofobjectsofthesubclass.However,astaticmethodinasubclasscanhideastaticmethodinthesuperclass.

Methodsdeclaredasstatichaveseveralrestrictions:

Theycanonlycallotherstaticmethods.

Thecanonlyaccessstaticdatamembers.

Theycannotrefertothisorsuperinanyway

staticinitializationblock:

Ajavaclasscanhaveoneormorestaticinitializationblock.Thesyntaxofthestatic

initializationblockisasfollows:

static

{

code

}

A static initialization block can be though of as a staticmethod,which is invokedimplicitly/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, Propertiesetc.

B.finalmodifier:Themodifierfinalcanbeusedwith

Localvariables

Instancevariables/datamembers

Staticvariables/datamembers

Instancemethods

finalvariables:

Afinalvariableisnormallyinitializedatthetimeofdeclarationanditsvaluecannotbe modified after assigning once. Here are few important points related to finalvariables:

Afinalvariableisaconstant,despitebeingcalledavariable.Itsvaluecannotbechanged once it has been initialized. This applies to instance, static and localvariables,includingparametersthataredeclaredfinal.

Thefinalistheonlymodifierapplicabletolocalvariablesorformalparameters.

Afinalvariableofaprimitivedatatypecannotchangeitsvalueonceithasbeeninitialized.

Afinalvariableofareferencetypecannotchangeitsreferencevalueonceithasbeeninitialized,butthestatoftheobjectitdenotescanstillbechanged.

Normallyafinalvariableisinitializedatthetimeofdeclarationbutitisnotmust.Sucha finalvariable is alsocalledblank finalvariable, andmustbe initialized

oncebeforeitisbeingused.

The final static variables are commonly used to define named constants, forexampleInteger.MAX_VALUE,whichisthemaximumintvalue.

Localfinalvariables:-

Example13.1

The following example illustrates that local final variable can be left blank asdiscussedabovebutmustbeinitializedbeforefirstuse.Thevariablexisinitializedjustbeforedisplayingitsvalueonthemonitor.

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.Soifwedonotinitializeat the time of declaration then the other places at which final variables can beinitializedare:

Constructor

Initializationblock

Example13.3

The following program will not compile, as final variable is not initialized. Theconceptof initializationbydefaultvalue isnotapplicable to finalvariablesas theycannotbemodifiedafterinitialization.

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 afterobtainingareference.

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 beinitializedintheconstructor.

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

Thefollowingprogramillustratesthatablankfinalvariablecanbeinitializedwithadynamicvalueandcanbereferredwiththiskeyword.Sodifferentobjectsofthesameclasscanhavedifferentvaluesofthefinalvariable.

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

{

code

}

A initialization block can be thought if as a constructor, which is invokedimplicitly/automaticallyassoonastheobjectiscreate.Infactifaclasscontainsinitializationblocksthemtheyareexecutedintheorderofdefinitionfromtoptobottombeforeanyconstructor.

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 codewhich is common to all constructors. Thiswill increase thecodereusabilityandreducemaintenance.

Astaticfinalvariables:

A static final variables can be left blank, but must be initialized before class isavailabletotheprogram.Soifwedonotinitializeatthetimeofdeclarationthentheonlyplaceatwhichstaticfinalvariablecanbeinitializedis:

staticInitializationblock

Example13.8

Thefollowingexampleillustratesthattheblankstaticfinalvariablecanbeinitializedinthestaticblock.

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)andcannotbeoverridden in any subclass. Subclasses are thus restricted in changing thebehaviorofthemethod.

The compiler is able to perform certain code optimizations for finalmethods,because certain assumptions can be made about suchmembers.When a non-staticmethodisinvoked,theruntimesystemdeterminestheactualclassoftheobject,bindsthemethodinvocationtothecorrectimplementationofthemethodforthattype,andtheninvokestheimplementation.

Incaseofafinalmethodwearesurethatsub-classcannotoverridethemethodso the binding is done at the compile time as in case of private and staticmethods,whichwoulddefinitelyimprovestheperformance.

IncaseofafinalmethodthecompilermayreplaceaninvocationwiththeactualbodyofthemethodlikeMacro.Thismechanismisknownas‘inlining’.InC++,wehave theoptionofdeclaringa functionas inline (although finaldecision istakenbythecompiler)butinJava,thecompilertakesthedecision.

C.abstractmodifier:-

Theabstractmodifiercanbeusedonlywith instancemethods.Anabstractmethoddoesnothavean implementation, that is,nomethodbody isdefinedforanabstactmethod,onlythemethodprototypeisprovidedintheclassdefinition.

Itsclassisalsoabstract(i.e.,incomplete)andmustbeexplicitlydeclaredasabstract.Subclasses of an abstract class must then provide the method implementation;otherwise,theyarealsoabstract.

Herearesomeimportantpointsrelatedtoabstractmethods:

An abstractmethod cannot be declared private.This is obvious aswe can notoverrideanprivatemethod,whileincaseofanabstractmethodbodyisalwaysprovidedinthesub-classbyover-ridingtheabstractmethod.Onlyaninstancemethodcanbedeclaredabstractsincestaticmethodscannotbeoverridden, declaring an abstract staticmethodwouldmake no sense andwillresultincompilationerror.Afinalmethodcannotbeabstractandvice-versa.Thekeywordabstractcannotbecombinedwithanynon-accessibilitymodifiersformethods.Methods specified in an interface are implicitly abstract, as only the methodprototypesaredefinedinaninterface.

D.synchronizedmodifier:-

Thesynchronizedkeywordcanbeusedwithmethodsandcodeblocks.Severalthreadcanexecutesimultaneouslyinaprogram.Theymighttrytoexecuteseveralmethodson thesameobjectsimultaneously inaprogram.Theymight try toexecuteseveralmethodsonthesameobjectsimultaneously.Ifitisdesiredthatonlyonethreadatatimecanexecuteamethodintheobject,themethodscanbedeclaredsynchronized.Theirexecutionisthemutuallyexclusiveamongallthreads.

Atanygiven time, atmostone threadcanbeexecutinga synchronizedmethodonanygiven time, atmostone threadcanbe executinga synchronizedmethodonanobject.Thisdiscussionalsoappliestostaticsynchronizedmethodsofaclass.

Note-Thesynchronizedmodifierdoesnotapplytoclassesormembervariables.

E.nativemodifier:-

The native modifier can refer only to methods. Like the abstract keyword, nativeindicates that thebodyofamethod is tobefoundelsewhere.ThebodyofanativemethodisentirelyoutsidetheJVM,inalibrary.Nativecodeiswritteninanon-javalanguage, typicallyCorC++,andcompiled fora single targetmachine type.ThusJava’s platform independence is violated. People who port Java to new platformsimplement extensive native code to support GUI components, networkcommunication,andabroadrangeofotherplatform-specificfunctionality.However,itisrarefortheapplicationandappletprogrammerstoneedtowritenativecode.

F.transientmodifier:-

Objects can be stored using serialization. Serialization transforms objects into anoutputformatthatisconduciveforstoringobjects.Objectscanlaterberetrievedinthesamestateaswhen theywereserialized,meaning thatall fields included in theserializationwillhavethesamevaluesasatthetimeofserialization.Suchobjectsassaidtobepersistent.

Afieldcanbespecifiedastransientintheclassdeclaration,indicatingthatitsvalueshouldnotbesavedwhenobjectsoftheclassarewrittentopersistentstorage.classExperimentimplementsSerializable-

{

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 serializedobject.

G.volatilemodifier

During execution, compiled code might cache the value of fields for efficiencyreasons.Sincemultiplethreadscanaccessthesamefield,itisvitalthatcachingisnotallowedtocauseinconsistencieswhenreadingandwritingthevalueinthefield.The

volatilemodifier can be used to inform the compiler that it should not attempt toperformoptimizationonthefield,whichcouldcauseunpredictableresultswhenthefieldisaccessedbymultiplethreads.

CHAPTER∞14∞

(WrapperClass)

Introduction-

Theprimitivedatatypesinjavaarenotobjects.Ifwewanttousethesedatatypesasobjects,thenwewillhavetousewrapperclassesforeachoftheseprimitivedatatypesprovidedinjava.langpackage.

Therearemanybuilt-inclasses,whichcannothandleprimitivedatatypesastheydeal onlywith objects.One such class isVector,which is used to store a collection ofobjects.Wecannotuse theVectorclass todirectlystore thecollectionofelementsofaprimitivedata typed.Butwecandosobystoring theobjectsofwrapperclasses,whichcorrespondtotheprimitivedatatypes.

TheJavahaswrapperclasscorresponding toeachof theprimitivedata typeasshowninthefollowingtable:

PrimitiveDataType WrapperClass

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Numberclass:

TheabstractclassNumberdefinessuper-classthatisimplementedbytheclassesthat wrap the numeric type byte, short, int, long, float, and double. Number class hasabstract methods that return the value of the object in each of the different numberformats.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 wheninvokingmethodsofclassNumber.

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 ofWrappers Classes andConvertingNumericObjectsbacktoPrimitiveNumbers:-

Example14.2

Thefollowingexampledemonstrateshowprimitivescanbewrappedinobjectsandhowtheycanbeconvertedbacktoprimitives.

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 thecorrespondingWrapperClass

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

105

303

100

454444444444

3.444

3.44444

ConvertingNumericObjectstoStringsusingtoString()methodofthecorrespondingWrapperClass:-

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()methodofcorrespondingwrapperclass:

103

203

32000

4544444444444

3.1444

4.1444

Converting String Objects(Numeric Strings) to Numberic Objects using the staticvalueOf()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 thevalueOf()methods throw“NumberFormatException” if the stringdoesnotcontainaparsablenumber.

ConvertingstringObjects(NumericStrings)toNumericObjectsusingConstructorofthecorrespondingWrapperClass

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 notcontainaparsablenumber.

Converting String Objects (Numeric Strings) to Primitive Numbers using parsingmethodsofthecorrespondingWrapperClass

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 notcontainaparsablenumber.

ConstantsdefinedinclassesDoubleandFloat:

MAX_VALUE

MIN_VALUE

NaN

NEGATIVE_INFINITY

POSITIVE_INFINITY

TYPE(Theclassinstancerepresentingtheprimitivetypedouble/float)

SIZE(Thenumberofbitsusedtorepresentadoublevalue).SinceJ2SDK1.5.

OtherMethodsinFloatClass:

1.staticintcompare(floatf1,floatf2)2.Comparesthetwospecifiedfloatvalues3.intcompareTo(FloatanotherFloat)4.ComparestwoFloatobjectsnumerically.5.booleanequals(Objectobj)6.Comparesthisobjectagainstthespecifiedobject7.inthashCode()8.Returnsahashcodeforthisfloatobject.9.booleanisInfinite()10. Returns true if this Float value is infinitely large in magnitude, falseotherwise.11. staticbooleanisInfinite(floatv)12. Returnstrueifthespecifiednumberisinfinitelylargeinmagnitude,falseotherwise.13.booleanisNaN()14. Returns true if this float value is a Not-a-Number (NaN) value, falseotherwise.15.staticBooleanisNaN(floatv)16. ReturnstrueifthespecifiednumberisaNot-a-Number(NaN)value,falseotherwise.

OthermethodsindoubleClass:

MethodsinDoubleclassarealmostsameasmethodsoffloatClass,withuseofdoubleanddoublewordsinsteadoffloatandFloatwordsintheprevioustable.

ConstantsdefinedinclassesByte,Short,IntegerandLong:

MIN_VALUE

MAX_VALUE

TYPE(Theclassinstancerepresentingtheprimitivetypebyte/short/int/long)

SIZE(Thenumberofbitsusedtorepresentabyte/short/int/longvalueintwo’scomplementbinaryform.)SinceJ2SDK1.5.

OtherMethodsinByteClass:

intcomparesTo(ByteanotherByte)

ComparestwoByteobjectsnumerically.

staticBytedecode(Stringnm)

Returns a Byte object that contains the value specified by the string nm. Acceptsdecimal,hexadecimal,andoctalnumbersgivenbythefollowinggrammer:

DecodableString:

[-]DecimalNumerical

[-]0xHexDigits

[-]0XHexDigits

[-]#HexDigits

[-]0OctalDigits

booleanequals(Objectobj)

Comparesthisobjecttothespecifiedobject.

inthashCode()

ReturnsahashcodeforthisByte.

OtherMethodsinShortClass:

MethodsinShortclassaresameasmethodsofByteclass,withtheuseofshortandShortwordsinsteadofbyteandBytewordsintheabovetable.

OtherMethodsinIntegerClass:

Some methods are same as Byte or Short class’s methods. Some other methods aredescribedbelow:

staticStringtoBinaryString(inti)

Returns a string representation of the integer argument as an unsignedintegerinbase2.

staticStringtoHexString(inti)

Returns a string representation of the integer argument as an unsignedintegerinbase16.

staticStringtoOctalString(inti)

Returns a string representation of the integer argument as an unsignedintegerinbase8.

OtherMethodsinLongClass:

MethodsinLongclassarealmostsameasmethodsofIntegerClass.

CharacterClass:

Thecharacterclasswrapsavalueoftheprimitivetypecharinanobject.

Constructor:

Character(charvalue)

ConstructsanewlyallocatedCharacterobjectthatrepresentsthespecifiedcharvalue.

Example:CharacterchObj=newCharacter(‘A’);

Methods:

SomeofthemethodsofCharacterclassaredescribedinthefollowingtable:

charcharValue()

ReturnsthevalueofthisCharacterobject.

staticbooleanisDefined(charch)

DeterminesifthespecifiedcharacterinUnicode.

staticbooleanisDigit(charch)

Determinesifthespecifiedcharacterisadigit.

staticbooleanisJavaIdentifierPart(charch)

Determinesif thespecifiedcharactermaybepartofaJavaidentifierasotherthanthefirstcharacter.

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 anobject.

Constructors:

Boolean(Booleanvalue)

AllocatesaBooleanobjectrepresentingthevalueargument.

Boolean(Strings)

AllocatesaBooleanobjectrepresentingthevaluetrueifthestringargumentisnotnullandisequal,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 thatrepresentsthesamebooleanvalueasthisobject.

staticBooleangetBoolean(Stringname)

Returns true if and only if the systemproperty namedby the argument exists and isequaltothestring“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.Astreamisanabstractionthateitherproducesorconsumesinformation.AstreamislinkedtoaphysicaldevicebytheJavaI/Osystem.

All streams behave in the samemanner, even if the actual physical devices towhichtheyarelinkeddiffer.Thus,thesameI/Oclassesandmethodscanbeappliedtoanytypeofdevice.

Thismeans an input streamcan abstractmanydifferent kinds of input: fromadisk file, a keyboard or a network socket. Likewise an output streammay refer to theconsole,adiskfile,oranetworkconnection.

Streamsareacleanway todealwith input/outputwithouthavingeverypartofourcodeunderstandthedifferencebetweenakeyboardandanetwork,forexample.Javaimplementsstreamswithinclasshierarchiesdefinedinthejava.iopackage.

(RelationshipofJavaProgramwithI/ODevices)

Theconceptof sendingdata fromonestream toanother (likeonepipe feedingintoanotherpipe)hasmadestreams inJavaapowerful tool for fileprocessing.Wecanbuildacomplexfileprocessingsequenceusingaseriesofsimplestreamoperations.

This feature canbeused to filterdata along thepipelineof streams so thatweobtaindata inadesired format.Forexample,wecanuseone stream toget rawdata inbinaryformatandthenuseanotherstreaminseriestoconvertitintointegers.

InputandOutputStreams:-

Java streams are classified into two basic types: normally input streams andoutputstreams.Aninputstreamextracts(i.e.reads)datafromthesourceandsendsit totheprogram.

The program connects and opens an input stream on the data source and thenreadsthedataserially.Similarly,theprogramconnectsandopensanoutputstreamtothedestinationplaceofdataandwritesdataoutserially.Inboththecases,theprogramdoesnotknowthedetailsofendpoints(i.e.sourceanddestination).

ByteStreamsandCharacterStreams-

Java2definestwotypesofstreams:ByteandCharacter.Bytestreamsprovideaconvenient means for handling input and output of bytes. Byte streams are used, forexample, when reading or writing binary data. Character streams provide a convenientmeansforhandlinginputandoutputofcharacter.

They useUnicode and therefore, can be internationalized.Also in some cases,characterstreamsaremoreefficientthanbytestreams.TheoriginalversionofJava(Java1.0)didnotincludecharacterstreamsandthis,allI/Owasbyteoriented.

CharacterstreamswereaddedbyJava1.1andcertainbyteorientedclassesandmethodsweredeprecated.

Note:Atthelowestlevel,allI/Oisstillbyteoriented.Thecharacter-basedstreamssimplyprovideaconvenientandefficientmeansforhandlingcharacters.

Thesetwogroupsmaybefurtherclassifiedbaseontheirpurposes.ByteStreamandCharacterStreamclassescontainspecializedclasses todealwith inputandoutputoperationsindependentlyonvarioustypesofdevices.

Wecanalsocross-group thestreamsbasedon the typeofsourceordestinationtheyreadfromorwriteto.Thesource(ordestinationmaybememory,afileorapipe.

(ClassificationofJavaStreamClasses)

OverviewofByteStreamClasses:-

Bytestreamclassesaredefinedbyusingtwoclasshierarchies.Atthetoparetwoabstractclasses:

(1)InputStreamand(2)OutputStream

Eachof these abstract classeshave several concrete subclasses, thathandle thedifferences between various devices, such as disk files, network connections and evenmemorybuffers.

InputStreamclasses

InputStreamclassesthatareusedtoread8-bitbytesincludeasuperclassknownasInputStreamandanumberofsub-classesforsupportingvariousinputrelatedfunctions.

HierarchyofInputStreamClasses.

HierarchyofInputStreamClasses.

TheInputStreamclass:-

The super class InputStream is an abstract class, which defines methods forperforminginputfunctionssuchas:

Readingbytes.Closingstream.Markingpositionsinstreams.Skippingaheadinastream.Findingthenumberofbytesinastream.

MethodsofInputStreamclass:

intavailable()

Givesthenumberofbytesavailableintheinput(mustbeoverriddenbythesubclasses).

TheavailablemethodforclassInputStreamalwaysreturns0.

voidclose()

Closesthis inputstreamandreleasesanysystemresourcesassociatedwiththestream.TheclosemethodofInputStreamdoesnothing.

voidmark(intreadlimit)

Marksthecurrentpositioninthisinputstream.ThemarkmethodofInputStreamdoesnothing.

booleanmarkSupported()

Tests if this input stream supports the mark and reset methods. The markSupportedmethodofInputStreamreturnfalse.

abstractintread()

Reads the next byte of data from the input stream. A subclass must provide animplementationofthismethod.

intread(byte[]b)

Readssomenumberofbytesfromtheinputstreamandstoresthemintothebufferarrayb.Thenumberofbytesactuallyreadisreturnedasaninteger.

intread(byte[]b,intoffset,intlen)

Readssomenumberofbytesfromtheinputstreamandstoresthemintothebufferarraybstartingfrompositionspecifiedbytheparameteroff.Thenuberofbytesactuallyreadisreturnedasaninteger.

voidreset()

Repositionsthisstreamtothepositionatthepositionatthetimethemarkmethodwas

last called on this input stream. The reset method of InputStream does nothing andalwaysthrowsIOException.

longskip(longn)

Skips over and discards upto n bytes of data from this input stream and returns thenumberofbytesactuallyskipped.

TheDataInputInterface:

TheDataInputisaninterface,whichdefinesmethodsforreadingprimitivesfromanInputStream.

MethodsofDataInputInterface:

booleanreadBoolean()

Readsoneinputbyteandreturnstrueifthatbyteisnon-zeroandfalseifthatbyteiszero.

bytereadByte()

Readsandreturnsonebyteinput.

charreadChar()

Readsaninputcharacterandreturnsitsvalue.

doublereadDouble()

Readseightinputbytesandreturnsadoublevalue.

floatreadfloat()

Readsfourinputbytesandreturnsadoublevalue.

voidreadFully(byte[]b)

Readssomebytes froman inputstreamandstores theminabufferarrayb.ThismethodthrowsEOFExceptionifthisstreamreachestheendbeforereadingallthebytes.

voidreadFully(byte[]b,intoff,intlen)

Readslenbytesfromaninputstreamandstorestheminabufferarraybstartingat

thepositionspecifiedbytheoff.ThismethodthrowsEOFExceptionifthisstreamreachestheendbeforereadingallthebytes.

intreadInt()

Readsfourinputbytesandreturnsanintvalue.

StringreadLine()

Readsthenextlinefromtheinputstream.

longreadLong()

Readseightinputbytesandreturnsalongvalue.

shortreadShort()

Readstwoinputbytesandreturnsashortvalue

StrigreadUTF()

ReadsinastringthathasbeenencodedusingamodifiedUTF-8format.

intskipBytes(intn)

Makesanattempttoskipovernbytesofdatafromtheinputstream,discardingtheskippedbytes.Theactualnumberofbytesskippedisreturned.

SummaryofInputStreamClasses:-

AFilterInputStreamcontainssomeotherinputstream,whichitusesasitsbasicsource of data possibly transforming the data along the way providing additionalfunctionality.

The class FilterInputStream itself simply overrides allmethods of InputStreamwith versions that pass all requests to the contained input stream. Sub-classes ofFilterInputStream may further override some of these methods and may also provideadditionalmethodsandfields.

Note that the classDataInputStreamextendsFilterInputStreamand implements

the interface DataInput. Therefore, the DataInputStream extends FilterInputStream andimplements the mewthods described in DataInput in addition to using methods ofInputStreamclass.

InputStreamclassessummary:

InputStream Thisabstractclassisthesuperclassofallclassesrepresentinganinputstreamofbytes.

BufferedInputStream AbufferedInputStreamaddsfunctionalitytoanotherinputstream-namely,theabilitytobuffertheinputandtosupportthemarkandresetmethod.

ByteArrayInputStream A ByteArrayInputStream contains an internal buffer that contain bytes thatmaybereadfromthestream.

DataInputStream ADataInputStreamletsanapplicationreadtheprimitiveJavadatatypesfromanunderlyinginputstreamfromamachine-independentway.

FileInputStream AFileInputStreamcontainsinputbytesfromafileinafilesystem.

FilterInputStream A FilterInputStream contains some other input stream, which it uses as itsbasicsourceofdata,possiblytransferringthedataalongthewayorprovidingadditionalfunctionality.

PipedInputStream APipedInputStreamshouldbeconnectedtoapipedoutputstream,thepipedinput stream then provides whatever data bytes are written to piped outputstream.

PushbackInputStream APushbackInputStreamaddsfunctionalitytoanotherinputstream,namelytheabilityto“pushback”or“unread”onebyte.

SequenceInputStream ASequenceInputStreamrepresentsthelogicalconcentrationofanotherstream.

ObjectInputStream AnObjectInputStreamdeserializsprimitivedataandobjectspreviouslywrittenusinganObjectOutputStream.

OutputStreamclasses-

OutputstreamclassesarederivedfromthebaseclassOutputStream,whichisanabstract class and have a number of sub-classes for supporting various output relatedfunctions.

TheOutputStreamclass:-

The super classOutputStream is an abstract class,which definesmethods forperformingoutputfunctionssuchas:

WritingbytesClosingstreamsFlushingstreams

(HierarchyofOutputStreamClasses)

Oops!!Let’sseefollowinggoodqualitypicture-

MethodsofOutputStreamClass:-

voidclose()

Closesthisoutputstreamandreleasesanystreamresourcesassociatedwiththisstream.

voidflush()

Flushesthisoutputstreamandforcesanybufferedoutputbytestobewrittenout.

voidwrite(byte[]b)

Writesb.lengthbytesfromthespecifiedbytearraytoitsoutputstream.

voidwrite(byte[]b,intoff,intlen)

Writeslenbytesfromthespecifiedbytearraystartingatoffsetoff toitsoutputstream.

abstractvoidwrite(intb)

Writesthespecifiedbytetoitsoutputstream.

TheDataOutputInterface:-

TheDataOutputisaninterface,whichdefinesmethodsforwritingprimitivestoanOutputStream.

MethodsofDataOutputInterface:

voidwriteBoolean(booleanv)

Writesabooleanvaluetoitsoutputstream.

voidwriteByte(intv)

Writestotheoutputstreamtheeightlow-orderbitsoftheargumentv.

voidwriteBytes(strings)

Writesthestringtotheoutputstream.Foreverycharacterinthestrings,takeninorder,onebyteiswrittentotheoutputstream.

voidwriteChar(intv)

Writesacharactervalue,whichiscomprisedoftwobytes,totheoutputstream.

voidwriteChars(strings)

Writeseverycharacterinthestrings,totheoutputstreamintheorderofeightbytes,totheoutputstream.

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)

Writestwobytesof lengthinformationtotheoutputstream,followedbythemodifiedUTF-8representationofeverycharacterinthestrings.

SummaryofOutputStreamClasses:-

The DataOutputStream is a counter part of DataInputStream. TheDataOutputStream class implements the methods described in DataOutput interface inadditiontousingmethodsofOutputStreamclass.

OutputStreamClassesSummary:-

OutputStream This abstract class is the super class of all classesrepresentinganoutputstreamofbytes.

BufferedOutputStream Theclassimplementsabufferedoutputstream.

ByteArrayOutputStream Theclassimplementsanoutputstreaminwhichthedataiswrittenintoabytearray.

DataOutputStream A data output stream lets an application write primitiveJavadatatypestoanoutputstreaminaportableway.

FileOutputStream AfileoutputstreamisanoutputstreamforwritingdatatoaFile.

PipedOutputStream Apipedoutputstreamcanbeconnectedtoapipedinputstreamtocreateacommunicationspipe.

FilterOutputStream AFilterOutputStreamcontainssomeotheroutputstreams,whichitusesasitsdestination,possiblytransformingthedata along the way or providing the additionalfunctionality.

PrintStream APrintStreamaddsfunctionalitytoanotheroutputstream,namelytheabilitytoprintrepresentationsofvariousdatavaluesconveniently.

OverviewofCharacterStreamClasses-

Characterstreamsaredefinedbyusingtwoclasshierarchies.Atthetoparetwoabstract classes: Reader and Writer. These abstract classes handle Unicode characterstreams.

The Javahas several concrete subclassesof eachof these.TheabstractReaderandWriter classes define several keymethods that the other stream classes implement.Twoofthemostimportantmethodsareread()andwrite(),whichreadandwritecharactersofdata,respectively.Thesemethodsareoverriddenbyderivedstreamclasses.

Readerstreamclasses:-

Readerstreamclassesaredesignedtoreadcharacterformthefiles.Readerclassis the base class for all other classes in this group. These classes are functionally verysimilar to the input stream classes, except input streams use bytes as their fundamentalunitofinformation,whilereaderstreamsusecharacters.

The Reader class contains methods that are identical to those available in theInputStream class. Therefore, Reader classes can perform almost all the functionsimplementedbytheinputstreamclasses.

(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() willattempt to reposition the stream to this point. Not all character input streamssupportthemark()operation.

booleanmarkSupported()

Tellswhetherthisstreamsupportsthemark()operation

intread()

Reads a single character and returns the integer representation of the nextavailable character from the invoking input stream. -1 is returnedwhenendoffileisencountered.

intread(char[]buffer)

Attemptstoreaduptobufferlengthcharactersintobufferandreturnstheactualnumberofcharactersthataresuccessfullyread.-1isreturnedwhenendoffileisencountered.Thesubclassesofthereadermustimplementthis.

abstractintread(char[]buffer,intoffset,intnumChar)

Attempts to readup tonumCharcharbuffer startingatbufrfer[offset], returningthenumberofcharacters thatare successfully read. -1 is returnedwhenendoffileisencountered.Thesubclassesofthereadermustimplementthis.

booleanready()

Tellswhetherthisstreamisreadytoberead.Returnstrueifthenextinputrequestwillnotwait,otherwiseitreturnsafalse.

voidreset()

Resetthestream.Thismethodisnotsupportedbyallcharacterinputstreams.

longskip(longn)

Skips up to n characters and returns the number of characters skipped. ThisthrowsIllegalArgumentExceptionifnis–ve.

SummaryofReaderClasses:-

Reader Abstractclassforreadingcharacterstreams

BufferedReader Readtextfromacharacter-inputstream,bufferingcharacterssoastoprovidefortheefficientreadingofcharacters,arraysandlines.

CharArrayReader Thisclassimplementsacharacterbufferthatcanbeusedasacharacter-inputstream.

FileReader Convenienceclassforreadingcharacterfiles.

FilterReader Abstractclassforreadingfiltercharacterstreams.

InputStreamReader An InputStreamReader is a bridge from byte streams tocharacter stream: It reads bytes and decodes them intocharactersusingaspecifiedcharset.

PipedReader Pipedcharacterinputstream.

PushbackReader Acharacterstreamreaderthatallowscharacterstobepushedbackintothestream.

StringReader Acharacterstreamwhosesourceisastring.

WriterStreamClass:-

WriterStreamClassesaredesignedtowritecharactertofiles/outputdevices.Thewriterclassisanabstractclass,whichactsasabaseclassforalltheotherwriterstreamclass.

The base class provides support for all output operations by definingmethodsthatareidenticalinthoseinOutputStreamclass.

TheWriter class contains methods that are identical to those available in theOutputStream class. Therefore, Writer classes can perform almost all the functionsimplementedbytheoutputstreamclasses.

(HierarchyofWriterStreamClasses)

TheWriterClass:-

Writer isanabstractclass thatdefinesstreamingcharacteroutput.Allof themethodsinthisclassreturnavoidvalueandthrowanIOExceptioninthecaseoferrors.

MethodsofWriterclass:

abstractvoidclose()

Closesthestreamflushesitfirst.

abstractvoidflush()

Flushesthestream.

voidwrite(char[]cbuf)

Writesanarrayofcharacters.

abstractvoidwrite(char[]cbuf,intoff,intlen)

Writes aportionof anarrayof charactersbeginning fromspecifiedoffset.Thesubclassesmustimplementthismethod.

voidwrite(intc)

Writesasinglecharactertotheinvokingoutputstream.Notethattheparameterisan int,which allows you to callwritewith expressionswithout having to castthembacktochar.

voidwrite(Stringstr)

Writesastring.

voidwrite(Stringstr,intoff,intlen)

Writestheportionofthestringbeginningatthespecifiedoffset.

SummaryofWriterClass-

Writer Abstractclassforwritingtocharacterstreams.

BufferedWriter Writestexttoacharacter-outputstream,bufferingcharacterssoastoprovidefortheefficientwritingofsinglecharacters,arrays,andstrings.

CharArrayWriter ThisclassimplementsacharacterbufferthatcanbeusedasaWriter.

FileWriter Convenienceclassforwritingcharacterfiles.

FilterWriter Abstractclassforwritingfilteredcharacterstreams.

OutputStreamWriter AnOutputStreamWriterisabridgefromcharacterstreamstobytestreams:Characterswrittentoitareencodedintobytesusingaspecifiedcharset.

PipedWriter Pipedcharacter-outputstreams.

PrintWriter Print formatted representations of objects to a text-outputstream.

StringWriter Acharacterstreamthatcollects itsoutput inastringbuffer,whichcanthenbeusedtoconstructastring.

FileClass-

Althoughmostiftheclassesdefinedbyjava.iooperateonstreams,theFileclass

doesnot.Itdealsdirectlywithfilesandthefilesystem.Thatis,thefileclassdoesnotspecifyhowinformationisretrievedfromorstoredinfiles.Itdescribesthepropertiesofaitself.

Afileobjectisusedtoobtainormanipulatetheinformationassociatedwithadiskfile,suchasthepermissions,time,dateanddirectorypath,andtonavigatesub-directoryhierarchies.

Althoughtherearesevererestrictionontheirusewithinappletsforsecurityreasons,filesarestillacentralresourceforstoringpersistentandsharedinformation.

AdirectoryinJavaistreatedsimplyasafilewithoneadditionalproperty–alistoffilenamesthatcanbeexaminedbythelist()method.

publicFile(String);

publicFile(String,String);

publicFile(File,String);

publicFile(URI);

ThisconstructorwasaddedbyJava2,version1.4

publicStringgetName();

Returnsthenameofthefileordirectory

publicStringgetParent();

Returnstheparentdirectoryofthefilefromthepathspecifiedduringobjectcreation,ornullifthispathnamedoesnotnameaparentdirectory.

publicStringgetPath();

Returnstherelativepath.

publicbooleanisAbsolute();

Testswhetherthisabstractpathnameisabsolute.

publicStringgetAbsolutePath();

Returnstheabsolute(complete)pathstartingfromroot.

publicbooleancanRead();

Testswhethertheapplicationcanreadthefiledenotedbythisabstractpathname.

publicbooleancanWrite();

Testswhethertheapplicationcanmodifythefiledenotedbythisabstractpathname.

publicbooleanexists();

Testswhetherthefileordirectorydenotedbythisabstractpathnameexists.

publicbooleanisDirectory();

Testswhetherthefiledenotedbythisabstractpathnameisadirectory.

publicbooleanisFile();

Testswhetherthefiledenotedbythisabstractpathnameisnormalfile.

publicbooleanisHidden();

Testswhetherthefilenamedbythisabstractpathnameisahiddenfile.

publiclonglastModified();

Returnsthetimethatthefiledenotedbythisabstractpathnamewaslastmodified.

publiclonglength();

Returnsthelengthofthefiledenotedbythisabstractpathname.

publicbooleancreateNewFile()throwsjava.io.IOException;

Automaticallycreatesanew,emptyfilenamedbythisabstractpathnameifandonlyifafilewiththisnamedoesnotyetexist.

publicbooleandelete();

Deletesthefileordirectorydenotedbythisabstractpathname.

publicString[]list();

Returnsanarrayofstringsnamingthefilesanddirectoriesinthedirectorydenotedbythisabstractpathname.ReturnsnullifFileobjectcorrespondstoafile.

publicbooleanmkdir();

Createsthedirectorynamedbythisabstractpathname.

publicbooleanmkdirs();

Createsthedirectorynamedbythisabstractpathnameincludinganynecessarybutnonexistentparentdirectories.

publicbooleansetLastModified(long);

Setsthelastmodifiedtimeofthefileordirectorynamedbythisabstractpathname.

publicbooleansetReadOnly();

Marksthefileordirectorynamedbythisabstractpathnamesothatonlyreadoperationsareallowed.

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 Windowsconventions.Ifyouuseaforwardslash(/)onawindowsversionofjava,thepathwillstillresolvecorrectly.

Remember,ifyouareusingthewindowsconvention(\)withastring.TheJavaconventionistousetheUNIX–andURLstyleforwardslashforpathseparators.

File definesmanymethods that obtain the standard properties of aFile object.TheFileclasshowever,isnotsymmetrical.Bythis,wemeanthattherearemainmethodsthat allow you to examine the properties of a simple file object, but no correspondingfunctionexiststochangetheseattributes.

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,yousimplycreateanobjectofFileInputStreamclass,specifyingthenameofthefile(directlyofindirectly)asanargumenttotheconstructor.

publicFileInputStream(String)throwsFileNotFoundException;

CreatesaFileInputStreambyopeningaconnectiontoanactualfile,thefilenamedbythepathnamefilePathinthefilesystem.

publicFileInputStream(File)throwsFileNotFoundException;

CreatesaFileInputStreambyopeningaconnectiontoanactualfile,thefilenamedbytheFileobjectfileinthefilesystem.

publicnativeintread()throwsIOException;

publicintread(byte[])throwsIOException;

publicintread(byte[],int,int)throwsIOException;

publicnativelongskip(long)throwsIOException;

publicnativeintavailable()throwsIOException;

publicvoidclose()throwsIOException;

FileOutputStream-

It is direct sub-class of theOutputStream class. To open a file forwriting,wesimplycreateanobjectofFileOutputStreamclass,specifyingthenameofthefile(directlyorindirectly)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 Fileobject.

publicFileOutputStream(File,boolean)throwsFileNotFoundException;

CreatesafileoutputstreamtowritetothefilerepresentedbythespecifiedFileobject.

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-

TheFileReaderclasscreatesaReaderthatyoucanusetoreadthecontentsofafile.Itstwomostcommonlyusedconstructorsare:

FileReader(Filefile)-

CreatesaFileReaderstreamtoreadfromthespecifiedfile.

FileReader(StringfileName)-

CreatesaFileReaderstreamtoreadfromthespecifiedfile.

Note:Either of the constructors can throwaFileNotFoundException if the file diesnotexist,isadirectoryratherthanaregularfile,orforsomeotherreasoncannotbeopenedforreading.

FileWriter

TheFileWriterclasscreatesawriter thatyoucanuse towrite toa file. Its twomostcommonlyusedconstructorsare:

Constructors:-

FileWriter(Filefile)

ConstructorsaFileWriterobjecttowritetothespecifiedfile.

FileWriter(StringfileName)

ConstructorsaFileWriterobjecttowritetothespecifiedfile.

FileWriter(Filefile,booleanappend)

ConstructorsaFileWriterobjecttowritetothespecifiedfileintheappendmode.

FileWriter(Sringfilename,booleanappend)

ConstructorsaFileWriterobject towrite to thespecified file in theappend mode. Iffirsttwoconstructorsareusedthenalwaysanewfileiscreated.Iffilewiththespecifiednameexists,itgetsdestroyed.Ifthelasttwoconstructorsareusedandappendflagisfalsethentheybehavelikefirsttwoconstructors.

Iftheappendflagistruethenfileisopenedintheappendmodei.e.iffilealreadyexiststhenfilepointerisplacedattheendofthefileandiffiledoesnotexistthennewfileiscreated.

Note:

TheseconstructorscanthrowanIOExceptionifthefileexistsbutisadirectoryratherthanaregularfile,doesnotexistbutcannotbecreated,orcannotbeopenedforanyotherreason.

Forexample,whenyouattempttoopenaread-onlyfile,anIOExceptionwillbethrown.

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 RandomAccessFileenablesustoreadandwritebytes,textandprimitivedatatypesfrom/tolocationinafile(when used with appropriate access permissions). It is not derived from InputStream.Instead, it implements the interfacesDataInput andDataOutput,which define the basicI/Omethods.Italsosupportspositioningrequests-thatis,youcanpositionthefilepointeranywherewithinthefile

Themodeargumentspecifiestheaccessmodeinwhichthefileistobeopened.Thepermittedvaluesandtheirmeaningsare:

ValueMeaning

“r”Openforreadingonly.InvokinganyofthewritemethodsoftheresultingobjectwillcauseanIOExceptiontobethrown.

“rw”Openforreadingandwriting.Ifthefiledoesnotalreadyexistthenanattemptwillbemadetocreateit.

“rws”Openforreadingandwriting,aswith“rw”,andalsorequirethateveryupdatetothefile’scontentormetadatabewrittensynchronouslytotheunderlyingstoragedevice.

“rwd”Openforreadingandwriting,aswith“rw”.Andalsorequirethateveryupdatetothefile’scontent(data)bewrittensynchronouslytotheunderlyingstoragedevice.

MethodsofRandomAccessFileclass:-

BesidemethodsoftheDataInputandDataOutputinterfaces,someofthecommonlyusedmethodsofthisclassare:

publicRandomAccessFile(String,String)throwsjava.io.FileNotFoundException;

Createsarandomaccessfilestreamtoreadfrom,andoptionallytowriteto,thefilespecifiedname.

publicRandomAccessFile(File,String)throwsFileNotFoundException;

Createsarandomaccessfilestreamtoreadfrom,andoptionallytowriteto,thefilespecifiedbytheFileargument.

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,atwhichthenextreadorwriteoccurs.

publicnativevoidseek(long)throwsjava.io.IOException;

Here,newPosspecitiesthenewposition,inbytesofthefilepointerfromthebeginningofthefile.Afteracalltoseek(),thenextreadorwriteoperationwilloccuratthenewfileposition.

publicnativelonglength()throwsjava.io.IOException;

publicnativevoidsetLength(long)throwsjava.io.IOException;

Setsthelengthofthisfile.Thismethodcanbeusedtolengthenorshortenafile.Ifthefileislengthened,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

AByteArrayInputStreamcontainsaninternalbuffer thatcontainbytesthatmaybereadfromthestream.ByteArrayInputStreamisanimplementationofaninputstreamthatusesabytearrayasthesource.

Thisclasshas twoconstructors,eachofwhich requiresabytearray toprovidethedatasource.

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 stream inwhich thedata iswritten intoabytearray.ByteArrayOutputStreamisanimplementationofanoutputstreamthatusesabytearrayasthedestination.

The buffer is hold in the protected buf field of ByteArrayOutputStream. Thebuffer sizewill be increased automatically, if needed. The number if bytes hold by thebufferiscontainedintheprotectedcountfieldofByteArrayOutputStream.

publicjava.io.ByteArrayOutputStream();

Createsanewbytearrayoutputstream.Thebuffercapacityisinitially32bytes,thoughitssizeincreasesifnecessary.

publicjava.io.ByteArrayOutputStream(int);

Createsanewbytearrayoutputstream,withabuffercapacityofthespecifiedsize,inbytes.

publicsynchronizedvoidwrite(int);

publicsynchronizedvoidwrite(byte[],int,int);

publicsynchronizedvoidwriteTo(java.io.OutputStream)throwsjava.io.IOException;

publicsynchronizedvoidreset();

publicsynchronizedbyte[]toByteArray();

publicsynchronizedintsize();

publicsynchronizedjava.lang.StringtoString();

publicsynchronizedjava.lang.StringtoString(java.lang.String)throwsjava.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 is an implementationofa reader stream thatusesachararrayasthesource.Thisclasshastwoconstructors,eachofwhichrequiresachararraytoprovidethedatasource.

Constructors:

CharArrayReader(char[]buf)

CratesaCharArrayReaderfromthespecifiedarrayofchars.

CharArrayReader(char[]buf,intoffset,intlength)

CratesaCharArrayReaderfromthespecifiedarrayofchars.Theresultingreaderwillstartreadingatthegivenoffset.Thetotalnumberofcharvaluesthatcanbereadfromthisreaderwillbeeitherlengthorbuf.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

CharArrayWriter isan implementationofawriter streamthatusesachararraybufferasthedestination.

Constructors:

CharArrayWriter()

CharArrayWriter(intinitialSize)

Inthefirstform,abufferwithadefaultsizeiscreated.Inthesecond,abufferiscreatedwiththesizeequaltothatspecifiedbytheparameterinitialSize.

Thebuffer is hold in thebuf field ofCharArrayWriter.Thebuffer sizewill beincreasedautomatically,ifneeded.ThenumberifcharacterheldbythebufferiscontainedinthecountfieldofCharArrayWriter.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-

APushbackInputStream adds functionality to another input stream, namely theability to “pushback” or “unread” one byte. One of the use of buffering is theimplementationofpushback.

Pushbackisusedonaninputstreamtoallowabytetobereadandthenreturnedto the stream. Beyond the familiar methods of the InputStream class,PushbackInputStreamprovidesunread()method,shownhere:

publicjava.io.PushbackInputStream(java.io.InputStream,int);

CreatesaPushbackInputStreamwithapushbackbufferofthespecifiedsize,andsavesitsargument,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;

Pushbackaportionofanarrayofbytesbycopyingittothefrontofthepushbackbuffer.

publicvoidunread(byte[])throwsjava.io.IOException;

Pushbackanarrayofbytesbycopyingittothefrontofthepushbackbuffer.

publicintavailable()throwsjava.io.IOException;

publiclongskip(long)throwsjava.io.IOException;

publicbooleanmarkSupported();

PushbackInputStreamhasthesideeffectofinvalidatingthemark()orreset()methodsoftheInputStreamusedtocreateit.UsemarkSupported()methodtocheckanystreamonwhichyouaregoingtousemark()/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

Acharacterstreamreaderthatallowscharacterstobepushedbackintothestream.

PushbackReader class allows one ormore 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 morecharacterstothemyokinginputstream.

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;

Pushbackaportionofanarrayofcharactersbycopyingittothefrontofthepushbackbuffer.

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:-AnIOExceptionwillbethrownifthereisanattempttoreturnacharacterwhenthepushbackbufferisfull.

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

TheSequenceInputStreamclass isabytestreamthatallowsyou toconcatenatemultipleInputStreams.TheconstructionofasequenceInputStreamisdifferentfromanyotherInputStream.ASequenceInputStreamconstructoruseseitherapairofInputStreamclassesoranEnumerationofInputStreamclassesasitsargument:

SequenceInputStream(InputStreamis1,InputStreamis2)

Initializes a newly created SequenceInputStream by remembering the twoarguments,whichwillberead inorder, first is1and then is2, toprovide thebytes tobereadfromthisSequenceInputStream.

SequenceInputStream(Enumeratione)

InitializesanewlycreatedSequenceInputStreambyrememberingtheargument,whichmustbeanEnumerationthatproducesobjectswhoserun-timetypeisInputStream.

Operationally, the class fulfills read requests from the first InputStreamuntil itruns out and then switches over to the second one. In the case of Enumeration, itwillcontinuethroughalloftheInputStreamsuntilendofthelastoneisreached.

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.APrintStreamaddsfunctionalitytoanotheroutputstream,namelytheabilitytoprintrepresentationsofvariousdatavaluesconveniently.

Optionally,aPrintStreamcanbecreatedsoastoflushautomatically;thismeans

that the flushmethod is automatically invoked after a byte array iswritten, one of theprintlnmethodsisinvoked,oranewlinecharacterorbyte(‘\n’)iswritten.

All characters printed by a PrintStream are converted are converted into bytesusing theplatform’sdefaultcharacterencodingand thenwritten to theOutputStreamorFilespecifiedintheconstructor.

PrintStream supports the print() and println() methods for all types, includingobject.Ifanargumentisnotasimpletype,thePrintStreammethodswillcalltheobject’stoString()methodandthenprinttheresult.

Constructors:

PrintStream(Filefile)

Createsanewprintstream,withoutautomaticlineflushing,withthespecifiedfile.

PrintStream(StringfileName)

Creates a newprint stream,without automatic line flushing,with the specifiedfilename.

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 consolewhenusingjavaisthroughaPrintWriterstream.PrintWriterisoneofthecharacter-basedclasses.Usingacharacter-basedclassforconsoleoutputmakesiteasiertointernationalizeyourprogram.

Constructors:-

PrintWriter(Filefile)

Creates a new PrintWriter, without automatic line flushing, for writing to thespecifiedfile.

PrintWriter(StringfileName)

Creates a new PrintWriter, without automatic line flushing, for writing to thespecifiedfile.

PrintWriter(OutputStreamout)

Creates a new PrintWriter, without automatic line flushing, for writing to thespecifiedOutputStream.

PrintWriter(OutputStreamout,booleanautoFlush)

CreatesanewPrintWriterforwritingtothespecifiedOutputStream.

PrintWriter(Writerout)

Creates a new PrintWriter, without automatic line flushing, for writing to thespecifiedWriter.

PrintWriter(Writerout,BooleanautoFlush)

CreatesanewPrintWriterforwritingtothespecifiedWriter.

Themostcommonlyusedconstructoris:

PrintWriter(OutputStreamos,booleanflushOnNewLine)

Here, os is an object of type OutputStream, and flushOnNewLine controlswhether Java flushes the output stream every time a println() method is called. IfflushOnNewLine is true, flushing automatically takes place. If false, flushing is notautomatic.

PrintWritersupportprint()andprintln()methodsforall typesincludingobjects.If an argument isnot a simple type, thePrintWritermethods call theobject’s toString()methodandthenprinttheresult.

Towrite the console by using a PrintWriter, specify System.out for the outputstreamandflushthestreamaftereachnewlime.Forexample,thislineofcodecreatesaPrintWriterthatisconnectedtoconsoleoutput.

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 acommunications pipe.The piped output stream is the sending end of the pipe.A pipedinput streamshouldbeconnected toapipedoutput stream; thepiped input stream thenprovideswhateverdatabytesarewrittentothepipedoutputstream.

Typically,dataisreadfromaPipedInputStreamobjectbyonethreadanddataiswrittentothecorrespondingPipedOutputStreambysomeotherthread.Attemptingtousebothobjectsfromasinglethreadisnotrecommendedasitmaydeadlockthethread.Thepiped input stream contains a buffer, decoupling read operations fromwrite 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:-

TheirfunctionalityissameasthatofPipedInputStreamandPipedOutputStreamwiththeonlydifferencethattheyarecharacterstreams.

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 outputstreamsthattransparentlyprovidesomeextendedleveloffunctionality.typicalextensionsare buffering, zip/unzip etc. The filtered byte streams are FilterInputStream,FilterOutputStream.Theirconstructorsare:

FilterInputStream(InputStreamin)

CreatesaFilterInputStreambyassigningtheargumentintothefieldthis.insoastorememberitforlateruse.

FilterOutputStream(OutputStreamout)

Creates an output Stream filter built on top of the specified underlying outputstream.

ThemethodsprovidedintheseclassesareidenticaltothoseinInputStreamandOutputStream.

BufferedByteStreams:-

Forthebyte-orientedstreams,abufferedstreamextendsafilteredstreamclassbyattachingamemorybuffertotheI/Ostreams.ThisbufferallowsJavatodoI/Ooperationsonmorethanabyteattime,henceincreasingperformance.

Because, thebuffer is available, skipping,marking, and resettingof the streambecome possible. The buffered byte stream classes are BufferedInputStream andBufferedOutputStream.PushbackInputStreamalsoimplementsabufferedstream.

TheBufferedInputStream:-

Buffering I/O is a very common performance optimization. Java’sBufferedInputStreamclassallowsyouto“wrap”anyInputStreamintoabufferedstreamandachievethisperformanceimprovement.

BufferedInputStreamhastwoconstructors:

BufferedInputStream(InputStreamin)

creates aBufferedInputStream and saves its argument, the input stream in, for

lateruse.aninternalbufferarrayiscreatedandstoredinbuf.

BufferedInputStream(InputStreamin,intsize)

Creates a BufferdInputStream with the specified buffer size, and saves itsargument,theinputstreamin,forlateruse.

Buffering an input stream also provides the foundation required to supportmoving backward in the available buffer. Beyond the read() and skip() methodsimplementedinanyInputStream,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(whichisenoughforallentityreference).Useofmarkisrestrictedtoaccesswithinthebuffer.Thismeansthatyoucanonlyspecifyaparametertomark()thatissmallerthanthebuffersizeofthestream.

BufferedOutputStream:-

Unlikebufferedinput,bufferingoutputdoesnotprovideadditionalfunctionality.Itisusedonlytoimproveperformance.

Herearethetwoavailableconstructors:

BufferedOutputStream(OutputStreamout)

Creates a newbuffered output stream towrite data to the specified underlyingoutputstream.itusesabufferofsize512bytes.

BufferedOutputStream(OutputStreamout,intsize)

Creates a newbuffered output stream towrite data to the specified underlyingoutputstreamwiththespecifiedbuffersize.

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

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:

UsingaBufferedWriteranincreaseperformancebyreducingthenumberoftimesdataisactuallyphysicallywrittentotheoutputstream.

Constructors:

BufferedWriter(Writerout)

Createsabufferedcharacter-outputstreamthatusesadefault-sizedoutputbuffer.

BufferedWriter(Writerout,intsz)

Createsabufferedcharacter-outputstreamthatusesanoutputbufferofthegivensize.

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

Thebasic inputandoutput streamprovide read/writemethods thatcanonlybeusedforreading/writingbytesorcharacters.

Ifwewanttoread/writetheprimitivedatatypessuchasintegersanddouble,wecanusefilterclassesaswrappersonexistinginputandoutputstreamstofilterdatainthe

originalstream.

The two filter classes used for creating “data streams” for handling primitivetypes are DataInputStream and DataOutputStream. These classes use the concept ofmultipleinheritanceasshownbelowandimplementallthemethodscontainedinboththeparentclassandtheinterface.

Adatastreamforinputfromafilecanbecreatedasfollows:

FileInputStreamfis=newFileInputStream(infile);

DataInputStreamdis=newDataInputStream(fis);

Thesestatementsbasicallywrapdisonfisanduseitasa“filter”.Similarlythefollowingstatementscreatetheoutputdatastreamdosandwrapitovertheoutputfilestreamfos.

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.Thesefieldsaredeclaredas publicandstaticwithinSystemclass.Thismeans that theycanbeusedbyanyotherpartofyourprogramandwithoutreferencetoaspecificobject.

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 anobjectoftypeInputStream.

System.err refers to standard error stream, which also is the console by default.System.errisanobjectoftypePrintStream.

Thesearebytestreams,eventhoughtheytypicallyareusedtoreadandwritecharactersfromandtotheconsole.Youcanwrapthesewithincharacter-basedstreams,ifdesired.

InputStreamReader:

An InputStreamReader is a bridge from byte streams to character streams; itreadsbytesanddecodesthemintocharacterusingaspecifiedcharset.Thecharsetthatitusesmaybespecifiedexplicitly,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,henceInputStreamReaderislinkedtoBufferedReaderthatprovidesthereadLine()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.Thecharsetthatitusesmaybespecifiedexplicity,ortheplatform’sdefaultcharsetmaybeaccepted.

Constructors:

OutputStreamWriter(OutputStreamout)

CreateanOutputStreamthatusesthedefaultcharacterencoding.

OutputStreamWriter(OutputStreamout,StringcharsetName)

CreateanOutputStreamthatusesthenamedcharset.

ReadingConsoleInput:

InJava1.0theonlywaytoperformconsoleinputwastouseabytestream,andoldercodethatusesthisapproachpersists.

Today,usingabytestreamtoreadconsoleinputisstilltechnicallypossible,butdoing so may require the use of a deprecated method, and this approach is notrecommended.

In Java, console input is accomplishedby reading fromSystem.in.Toobtain acharacter-based stream that is attached to console, you wrap System.in in aInputStreamReaderobject,whichcanbefurtherwrapped inaBufferedReaderobject, toimproveperformance.

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 inInputStreamReaderandtofurtherwrapittoBufferedReadertoimproveperformanceandto input one line at a time.The appropriate exampleshave alreadybeen covered in theearliersectionrelatedtoInputStreamReaderclass.

WritingConsoleOutput:

Console output is most easily accomplished with print() and println(). These

methodsaredefinedbytheclassPrintStream(whichisthetypeoftheobjectreferencedby System.out).Even though System.out is a byte stream, using it for simple programoutputisstillacceptable.

However, a character-based alternative is the right choice.Because PrintStream is anoutput stream derived from OutputStream, it also implements the low-level methodwrite().Thus,write() can be used towrite to the console.The simplest formofwrite()definedbyPrintStreamis:

voidwrite(intbyteval)

Thismethodwritestothestream,thebytespecifiedbybyteval.Althoughbytevalisdeclaredasaninteger,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.Thisisusefulwhenyouwanttostorethestateofanobjecttoabytestream.Thisisalsousefulwhenyouwanttosavethestateofyourprogramtoapersistentstoragearea,suchasfile.Atalatertime,youmayrestoretheseobjectsbyusingtheprocessofdeserialization.

SerializationisalsoneededtoimplementRMI.RMIallowsajavaobjectononemachine to invokeamethodofa javaobjectonadifferentmachine.Anobjectmaybesuppliedasanargumenttotheremotemethod.Thesendingmachineserializestheobjectandtranslatesit.Thereceivingmachinedeserializesit.

If you attempt to serialize an object at the top of an object graph, all of the otherreferencedobjectsarerecursivelylocatedandserialized.

Similarly, during the process of deserialization, all of these objects and theirreferences are correctly stored.Variables that are declared as transient or static are notsavedbytheserializationfacilities.

Externalizableinterface:

TheJavafacilitiesforserializationanddeserializationhavebeendesignedsothatmuchoftheworktosaveandrestorethestateofanobjectoccursautomatically.

However,therearecasesinwhichtheprogrammermayneedtohavecontroloverthese processes. For example, it may be desirable to use compression or encryptiontechniques. The externalizable interface is designed for these situations. The objects ofclassimplementingExternalizableinterfacecanalsobeserializedanddeserialized.

But thecontrol iswith theuser i.e.user candecidewhichpart to serializeanddeserialize.TheserializationcodeiswritteninreadExternal()methodanddeserializationcodeiswritteninwriteExternal()method.

MethodsinExternalizableinterface:

voidreadExternal(ObjectInputin)

TheobjectimplementsthereadExternalmethodtorestoreitscontentsbycallingthemethodsofDataInputforprimitivetypesandreadObjectforobject,stringsandarrays.

voidwriteExternal(ObjectOutputout)

Theobject implements thewriteExternalmethod tosave itscontentsbycallingthe methods of DataOutput for its primitive values or calling writeObject method ofObjectOutputforobjects,stringsandarrays.

ObjectOutputInterface:

TheObjectOutputinterfaceextendstheDataOutputinterfaceandsupportsobjectserialization. Beside methods defined in DataOutput interface, objectOutput interfacedefineonlymethod.

VoidwriteObject(Objectobject)

This iscalled toserializeanobject.AllmethodsofObjectOutput interfacewillthrowanIOExceptiononerrorconditions.

ObjectOutputStream:

The ObjectOutputStream class extends the OutputStream class and implements theObjectOutputinterface.Itisresponsibleforwritingobjectstoastream.

Constructor:

ObjectOutputStream(OutputStreamout)

Creates anObjectOutputStream thatwrites to the specifiedOutputStream. Theargumentoutistheoutputstreamtowhichserializedobjectswillbewritten.

Methodtowriteobject:

voidwriteObject(Objectobj)

Writeanobjecttotheunderlyingstorageorstream.

ObjectInputInterface:-

The ObjectInput interface extends the DataInput interface. It supports objectserialization.BesidemethodsdefinedinDataInputinterface,ObjectInputinterfacedefinesonlyonemethod:

ObjectreadObject()

Thisiscalledtodeserializeanobject.

ObjectInputStream:

TheObjectInputStream class extends the InputStream class and implement theObjectInputinterface.ObjectInputStreamisresponsibleforreadingobjectfromastream.

Constructor:

ObjectInputStream(InputStreamin)

Creates an ObjectInputStream that reads from the specified InputStream. Theargumentin,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:wecansavemorethanoneobjectofthesametypeinafileandcanalsosaveobjectofdifferenttypesinthesamefile.

Example15.32

Thisexampledemonstratesthatthetransientandstaticvariablesarenotpersistedduringserialization.

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 initializationwill take place. Testoring stateshouldbedoneinreadExternal().Similarlyduringserializationonlyclassidentificationissaved.AnystatemustbesavedexplicitlyinwriteExternal().

CHAPTER∞16∞(Applet)

Introduction-

AnappletisanapplicationdesignedtotravelovertheInternetandtobeexecutedontheclientmachinebyaJavaCompatiblewebbrowserlikeInternetExplorerorNetscapeNavigator.AppletsarealsoJavaprogramsbuttheyreside(stored)ontheservers.

An applet cannot be executed like standalone application. Applet can be executedonlybyembeddingitintoanHTMLpagelikeanimageorsoundfile.TorunanappletweneedtoaccessanHTMLpagewhichhasappletembeddedintoit.WhenthewebbrowserdownloadssuchanHTMLpage,itsubsequentlyloadstheexecutablefile,whichcontainsappletcodeandthenexecutesitonthelocalmachine.

Afteranappletarrivesontheclient,ithaslimitedaccesstoresources,sothatitcanproduce an arbitrarymulti-media user interface and run complex computationswithoutintroducingtheriskofvirusesorbreaching(breaking)dataintegrity.

AppletArchitecture:

AppletsaredifferentfromnormalJavaprograms.

AppletsareGUIbased(window-based)programs

Appletsareevent-driven

Whenanormal Javaprogram (which is notGUIbased)needs input it prompts the

userandthencallssomeinputmethod,suchasreadLine()i.e. theinteractionisinitiatedbytheprogram.

This is not the way in which GUI-based programs behave. The user initiatesinteractionwiththeprogramratherthanprograminitiatingtheaction.

For example, in a word processing software, user initiates action by clicking ondifferentbuttons,whichgeneratesaneventandsomepieceofcodeisexecutedasaresultandaccordinglysomeactiontakesplace.

Applets use awt package (Abstract Windows Toolkit) for providing GUI and forevent-handling.Theawtiscalledsobecauseittotallydependsonthefunctionalityoftheunderlyingoperatingsystem.

Anappletresemblesasetofinterruptserviceroutines.Anappletwaitsuntilaneventoccurs. The awt notifies the applet about an event by calling an event handler that hasbeenprovidedbytheapplet.

Once this happens, the appletmust take appropriate action and then quickly returncontroltotheAWT.

This is a crucial point. For themost part, our applet should not enter a “mode” ofoperation inwhich itmaintainscontrol foranextendedperiod. Instead, itmustperformspecificactionsinresponsetoeventsandthenreturncontroltotheAWTruntimesystem.

Inthosesituationsinwhichourappletneedstoperformarepetitivetaskonitsown(for example, displaying a scrolling message across its window), we must start anadditionalthreadofexecution.

WritinganApplet:

All applets are sub classes of Applet class. The Applet class is contained in thepackagejava.applet.ThehierarchyoftheAppletclassisasfollows:

java.lang.Object

|

java.awt.Component

|

java.awt.Container

|

java.awt.Panel

|

java.applet.Applet

Theappletclassprovidesallnecessarysupportforappletexecution,suchasstartingandstopping.

It also provides methods that load and display images. It also provides necessarysupportforallthewindow-basedactivities.

Oursubclassextendingtheappletclassmustalwaysbedeclaredaspublicasitisinstantiated(creatingobject)andexecutedbythewebbrowser.

Thebrowsermakesuseofnoargumentconstructorwheninstantiatingtheappletsoitismusttoprovideno-argumentpublicconstructorwiththepublicvisibility.

It is recommended thatwedonotprovideconstructor in theAppletclassas in thatcasecompilerwillprovidethedefaultnoargumentconstructor.

Wecanmakeuseoftheinit()methodforinitialization.Whilewritingappletcodewenormally override some of the methods of the Applet class, which are invokedautomaticallyduringappletexecution.

It is very common to override the paint()method. The code in the paint()methodmainlydisplaystheoutputintheAppletwindow.

Example16.1(App1.java)Thefollowingprogramillustratesasimpleapplet,whichjustdisplays“HelloWorld”insideawindow.Whateverwedraw/displayintheapplet’spaintmethod,itappearsintheapplet’swindow.

Inthefollowingexample,thebackgroundcoloroftheappletwindowissettoredandtheforegroundcolor is set togreenso thebackgroundwouldappearas redand text“HelloWord”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 aretwowaysinwhichwecanrunanapplet.

1.ExecutingtheappletwithinaJavacompatiblewebbrowser.

2.Usinganappletviewer,suchasthestandardSDKtool,appletviewer.Anappletviewerexecutesourapplet inawindow.This is fastestandeasiestway totestourapplet.

ExecutingAppletinawebbrowser:

WeneedtowriteashortHTMLtextfilethatcontainstheappropriateAPPLETtag.Theapplettagmustincludeatleastfollowingthreeattributes:

Code

Width

Height

The attribute code’s value specifies the nameof the class containing applet’s code.The attribute width and height specify the width and height of the applet’s windowsrespectively.

HeretheHTMLfileRunApp.Htmlwithapplet“App1”embeddedintoit.

<html>

<head>

<title>SimpleApplet</title>

</head>

<body>

<h1>Simple“HelloWorld”Application</h1>

<appletcode=“App1”width=500height=100>

</applet>

</body>

</html>

Youcanexecute theappletbyopeningfileRunApp.html inwebbrowser.The filecanbeonlocalfilesystemorcanalsobeloadedfromawebserver.

ExecutingAppletusingappletviewer:

However, a more convenient method exists that we can use to speed up testing.Simplyincludeacomment inyour javasourcecodefile thatcontains thatAPPLETtag.Bydoingso,ourcodeisdocumentedwithaprototypeofthenecessaryHTMLstatements,andwecantestyourcompiledoutputmerelybystartingtheappletviewerwithourJavasourcecodefile.ifweusethismethod,thenaftercompilingwecanexecutetheappletasfollows:

appletviewerSimpleApplet.Java

AppletLifecycleMethods:

Applet overrides a set ofmethods that provides the basicmechanismbywhich thebrowserorappletviewerinterfacestotheappletandcontrolsitsexecution.

Thesemethodsarealsocalledlifecyclemethodsbecausethebrowserorappletviewercalls them automatically during different stages of applet lifecycle. In all there are fivelifecyclemethods:

publicvoidinit()publicvoidstart()publicvoidstop()publicvoiddestroy()publicvoidpaint(Graphicsg)

Four of thesemethods: init(), start(), stop(), anddestroy() are defined in the appletclass.

Thepaint(), isdefinedby theawtComponentclass,default implementations forallthesemethodsareprovided.Appletsdonotneed tooverride thosemethods theydonotuse.However,verysimpleappletswillnotneedtodefinethem.

AppletInitializationandTermination:

Whenanappletbegins,thefollowingmethodsarecalledinsequence

1. init()

2. start()

3. paint()

Whenanappletisterminated,thefollowingsequenceofmethodcallstakesplace:

4. stop()

5. destroy()

Theinit()Method:

Thisisthefirstmethodtobecalled.Thisiswhereweshouldinitializevariablesandwritecodeforotherinitializationactivities.Thismethodiscalledonlyonceduringthelifecycleofourappletimmediatelyafterinstantiation.

Thestart()Method:

Thestart()methodiscalledafterinit().Itisalsocalledtorestartanappletafterithasbeenstopped.Whereinit()iscalledoncethefirsttimeanappletisloaded,start()iscalledeachtimeanapplet’sHTMLdocumentisdisplayedonscreen.So,ifauserleavesawebpageandcomesback,theappletresumesexecutionatstart().

Thepaint()Method:

The paint( ) is called after the init() and start() method when the applet beginsexecution. The paint() method is also called each time our applet’s output must beredrawn.Thissituationcanoccurforseveralreasons.Forexample,thewindowinwhichtheapplet isrunningmaybeoverwrittenbyanotherwindowandthenuncovered.or theappletwindowmaybeminimizedandthenrestored.

TheStop()Method:

The stop()method is calledwhen aweb browser leaves theHTML documentcontainingtheappletwhenitgoestoanotherpage,forexample.Whenstop()iscalled,theappletisprobablerunning.

Weshouldusestop()tosuspendthreadsthatdonotneedtorunwhentheappletisnotvisible.Wecanrestartthemwhenstart()iscallediftheuserreturnstothepage.Wecanalsofreeanycostlyresourceandacquireitagaininthestart()method.

Thedestroy()Method:

The destroy () method is called when the environment determines that our appletneeds to be removed completely from memory. At this point, we should free up any

resourcestheappletmaybeusing.Thestop()methodisalwayscalledbeforedestroy().

Example 16.2A simple applet that sets the background color to cyan, the foregroundcolor to red,anddisplaysamessage that illustrates theorder inwhich the init(), 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,wecandisplayamovingbanner.TheappletcanalsobeusedinapplicationslikedisplayingscoreandotherstatisticsrelatedtoaCricketmatchbyretrievingfromserver;displayingstockpricesetc.

Example16.3

The following example displays a moving banner. It demonstrates use ofrepaint()method to refresh thedisplay.Thisapplet scrollsamessage, fromright to left,acrosstheapplet’swindow.

Since the scrolling of the message is a repetitive task, it is performed by aseparatethread,createdbytheappletwhenitisinitiated.Thisprogramalsodemonstratesthat theresourcescanbefreedinthestop()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 amessagetothestatuswindowsofthebrowserorappletvieweronwhichitisrunning.

TodosocallshowStatus()withthestringthatwewanttodisplay.Thestatuswindowisagoodplace togive theuser feedbackaboutwhat isoccurring in theapplet, suggestoptions,orpossiblereportsometypesoferrors.

Thestatuswindowalsomakesanexcellentdebuggingaid(help),becauseitgivesusaneasywaytooutputinformationaboutourapplet.

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:

TheAPPLETtagisusedtostartanappletfrombothanHTMLdocumentandfromanappletviewer.

Anappletviewerwill execute eachAPPLET tag that it finds in a separatewindow;whilewebbrowserslikeNetscapeNavigator,andInternetExplorerallowmanyappletsonasinglepage.

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:

CODEisa requiredattribute thatgives thenameof thefilecontainingourapplet’scompiledclassfile.ThisfileisrelativetotheCODEBASEURLoftheapplet,whichisthedirectorythatthehtmlfilewasinordirectoryindicatedbyCODEBASEifset.

CODEBASE:

CODEBASE is an optional attribute that specifies the baseURLof the appletcode,whichisthedirectorythatwillbesearchedfortheapplet’sexecutableclassfile(specifiedbytheCODEtag).

TheHTMLdocument’sURLdirectoryisusedastheCODEBASEifthisattributeisnot specified. The CODEBASE does not have to be on the host from which theHTMLdocumentwasread.

ALT:TheALTtagisanoptionalattributeusedtospecifyashorttextmessagethatshouldbedisplayedifthebrowserunderstandstheAPPLETtagbutcannotcurrentlyrun Javaapplet.This isdistinct from the alternateHTMLweprovide forbrowsersthatdonotsupportapplets.

NAME: NAME is an optional attribute used to specify a name for the appletinstance.Appletsmustbenamedinorderforotherappletsonthesamepagetofindthem by name and communicate with them. To obtain an applet by name, usegetApplet(),whichisdefinedbytheAppletContextinterface.

WIDTHandHEIGHT:Sizeofapplet’sdisplayareainpixels.

ALIGH:ALIGNisanoptionalattributesthatspecifiesthealignmentoftheapplet.This attribute is treated the same way as the HTML’S IMG tag with followingpossiblevalues:

LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP,ABSMIDDLE,ANDABSBOTTOM.

VSPACEandHSPACE:TheseattributesareoptionalVSPACEspecifiesthespace,inpixels,aboveandbelowtheapplet.HSPACEspecifiesthespace,inpixelsoneachsideof the applet.Theyare treated the sameas IMG tag’sVSPACEandHSPACEattributes.

ThePARAMTag

ThePARAM tag allowswe to specify applet specific arguments in anHTMLpage.Applets access their attributeswith thegetparameter()method.PARAMtaghastwoattributes:NAMEandVALUE.

Example 16.5 This example demonstrates how to pass parameters to Applet from theHTMLpage.

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.JavawillallowtheapplettoloaddatafromthedirectoryholdingtheHTMLfilethatstartedtheapplet (the docoument base) and the directory from which the applet’s class file wasloaded(thecodebase).

ThesedirectoriesarereturnedasURLobjects.Theycanbeconcatenatedwithastring thatname the filewewant to load.Toactually loadanother file,wewilluse theshowdocument()methoddefinedbytheAppletcontextinterface.

Example 16.6 The following example demonstrates how we can obtain the documentbaseandcodebaseintheappletcode.

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 agraphicalmeansofnavigating theweb that ismore interesting than theunderlinedbluewordsusedbyhypertext.ToallowsourapplettotransfercontroltoanotherURL,wemustusetheshowDcoument()methoddefinedbytheAppletContextinterface.

TheAppletContextisaninterfacethatletsusgetinformationfromtheapplet’sexecutionenvironment.ThecontextofthecurrentlyexecutingappletisobtainedbyacalltothegetAppletContext()methoddefinedbytheappletclass.

Within an applet, once we have obtained the applet’s context, we can bringanother document into view by calling showDocument()method. Thismethod has noreturn value and returns no exception if it fails so use it carefully. There are twoshowDocument()methods.

voidShowDocument(URLurl)

ReplacestheWebpagecurrentlybeingviewedwiththegivenURL

voidShowDocument(URLurl,Stringwhere)

Displays the specified document at the specified loacationwithin the browserwindow.Validargumentsfor“where’are:

“_self”(showinthecurrentframe)

“_parent”(showintheparentframe)

“_top”(showintopmostframe),and

“_blank”(showinnewbrowserwindow)

Example16.7

The following applet demonstrates use of Applet Context and showDocument(). Uponexecution,itobtainsthecurrentappletcontextandusesthatcontexttotransfercontroltoafile calledA.html. This filemust be in the same directory as the applet. Test.html cancontainanyvalidhypertextthatyourlike.

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 designinggraphicaluserinterface(GUI).Mostoftheseclassesbelongtothepackagejava.awtandarecollectivelyknownasAbstractWindowsToolkit(AWT).

We are familiar with software likeMS-WORD,MS-EXCEL etc. All of thesesoftwarehaveaGUIi.e.whenwerunthesesoftware,weseegraphicaluserinterface.

Weaccessvariousfeaturesofthissoftwarebyselectingdifferentoptionsthroughkeyboardormouse.Lotofprogrammingisneededtodisplaytheuserinterface.

ThreeimportantpartsofAWT,whichhelpindesigninggraphicaluserinterfaces,are

Components

Containers

LayoutManagers

AlloftheaboveplayanimportantroleindesigningtheGUI.

Components:

Components are Java’s building blocks for creatingGUI’s.A component is anobject having graphical representation that can be displayed on the screen and that caninteractwiththeuser.Examplesofcomponentsarethebuttons,checkboxesandscrollbarsofa typicalgraphicaluser interface.The java.awt.Componentclass is theabstract superclassof thenon-menurelatedAWTcomponents.Classcomponentcanalsobeextendeddirectly to create lightweight component. A lightweight is a component that is notassociatedwithanativeopaquewindow.

Somecomponentstypes,suchasbuttonsandscrollbars,areuseddirectlyforGUIcontrol.Otherkindsofcomponents(those that inherit fromtheContainerclass)providespecialorganization.WhilethecomponentslikeTextField,TextArea,Listetc,areusedtoacceptinputfromtheuser.Thelabelisadifferenttypeofcomponentwhosepurposeistosimplydisplaytheappropriatelabeltoidentifyothercomponents.

Java’s components are implementedby themany subclassesof the java.awt.Componentandjava.awt.Menucomponentsuperclasses.

One way to organize this fairly large number of classes is to divide them intocategories:

Visualcomponents

Containercomponents

Menucomponents

Componenthierarchy:ThefollowingdiagramshowsAWTthecomponenthierarchy.

Containers:

Thefollowingdiagramdescribesthecontainerhierarchy

All thewindow–basedapplicationsstartwitha top-levelwindowvisibleon thescreen.

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. Acomponent can be made visible only by adding it to a container or putting it inside acontainer.

All javaGUI’sresideeither inanappletor inaFrame.Theappletsandframesarethetwotop-levelcontainersinjava.

Theappletisthetop-levelcontainerforappletssothecomponentsmustbeaddedtoit.Similarlytheframeisthetop-levelcomponentforthestandaloneapplications.

FormorecomplicatedGUI’sitisconvenienttodividetheappletsorframeintosmallerregions.Theseregionsmightconstitute,forexample,atoolbaroramatrixofradiobuttons. In java, GUI sub-regions are implemented most commonly with the panelcontainer.

Panels, just like applets and frames can contain other components such asbuttons, canvas, checkboxes, scrollbars, scrollpanes, text areas, textfields, and otherpanels.

ComplicatedGUI’ssometimeshaveverycomplicatedcontainmenthierarchiesofpanelswithinpanelswithinpanels.Andsoon,downthroughmanylayersofcontainment.

As containers are also components so the methods available for components are alsoavailableforcontainersduetoinheritance.

Themostcommonlyusedmethodforthecontainersisadd()methodusingwhichthecomponentsareaddedthecontaineritsgeneralformis.

voidadd(Componentcomp);

Allthecomponentsarethesub-classesofthecomponentclasssoanycomponentcanbeaddedtothecontainerusingtheadd()method.

LayoutManager:

While adding components to a containers, one important issue is related to theposition and size of the component. The components position can be specified in twoways.

(i)Absolutepositioning.

(ii)Relativepositioning.

Inabsolutepositioning,wespecifytheexactlocationatwhichthecomponentshouldbeadded.ThismethodgivesusfinecontrolandmaybethebestchoiceifwedesigntheGUIforjustoneplatform.

For example, a component can be added in middle of container along horizontaldirection,byspecifyingtheco-ordinatesoftop-leftcornerofthecomponent.

Wecancalculatetheseco-ordinatesbasedonthecontainerwidthandthecomponentwidth.Butthecomponentwillnotbeleftinthemiddle.Ifthecontainerwidthchangesorthesizeofthecomponentchanges.

Theotherapproach, relativepositioning,maynotallowus to specify theexactlocationof thecomponentsbutmaybe suitable in the situationwherewewant that thecomponentshouldalwaysbeinthemiddleofthecontaineralongthehorizontaldirection.

Wecanachievethisbyspecifyingtherelativepositionofthecomponentlikeleft,right, center etc. it is very common to center headings in documents using wordprocessors.Theheadingsremaincenteredevenifthewidthofthepagechangesthisisanexampleorrelativepositioning.

Injavaitispossibletouseabsolutepositioningbutitisnotadvisable.TheAWTis designed to use relative positioning.We can specify component layoutswith relativespecifications, such as the component will be added to the right of the previouscomponent, the componentwill be addedbelow someother component, the componentwill appear at top, size of the component will be ¼th of the container width etc. suchspecificationsareusefulevenwithoutknowledgeofcomponentsizes.

Javaencourages relativepositioningbecause it isplatform independentand thesameGUIshouldworkonawidevarietyofplatformswithoutmodifications.

Built-injavaclassescalledlayoutmanagershandlethetaskofmappingrelativepositionstoactual/physicalpositions.Javasupportsmanytypesoflayoutmanagers,wewilldiscussaboutfollowinglayoutmangers.

1. FlowLayout

2. GridLayout

3. BorderLayout

4. CardLayout

5. GridBagLayout

TwoObservationswhenworkingwithlayoutmanagers:

Wedonothavetobeartheburdenofspecifyingtheexactpositionanddimensionofeachcomponent.

We no longer had the power to specify the exact position anddimensionsofeachcomponent.

WhyJavauseslayoutmanagers?

Therearetworeasons:

1. The theory lies in the position that precise layout (that is, specification in pixels ofeach component’s size and position) is a repetitious and often performed task;therefore,accordingtoOOP’slayoutfunctionalityoughttobeencapsulatedintooneormoreclassestoautomatethetask.

Certainly the layout managers eliminate a lot of development tedious. Manyprogrammersdislike the ideaof layoutmanagersfirst,butcometoappreciate themmoreandmoreastediouschoicesareeliminated.

2. The practical reason for having layout manager stems from java’s platformindependence. In java,AWT components borrow their behaviour from thewindowsystemoftheunderlyinghardwareonwhichtheJVMisrunning.

ThusonaMacintosh,anAWTbuttons tools likeanyotherMacbutton;onamotifplatform,ajavabuttonlookslikeanyothermotifbutton,andsoon.Theproblemhereis that buttons and other components have different sizes when instantiated ondifferentplatforms.

If java encouragedprecisepixel-level sizing andpositioning, therewouldbe lot ofjava GUI’s that looked exquisite on their platform of origin and terrible or evenunusable,onotherplatforms.

Asdiscussedabove,layoutmanagerssolvetheproblembyusingrelativepositioning.

Layoutpolicy:

Every javacomponenthaspreferred size.Thepreferred size expresseshowbig thecomponent would like to be, barring conflict with a layout manager. Preferred size isgenerally the smallest size necessary to render the component in a visuallymeaningfulwayforexample,abutton’spreferredsizeisthesizeofitslabeltext,plusalittleborderofemptyspacearoundthetext,plustheshadoweddecorationsthatmarktheboundaryofthebutton thus a buttons preferred size is “just big enough”. Preferred size is platform

dependentsincecomponentboundarydecorationsvaryfromsystemtosystem.

Whena layoutmanager laysout itscontainer’schildcomponents, ithas tobalancetwoconsiderations;

(i)layoutpolicyand

(ii)eachcomponent’spreferredsize

Firstprioritygoestoenforcinglayoutpolicy.Ifhonoringacomponent’spreferredsize would mean violating the layout policy, then the layout manager overrules thecomponent’spreferredsize.Understandingalayoutmanagermeansunderstandingwhereitwillplaceacomponentandalsohowitwilltreatacomponent’spreferredsize.

1.FlowLayout:

The functionality of the flow layout manager is encapsulated in the classjava.awt.FlowLayout.

The Flow LayoutManagers arranges components in horizontal rows. It is thedefaultlayoutmanagertypeforpanelsandapplets.

Theflowlayoutmanagerfitsasmanycomponentsaspossible into the toprowandmovestheothercomponentintosecondrow.Ifnospaceisleftinthesecondrow,thecomponentwillmovetothethirdrow,andsoon.Thisisquitesimilartotypingtextinadocument.

Whenwereachat theendof thecurrent line, thenextwordmoves to thenextline,andsoon.Ifwechangethewidthorheightofthedocument,theentiredocumentisre-formatted.

The components always appear, left to right, in the order in which they wereaddedtotheircontainer.

Bydefault,theflowlayoutmanagerleavesagapoffivepixelsbetweencomponentsinboth thehorizontalandverticaldirections.Thisdefaultcanbechangedbycallinganoverloadedversionof theFlowLayoutconstructor,andpassing in thedesiredhorizontalandverticalgaps.

Withineveryrow,thecomponentsareevenlyspaced,andtheclusterofcomponentsiscentered. The alignment (sometimes called “justification”) of the clustering can becontrolledbypassingaparametertotheFlowLayoutconstructor.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:-Ifwe reduce the size of the abovewindowand three components do not fit in asinglerowthencomponentsaremovedinthenextrowstartingfromlastcomponent.

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)andthegapbetweenrows(verticalgap)byusingtheoverloadedconstructorwhilesettingthelayout:

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 classjava.awt.GridLayout. The Grid Layout Manager arranges components in tabularformatinrowandcolumns.

Wecanthinkofcontainerspaceasagridofrowsandcolumns.Wehavetospecifythenumberofrowsandcolumnswhilespecifyingthelayout.

TheGridLayoutManagerfitsasmanycomponentsasthesizeoftherow(numberofcolumns specified in the layout) into the top row andmoves the other component intosecondrow,andsoon.Thisislikethespreadsheet,whichisdividedintofixednumberofrowsandcolumns.

The flow layout manager always honors a component’s preferred size. TheGridLayoutmanager takes the opposite extreme: when it performs a layout in a givenspace,itignoresacomponent’spreferredsize.

Eachrowandcolumninagirdlayoutwillbethesamesize,theoverallareaavailabletothelayoutisdividedequallybetweenthenumberofrowsandbetweenthenumberofcolumns.Thegridlayoutuses“rowmajor”notation,i.e.componentsappearintheorderinwhichtheywereadded,fromlefttoright,rowbyrow.

GridLayout manger behaves strangely when we add few components (that is,significantlyfewerthanthenumberofrowstimesthenumberofcolumns)orverymanycomponents(thatis,morethanthenumberofrowstimesthenumberofcolumns).

If the same components are to be laid in a taller, narrower frame, then everycomponentisproportionallytallerandnarrowerandvice-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 classjava.awt.BorderLayout.TheBorderLayoutmanageristhedefaultmanagerforframes,sosoonerorlaterapplicationprogrammersarecertaintocometogripswithit.

Itenforcesaveryusefullayoutpolicy,butitispossiblylessintuitivethaneithertheflow or grid layout managers. The Flow layout manger always honor’s a component’spreferred size; the Grid layout manager never does. The Border layout manager doessomethinginbetween.

The Border Layout Manager divides the available container space into five parts:North,South,East,WestandCenter.Wecanaddonecomponenttoeachregion.

Each of the five regionsmaybe empty ormay contain one component (that is, noregion is required to contain a component, but the regions can only contain onecomponent).

The Border layout manager honors the preferred height of the North and Southcomponents,andforcesthemtobeexactlyaswideasthecontainer.TheNorthandSouthregionsareusefulfortoolbars,statuslines,andanyothercontrolsthatoughttobeaswideaspossible,butnohigherthannecessary.

TheEastandWestregionsaretheoppositeofNorthandSouth.InEastandWest,acomponentgetsitspreferredwidthbuthasitsheightcontained.

Here a component Extends vertically up to the bottom of theNorth component (ifthereisone)ortothetopofthecontainer(ifthereisnoNorthcomponent).

SimilarlythecomponentextendsverticallydowntotheSouthcomponent(ifthereisone)ortothebottomofthecontainer(ifthereisnoSouthcomponent).

We can only put a single component in each region well, if that component is acontainer, then we can get multiple components displayed. The Border layout is notaffectedbytheorderinwhichweaddcomponents.Instead,wemustspecifywhichofthefiveregionswillreceivethecomponentweareadding.

Theoverloadedversionofadd()takestwoparameters:

First,thecomponentbeingadded,and

Second,anobject

ProperuseofBorderlayoutmanagerrequiresthatthesecondparameterbeaconstantdefined in theBorderLayoutclass itself.The fiveconstants thatweshouldknowaboutare:

BorderLayout.NORTH

BorderLayout.SOUTH

BorderLayout.EAST

BorderLayout.WEST

BorderLayout.CENTER

The fifth region that a Border layout manager controls is called Center. Center issimplythepartofacontainerthatremainsafterNorth,South,East,andWesthavebeenallocated.

Whenaddingacomponenttocenter,itislegalbutveryunwise,toemitthesecondparametertoadd()call.InJavaPlatform,theBorderlayoutmanagerwillassumethatWemeancenter;

However,inolderversions,thebehaviorwasunpredictable,andtypicallyresultedinthecomponentbeingentirelyinvisible.

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

InCardLayoutwecan storemanycardsbutone cardwill be shownat a time.Onlyonecardwillbevisibleata time,butyoucanflipfromonecard toanother.HerecardmeansaPanel.

If we want to show two cards one at a time then we have to create first two

PanelsoneforeachcardandonemainPanelforcontainingthesetwocards.Thiscanbeusefulforuserinterfaceswithoptionalcomponentsthatcanbedynamicallyenabledanddisableduponuserinput.

Constructors:

CardLayout();

createsanewcardlayoutwithgapsofsize0.

CardLayout(int,int);

CreatesanewCardLayoutwiththespecifiedhorizontalandverticalgaps.Thehorizontalgapsareplacedattheleftandrightedges.Theverticalgapsareplacedatthetopandbottomedges.

FromotherlayoutstheCardLayoutrequiresabitmorework.Thecardsareheldtypicallyinanobjectoftypepanel.Whencardsareaddedtothepanel,theyareusuallygivenaname.Thuswewillusetheadd()methodwhenaddingcardstoapanel.

voidadd(Componentobjpanel,Objectobjname)

Here,objnameisastringthatspecifiesthenameofthecardwhosepanelisspecifiedbyobjpanel.

Methods:

voidfirst(Containerparent)

Goestothefirstcardofthecontainer.

voidnext(Containerparent)

Goestothenextcardofthegivencontainer.Ifthecurrentlyvisiblecardisthelastone,thismethodflipstothefirstcardinthelayout.

voidprevious(Containerparent)

Goestothepreviouscardofthegivencontainer.Ifthecurrentlyvisiblecardisthefirstone,thismethodflipstothelastcardinthelayout.

voidlast(Containerparent)

Goestothelastcardofthecontainer

voidshow(Containerparent,Stringname)

Goestothecomponentthatwasaddedtothelayoutwiththegivenname.Ifnosuchcomponentexists,thennothinghappens.

ThefollowingstepsareusedtocreatesaCardLayout

1,CreatesanewPanelobjectandanobjectofCardLayout.

2.SetthelayoutforPanelobjectasCardLayoutusingitsinstancecreatedinfirststeps.

3.Nowforeachcard,createsaseparatePanelobjectandaddwhatevercomponentswewanttoaddtothatPanellikebuttons,checkboxes,etc.

4.EachPanelobjectcreatedinsteps3isaddedtothemainPanelobjectcreatedinstep1,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-

TheGridBagLaoutisthemostcomplexandflexibleofthestandardlayoutmanagers.AlthoughitsoundslikeitshouldbeasubclassofGridLayout,butitisdifferententirely.WithGridLayout,elementsarearranged

Example17.11:

AWTcomponentscanbeclassifiedas:

1. VisualComponents.

2. ContainerComponents.

3. MenuComponents.

VisualComponents andContainer componentsboth arepartof the componenthierarchystartingwiththeclassjava.awt.Component.

1. Methodsofjava.awt.Componentclass

Severalmethodsareimplementedbyallthevisualandcontainercomponents,byvirtueofinheritancefromjava.awt.component.(Themenucomponentsextendfromjava.awt.MenuComponent,Sotheydonotinheritthesamesuperclassfunctionality).Thesemethodsarediscussedbelow:

DimensiongetSize()

ReturnsthesizeofthiscomponentintheformofaDimensionobject,whichhaspublicdatamembersheightandwidthoftypeint.

voidsetBackground(Colorc)

Sets thebackgroundcolorofacomponent.Generallybackgroundcolor isusedforrenderingthenon-textualareaofthecomponent.

voidsetForeground(Colorc)

Sets the foreground color of a component. Generally foreground color of acomponent is used for rendering text. If We do not explicitly set a component’sforegroundorbackgroundcolor,thecomponentusestheforegroundandbackground

colorofitsimmediatecontainer.

voidsetFont(Fontf)

ThesetFont()methoddeterminesthefont thatacomponentwilluseforrenderinganytext that itneeds todisplay.IfWedonotexplicitlysetacomponent’sfont, thecomponentusesthefontofitscontainer.

voidsetEnabled(Booleanb)

If the argument is true, then the component has its normal appearance. If theargument is false, then the component is grayed out and does not respond to userinput.

voidsetSize(Dimensiond)

Setsthesizeofthecomponent.

voidsetSize(intwidth,intheight)

Setsthesizeofthecomponent.

voidsetBounds(intx,inty,intwidth,intheight)

Attempts tomoveand resize the component.Thenew locationof the top- leftcornerisspecifiedbyxandy,andthenewsizeisspecifiedbywidthandheight.

voidsetVisible(Booleanb)

ThismethodtakesaBooleanargumentthatdictateswhetherthecomponentistobeseenonthescreen.Thismethodisgenerallyusedforframes.

Note-

ifWehavetriedcallingsetSize()orsetBounds()methods,weknowthatitisusuallyfutile.Thesizeandpositionthatweattempttogiveacomponentisoverruledbyalayoutmanager.

In fact, these two methods exist mostly for the use of layout managers. Themajor exception to this rule is theFrame class,which is not under the thumbof alayoutmanagerandisperfectlywillingtohavewesetitssizeorbounds.

VisualComponents:

Thevisualcomponentsaretheonesthatuserscanactuallyseeandinteractwith.TheAWTsupportsthefollowingvisualcomponents.

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 theappropriateconstructor.Thenweaddthecomponenttoacontainer.

Button:

TheButtonclass,implementsapushbutton.

Constructors

Button()

Button(String)

The constructor takes a string parameter that specifies the text of the button’slabel.WhenabuttonispusheditsendsanActionevent.

Methods:

StringgetLabel()

Getsthelabelofthisbutton.

voidsetLabel(Stringlabel)

Setsthebutton’slabeltobethespecifiedstring.

voidaddActionListener(ActionListener1)

Adds the specified action listener to receive action eventsfromthisbutton.

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 cansubclass 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 theprogrammertotransformthoseinputsintoameaningfullookandfeel.

Thedefaultsize(or,moreproperly,thepreferredsize)ofacanvasisuselesslysmall.Onewaytodealwiththisproblemistousealayoutmanagerthatwillresizethecanvas.AnotherwayistocallsetSize()onthecanvasourself,canvasesareararecasewherethismightactuallyworkbecause thevaluewesend into thesetSize( )methodbecomes thecanvas’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.Ifwedonotspecifyandinitialstate,thedefaultisfalse.

Methods:

StringgetLabel()

Getsthelabelofthischeckbox.

voidsetLabel(Stringlabel)

Setsthischeckbox’slabeltobethestringargument.

boleangetState()

Determineswhetherthischeckboxisinthe“on”or“off“state.

voidsetState(booleanstate)

Setsthestateofthischeckboxtothespecifiedstate.

voidaddItemListener(ItemListener)

Addsthespecifieditemlistenertoreceiveitemeventsfromthischeckbox.

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 radiobehavior.Withradiobehavior,onlyonememberofacheckboxgroupcanbetrueatanytime; selecting a newmember changes the state of the previously selected member tofalse.Manywindowssystems(Motifforexample)implementradiogroupsascomponentsintheirownright.

Wecanimplementradiobehaviorbycreatingmultiplecheckboxesandgroupingthemusingjava.awt.CheckboxGroupClass.InJavathejava.Awt.CheckboxGroupclassisnotacomponent;itissimplyanon-visibleclassthatorganizescheckboxes.ThismeansthatJavaimposesnorestrictionsonthespatialrelationshipsamongmembersofacheckboxgroup.

If wewant to, we could put onemember of a group in the upper left corner of aframe,anothermemberinthelower-rightcorner,andathirdmemberinadifferentframealtogether.Ofcourse,theresultwouldprobablybecontrarytobothreasonandmostGUIstyleguides.

TwomethodsoftheCheckboxGroupclasssupportgettingandsettingthecurrentlyselectedmemberorthegroup.

CheckboxgetSelectedCheckbox()

Getsthecurrentchoicefromthischeckboxgroup.

voidsetSelectedCheckbox(Checkboxbox)

Sets the currently selected check box in this group to bespecifiedcheckbox.

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)

Adds the specified item listener to receive itemevents fromthischoicemenu.

StringgetItem(intindex)

GetstheStringatthespecifiedindexinthisChoicemenu.

intgetItemCount()

ReturnsthenumberofitemsinthisChoicemenu.

intgetSelectedIndex()

Returnstheindexofthecurrentlyselecteditem.

StringgetSelectedItem()

Getsarepresentationofthecurrentchoiceasastring.

voidinsert(Stringitem,intindex)

Insertstheitemintothischoiceatthespecifiedposition.

voidremove(intposition)

Removesthefirstoccurrenceofitemformthechoicemenu.

voidremove(Stringitem)

RemovesthefirstoccurrenceofitemfromtheChoicemenu.

voidremoveAll()

Removesallitemsfromthechoicemenu.

voidselect(intpos)

Setstheselectediteminthischoicemenutobetheitematthespecifiedposition.

voidselect(StringStr)

Sets the selected item in this Choice menu to be the itemwhosenameisequaltothespecifiedstring.

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 torespondtouserinput,ortosendoutevents.

Constructors:

Label()

Constructsanemptylabel.

Label(Stringtext)

Constructsanewlabelwiththespecifiedstringoftext,leftjustified.

Label(Stringtext,intalignment)

Constructsanewlabelthatpresentthespecifiedstringoftextwiththespecifiedalignment.

Thedefaultalignmentforlabelsistotheleft.Tosetthealignment,usethethirdfromoftheconstructorandpassinoneofthefollowing:

Lable.LEFTLabel.CENTERLabel.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:

A list is a collectionof text items, arrangedvertically. If a list containsmore itemsthanitcandisplay,itautomaticallyacquiresaverticalscrollbar.

Constructors:

List()

CreatesanewScrollinglist.Thisconstructordoesnotspecifynumberofvisible

rowsbutproducesadefaultpreferredheightof four rows.Ofcourse, inmanycasestheactualheightofalistwillbedictatedbyalayoutmanager.

List(introws)

Createsanewscrollinglistinitializedwiththespecifiednumberofvisiblelines.

List(introws,booleanmultipleMode)

Createsanewscrollinglistinitializedtodisplaytospecifiednumberofrowsandallowsmultipleselections.

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,soascrollbarisautomaticallyprovidedtogiveaccesstothebottomtwolines.

Note:SelectinganiteminalistcausesthelisttosendanItemevent;double-clickinganitemsendsanActionEvent.

voidadd(Stringitem)

Addthespecifieditemtotheendofscrollinglist.

voidadd(Stringitem,intindex)

Addsthespecifieditemtothescrollinglistatthepositionindicatedbytheindex.

voidaddActionListener(ActionListeneri)

Addsthespecifieditemlistenertoreceiveactioneventsformthislist.

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)

Replaestheitematthespecifiedindexinthescrollinglistwiththenewstring.

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.BothclassesextendfromtheTextComponentsuperclass.

Object � Component� TextComponent� (TextField,TextArea)

Bothclasses(TextFieldandTextArea)haveavarietyofconstructors,whichoffertheoptionofspecifyingornotspecifyinganinitialstringorpreferredsize.Theconstructorsthat do not specify a preferred size are most appropriate for situations where a layoutmanagerwillignorethecomponent’spreferredsize.

ConstructorsofTextFieldClass:

TextField()

Constructsanewtextfiled.

TextField(intcolumns)

Constructsanewemptytextfieldwiththespecifiednumberofcolumns.

TextField(Stringtext)

Constructsanewtextfieldinitializedwiththespecifiedtext.

TextField(Stringtext,intcolumns)

Constructs a new text field initializedwith the specified text to be displayed, andwideenoughtoholdthespecifiednumberofcolumns.

ConstructorsofTextAreaClass:

TextArea()

Constructsanewtextareawiththeemptystringtext.

TextArea(introws,intcolumns)

Constructs a new text area with the specified number of row& columns and theemptystringastext.

TextArea(Stringtext)

Constructsanewtextareawiththespecifiedtext.

TextArea(Stringtext,introws,intcolumns)

Constructsanewtextareawiththespecifiedtext,andwiththespecifiednumberofrowsandcolumns.

TextArea(Stringtext,introws,intcolumns,intScrollbarPolicy)

Constructsanewtextareawiththespecifiedtext,andwiththerows,columns,andscrollbarpolicyasspecified.

The textAreaclassdefinesseveralconstants thatcanbesuppliedasvalues for thescrollbarPolicyargument.

SCROLLBARS_BOTH,

SCROLLBARS_VERTICAL_ONLY,

SCROLLBARS_HORIZONTAL_ONLY,

SCROLLBARS_NONE.

For both classes, there are some surprising issues to the number of columnsparameter.

First,thenumberofcolumnsisameasureofwidthintermsofcolumnsoftext,as rendered in a particular front. A 25-columns text area with a tiny will be verynarrow,whilea5-columnstextareawithahugefontwillbeextremelywide.

Next, there is the problem of proportional fonts. For a fixed width font, it isobviouswhatthecolumnwidthshouldbe.Forproportionalfont,thecolumnwidthistaken tobe the averageof all the font’s characterwidths.This average is a simpleaverage of all the characters in the set; it does not take into account frequency ofcharacters use. So in most cases, text components that contain largely lowercaseletterswilldisplaymorethantherequestednumberofcharacters.

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 iseditable.

voidsetTextSrtingt)

Setsthetextthatispresentedbythistextcomponenttobethespecifiedtext.

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 modaldialog,whichmeansinputfromthedialog’sparentframewillbedirectedexclusivelytothe dialog, as long as dialog remains visible on the screen.The dialog is automaticallyremovedwhen theuse specifies a file or clicks the cancel button.Themost usefulFiledialogconstructorhasthefollowingform:

FileDialog(Frameparent,Stringtitle,intmode)

The dialog’s parent is the frameoverwhich the dialogwill appear.The title stringappearsinthedialog’stitlebar.

Themodeshouldbeeither.

FileDialog.LOADor

FileDialog.SAVE

Aftertheuserhasspecifiedafile,thenameofthefileoritsdirectorycanberetrievedwiththefollowingmethods.:

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,whichmaybetallerorwiderthanthescrollpaneitself.

If the container component is larger than the scroll pane, then the defaultbehavior 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 containerwith the specified scroll bar behavior. Thescrollpanedisplaypolicyshouldbeoneof:

ScrollPane.SCROLLBARS_AS_NEEDED(default)

ScrollPane.SCROLLBARS_ALWAYS

ScrollPane.SCROLLBARS_NEVER

TheCode listedbelowcreatesa scrollpanewithdefault (As_NEEDED)scrollbar behavior. The scroll pane contains a very large button; So the scroll barswilldefinitelybeneeded.

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 acomponentinitsownright.Therearethreeconstructors:

Scrollbar()

Constructsanewverticalscrollbar.

Scrollbar(intorientation)

Constructsanewscrollbarwithhespecifiedorientation.

Scrollbar (int orientation, int initialValue, int sliderSize, int minValue, intmaxValue)

Constructs a new scroll barewith the specified orientation initial value, slidersize,andminimumandmaximumvalues.ThesliderSizeparametercontrolsthesizeoftheslider,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, itpromptsthe user and then calls some input method, such as readline() i.e. the interaction isinitiatedby theprogram.This isnot theway inwhichgui-basedprogramsbehave.Theuserinitiatesinteractionwiththeprogramratherthanprograminitiatingtheaction.

Forexample,inawordprocessingsoftware,userinitiatesactionbyclickingondifferentbuttons,whichgeneratesaneventandsomepieceofcodeisexecutedasaresultand accordingly some action takes place. The clicking on save button will invoke themethodwhichsavesthecontentstoafile.

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 delegationmodelacomponentmaybetoldwhichobjectorshouldbenotifiedwhenthecomponentgeneratesaparticularkindofevent.

Ifacomponentisnotinterestedinaneventtype,theneventsofthattypewillnotbepropagated.Thedelegationmodelisbasedonthefollowingkeyconcepts:

Eventclasses.

Eventlisteners.

Adapters.

Eventclasses:

Clicking on a button results in an event. The event has lot of informationassociatedwithit,like:time,componentgeneratingtheevent,co-ordinatesofthepointatwhichclickingtookplaceetc.

Thisinformationisputinsideaneventclass.Theconceptissimilartoexceptionhandling. Whenever an exception occurs an object of appropriate exception class iscreatedandalltheexceptionrelatedinformationisputintothisobject.

Wehavehierarchyofeventclasses,whichissomewhatsimilartothehierarchyof exception classes. Whenever some event occurs, it is detected by event handling,mechanism,whichcreatesobjectsofappropriateeventclassandputsalltheeventrelatedinformationintoit.

Eventlisteners:

Event listeners are responsible for taking appropriate action when an eventoccurs. An event listener is an object to which a component has delegated the task ofhandlingaparticularkindofevent.

When the component experiences input, an event of the appropriate type isconstructed,theeventisthenpassedastheparametertoamethodcallonthelistener.Alistenermustimplementtheinterfacethatcontainsthateventhandlingmethod.

We can compare the event listeners with the catch blocks for handling theexceptions. We need to provide a catch block corresponding to the exception to behandled.Similarlyifwewanttohandleaneventgeneratedbysomecomponent,weneedtoprovideappropriatelistener.

Thelistenersareassociatedwiththecomponents.Differenteventshavedifferentlisteners.Wheneventoccurs,anappropriatelistenermethodiscalledandeventobjectispassedasparameter.

Adapters:

The listeners defined in the language are interfaces only.We need to provideimplementationoftheappropriatelistener.Somelistenershave2ormoremethods.

To implement a listener having more than one method, we need to provideimplementation of all the methods even if we are interested only in one method. theadapterclassesprovidethesolutiontothisproblem.

Anadapterclassprovidesdummyimplementationofallthemethodsofalistener.This helps in reducing programming efforts. If we want to use just one method of alistenerclasscontainingsay5methods thenwecansimplyextent theadapterclassandoverridethedesiredmethod.

Eventhierarchy:

TheAWThasawell-definedeventhierarchy.Normallytheclassescorrespondingtoleafnodesintheeventhierarchyrepresenttheactualevents.Whilenon-leafclassesactasbaseclassesandencapsulate.

AWTeventhierarchyisdescribedinthefollowingdiagram.

Thejava.util.eventObjectclass:

Thisisthetopmostsuperclassofalltheeventclasses.Itisaverygeneralclass,withonlyonemethodofinterest,whichreturnstheobjectthatoriginatedtheevent.

Objectgetsource()

Thejava.awt.AWTEventClass:

Onesubclassofeventobjectisjava.awt.AWTEvent,whichisthesuperclassofallthedelegationmodeleventclasses.Again,thereisonlyonemethodofinterest,whichreturntheidoftheevent.

intgetID()

Anevent’sIDisanintthatspecifiestheexactnatureoftheevent.Forexample,aninstanceofthemouseeventclasscanrepresentoneofsevenoccurrences:click,Drag,Entrance,Move,Exit,Press,Release.EachofthesepossibilitiesisrepresentedbyanintMouseEvent.MOUSE_CLICKED,MouseEvent.MOUSE_DRAGGED,andsoon.

Thesubclassesofjava.awt.AWTEventrepresentthevariouseventtypesthatcanbe generated by the various AWT components, and contain all necessary informationrelatingtotheactivitythattriggeredtheevent.

Thenon-superclasseventtypes(i.ethosethatareactuallyfiredbycomponent)are:

1. ActionEvent:generalbyactivationofcomponentsforexample.itisgeneratedonbuttonclick,ondouble-clickonlistitemandonpressingenterinaTextField.

2. AdjustmentEvent: generated by adjustment of adjustable components such asscrollbars.

3. ContainerEvent: generatedwhencomponents are added toor removed fromacontainer.

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:

Thispackageprovidestheinterfacesandclassesfordealingwithdifferenttypesof events fired by AWT components. The events are fired by event sources. An eventlistener registers with an event source to receive notifications about the events of aparticulartype.

This package defines events and event listeners, as well as event listeneradapters, which are convenience classes to make easier the process of writing eventlisteners.

EventListenerInterfaces:

Eacheventclasshasacorrespondinglistenerinterfaceanddefinesoneormoremethods. The most commonly used listener interfaces are described in the followingsections.

TheActionListenerInterface:

This is the listener interface for receiving action events. The class that isinterestedinprocessinganactioneventimplement this interface,andtheobjectcreatedwiththatclassisregisteredwithacomponent,usingthecomponent’saddActionListener()method.Whentheactioneventoccurs,theactionlistener’sactionperformed()methodisinvokedwhosesignaturesare:

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 orremovedfromacontainer.

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,andexit)onacomponent.

Method:

voidmouseClicked(MouseEvente)

Invokedwhenthemousebuttonisclicked(pressedandreleased)onaComponent.

voidmouseEntered(MouseEvente)

Invokedwhenthemouseentersacomponent.

voidmouseExited(MouseEvente)

Invokedwhenamouseexitsacomponent.

voidmousePressed(MouseEvente)

Invokedwhenamousebuttonispressedonacomponent.

voidmouseReleased(MouseEvente)

Invokedwhenamousebuttonisreleasedonacomponent.

MouseMotionListener:

This is the listener interface for receivingmousemotion events (move and drag) on acomponent.

Method:

voidmouseDragged(MouseEvente)

Invokedwhenamousebuttonispressedonacomponentandthendragged.

voidmouseMoved(MouseEvente)

Invoked when a mouse cursor is moved over a component but nobuttonsispushed.

TheMouseWheelListenerInterface:

Thisisthelistenerinterfaceforreceivingmousewheeleventsonacomponent.

Method:

voidmouseWheelMoved(MouseEvente)

Invokedwhenthemousewheelisrotated.

TheWindowListenerInterface:

whenthewindow’sstatuschangesbyvirtueofbeingopened,closed,activatedordeactivated,iconifiedordeiconified,therelevantmethodinthelistenerobjectisinvoked,andthewindoweventispassedtoit.

Methods:

voidwindowAcitvated(WindowEvente)

Invokedwhenthewindowissettobetheactivewindow.

voidwindowClosed(WindowEvente)

Invoked when the window has been close as the result of callingDisposeonthewindow.

voidwindowClosing(WindowEvente)

Invoked when the user attempts to close the window from thewindow’ssystemmenu.

voidwindowDeactivated(WindowEvente)

Invokedwhenawindowisnolongertheactivewindow.

voidwindowDeiconified(WindowEvente)invokedwhenawindowischangedfromaminimizedtoa

normalstate.

voidwindowIconified(WindowEvente)

Invoked when a window is changed from a normal to a minimizedstate.

voidwindowOpended(WindowEvente)

Invokedthefirsttimeawindowismadevisible.

HandlingActionEvent:Example18.1

The following example explains how to handle the actionevnet generated as a result ofclickingonabutton.

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.thereisnoguaranteethatlistenerswillbenotifiedintheorderinwhichtheywereadded.

Thereisalsonoguaranteethatalllistenernotificationwilloccurinthesamethread,thus,listenersmusttakeprecautionsagainstcorruptingshareddata.

Aneventlistenermayberemovedfromacomponent’slistoflistenersbycallingremoveXXXListener()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.Althoughweneedonlyonemethodwindow Closing ( ) in the class implementing Window Listener but we will have toprovidedummyimplementationforallthemethods.

The java.awt.event package provides several adapter classes, one for each listenerinterfacethatdefinesmorethanjustasinglemethod.

An adapter is simply a class that implements an interface by providing do nothingmethods. For example, the Window Adapter class implements the Window Listenerinterfacewithsevendo-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 aredelivered to listeners before they are processed normally by the source where theyoriginated. This allows listeners and component subsclasses to “consume” the event sothat the sourcewill not process them in their defaultmanner. For example, consumingmouse pressed events on a Button component will prevent the Button from beingactivated.

Methods:

voidconsume()

Consumes this event so that it will not be processed in the defaultmannerbythesourcethatoriginatedit.

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 actionoccurredinacomponent.Amouseactionisconsideredtooccurinaparticularcomponentifandonlyifthemousecursorisovertheun-obscuredpartofthecomponent’schildrenorbyamenuorbyatop-levelwidow.

ThiseventisusedbothforMouseevents(click,enter,press,exit,release)andMousemotionevents(moveanddrag).

Methods:

intgetButton()

Returns which, if any, of the mouse buttons has changedstate.

intgetClickCount()

Returns the number of mouse clicks associated with thisevent.

staticStringgetMouseModifiersText(intmodifiers)

ReturnsaStringdescribingthemodifierKeysthatweredownduringtheevent,suchas“Shift”,or“Ctrl+shift”.

pointgetPoint()

Returns the x, y position of the event relative to the sourcecomponent.

intgetX()

Returns thehorizontalxpositionof theevent relative to thesourcecomponent.

intgetY()

Returns the vertical y position of the event relative to thesourcecomponent.

booleanisPopupTrigger()

Returnswhetherornot thismouseevent is thepopupmenutriggereventfortheplatform.

Note: Popup menus are triggered differently on different systems. Therefore,isPopupTrigger () should be checked in both mouse Pressed and mouse Released forpropercross-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:

It is a semantic event,which indicates that a component–definedactionoccurred.This high level event is generated by a component (such as a Button) when thecomponent-specificactionoccurs(Suchasbeingpressed).TheeventispassedtoeveryActionListenerobject that registered to receive such eventsusing the component’s addactionListenermethod.

TheobjectthatimplementstheActionListenerinterfacegetsthisActionEventwhenthe event occurs. The listener is therefore spared the details of processing individualmousemovementsandmouseclicks,andcaninsteadprocessa“meaningful”(semantic)eventlike“buttonpressed”.

Note:ToinvokeanActionEventonaButtonusingtheKeyboard,usethespacebar.

Methods:

StringgetAction(Command)

Returnsthecommandstringassociatedwiththisaction.

intgetModifiers()

ReturnsthemodifierKeyshelddownduringthisactionevent.

longgetWhen()

Returnsthetimestampofwhenthiseventoccurred.

Example18.8:

ThisexampleillustrateshowwecanidentifythekeymodifierseffectivewhenandActionEventoccurs.

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 anadjustmentevent,theobviousquestionis,“Nowwhatisthescrollbar’svalue?”.Whenwefindoutthatthemousehasbeenclicked,itisnaturaltowonder,“Whatarethemouse’sxandycoordinates?”Butwhenwe findout thatabuttonhassentanActionevent, theredoesnotseemtobeanyadditionalinformationtoseek;thebuttonhasbeenclicked,andthatseemstobeallthereistoKnow.

However,thereisanextrapieceofinformationassociatedwithanActionevent.Thisinformation is a string,knowas anActioncommand.Wecanextract anActionevent’s

ActioncommandwiththegetActionCommand()method.IfanActioneventwassentbyatextfield,getActionCommand()returnsthecurrentcontentsofthetextfield.(AtextfieldsendsanActioneventwhentheusertypestheEnterKey.).IfanActioneventwassentbyabutton,thedefaultbehaviorisforgetActionCommand()toreturnthestringthatisthebutton’s label.However,wecanexplicitly set abutton’sActionCommandbycalling itssetActionCommand(String)method.

Buttonbtn=newButton(“Hello”);

btn.setActionCommand(“Hello”);

The benefit of Action commands for buttons is apparent when a button’s ActionlistenerneedstodecidehowtoreacttoanActionevent.Itiscommonforasinglelistenerto act as a listener for several components ; inour context, a singleobjectmightbe anActionlistenerforseveralormanybutton.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:DemonstrationofFocusListenerColorofTextFieldchangesonfocuslostorgained

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’tuseWindowListenerinsameclasssowedefinedtwoclassesoneforframe&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 underlyingwindow system.Other component types notablyapplets,frames,panelsandcanvaseshavenointrinsicappearance.Ifweuseanyoftheseclassesotherthansimplyascontainersandwantourcomponenttolookatalluseful,wewillhavetoprovidethecodethatimplementsthecomponentsappearance.

Everycomponenthasagraphicscontextassociatedwithit.Thegraphicscontextcorrespondencetotheframebufferrelatedtothecomponent.

We can draw on the component using methods supported by the GraphicsContext.AnythingdrawnontheGraphicscontextappearsonthecomponent.

The correct approach for painting on any component is to override its paint( )methodandprovidetheappropriatecode.

The paint( )method has one argument of typeGraphics, which represents theGraphicsContextofthecomponent.Itisalsopossibletodrawonthecomponentwithoutusingpaint()methodalthoughthisapproachisnotrecommended.

Thepaint()methodandtheGraphicsContext:

Oneinterestingpointabouttheframeinthefollowingexampleisthatnoexplicit

callsmadetothepaint()method;themethodissimplyprovided.Theenvironmentseemstodoagoodjobofcallingpaint()attherightmoment.

PaintingonacomponentisaccomplishedbymakingcallstoaGraphicscontext,whichisaninstanceoftheGraphicsclass.Agraphicscontextknowshowtorenderontoasingletarget.ThethreemediaaGraphicsContextcanrenderontoare:

1. Components.

2. Images.

3. Printers.

Any Kind of component can be associated with a Graphics context. Theassociationispermanent;acontextcannotbereassigned toanewcomponent.Althoughwecanusegraphicscontextstopaintontoanykindofcomponent,itisunusualtodosowithcomponentsthatalreadyhaveanappearance.

Buttons,Choices,Checkboxes,Labels,Scrollbars,TextFields,andTextAreasdonotoftenrequireprogrammerlevelrendering.Mostoften,thesecomponentsjustusetheversionofpaint()thattheyinheritfromthecomponentsuperclass.

This version does nothing; the components are rendered by the underlyingwindow system. However, there are four classes of “blank” components that have nodefaultappearanceandwillshowupasemptyrectangles,unlesstheyaresub-classedandgivenpaint()methods.

Thesefourcomponentclassesare:

Applet.

Canvas.

Frame.

Panel.

Example19.1 The FrameClass is extended and paint() methods is over-ridden tochangetheappearanceoftheframe.

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,passinginanappropriateinstanceofGraphics.

Operationssupportedbythegraphicsclass

Thefourmajorcategoriesofoperationsprovidedbythegraphicsclass(graphicscontext)are:

Selectingacolor.

Selectingafont.

Drawingandfilling.

Clipping.

Selectingacolor:

Colors are selected by calling the setcolor()method.The required argument is aninstanceofthecolorclass.

There are 13 pre-defined colors, accessible as static final variables of the colorclass.

(The variables are themselves instance of the color class. Which makes somepeopleuneasy,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

Ifwewant a color that is not on this list,we can construct our own.There are severalversionofthecolorconstructor,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)

Codefragmentbelowlists thefirstpartofapaint()methodthatsetsthecolorofitsgraphicscontexttopalegreen:

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 thecolorofanythingthathasalreadybeendrawn;itonlyaffectsubsequentoperations.

SelectingaFont:

Setting the fontofagraphicscontext is like setting thecolor subsequent stringdrawingoperationswillusethenewfont,whilepreviouslydrawnstringsarenotaffected.Beforewecansetafont,wehavetocreateone.Theconstructorforthefontclasslookslikethis:

Font(stringfontName,intstyle,intsize)

The first parameter is the name of the font. Font availability is platformdependent.Wecangetalistofavailablefontnames,returnedasanarrayofstrings,bycallingthegetFontList()methodonourtoolkitlikethis:

StringfontNames[]=Toolkit.getDefaultToolkit().getFontList();

Thereare threefontnames thatareplatformindependentand thatweareencouraged touse:

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,bypassingthesumifstyles,likethis:

Font.BOLD+Font.ITALIC

Drawingandfilling:

All the renderingmethods of graphics class specify pixel co-ordinate positionsfortheshapestheyrendereverycomponenthasitswonco-ordinatespace,withtheorigininthecomponent’supper-leftcorner,xincreasingtotherightandyincreasingdownward.Followingfigureshowsthecomponentco-ordinatesystem:

Thegraphicscontext classdoesnothaveanextensive setofpaintingmethods.(SophisticatedrenderingishandledbyextendedAPIssuchas2d,3d,andanimation.)

Themethodsinthegraphiccontextclassthatweneedtoknowaboutare:

voiddrawLine(intx1,inty1,intx2,inty2)

Drawsa line,using thecurrentcolor,between thepoints (x1,y1)and (x2,y2) in thisgraphicscontext’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.Theovalliesinsidetheboundingboxandistangenttoeachofthebox’ssidesatthemid-pointasshownbelow:

To draw a circle, use a square-bounding box. Note that the painting only drawsforegroundpixels,notbackground,sothespaceinsidetheboundingboxbutoutsidetheovalisleftunchanged.Herexandyaretheco-ordinatesoftheupperleftcorneroftheboundingbox,andwidthandheightarethewidthandheightofthebox.

voiddrawArc(intx,inty,intwidth,intheight,intstartAngle,intarcAngle)

Drawtheoutlineofacircularorellipticalarccoveringthespecifiedrectangle.

voidfillArc(intx,inty,intwidth,intheight,intstartangle,intarcangle)

Fillsacircularorellipticalarccoveringthespecifiedrectangle.

Anarcissegmentofanoval.Thespecifyanarc,wefirstspecifytheoval’sboundingbox,justaswedowithdrawOval()andfillOval().Wealsoneedtospecifythestartingandendingpintsofthearc,whichwedonyspecifyinganstartingangleandtheanglesweptoutbythearc.

Afilledarcisregionboundedbythearcitselfandthetworadiifromthecenteroftheovaltotheendpointsofthearc.

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 arepassedtothedrawPolygon()andfillPolygon()methodsastwointarrays.Thefirstarraycontainsthexco-ordinatesofthevertices,thesecondarraycontainstheyco-ordinates.Athirdparameterspecifiesthenumberofvertices.

Note:endpointisjoinedwiththefirstpoint.

voiddrawPolyLine(int[]xPoints,int[]yPoints,intnPoints)

Drawsasequenceofconnectedlinesdefinedbyarrayofxandycoordinates.

Apolyline is similar toapolygon ,but it isopen rather that closed.There isno linesegmentconnectingthelastvertextothefirst.

voiddrawString(Stringstr,intx,inty)

Drawsthetextgivenbythespecifiedstring,usingthisgraphicscontext’scurrentfontandcolor.Thex,yparametersspecifytheleftedgeofthebaselineofthestring.The

characterswithdescenders(g.j,p,q,andyinmostfonts)extendbelowthebaseline.

Thefactthattext-coordinatesarerelativetothebaselineisimportant.Inasimpletext,forexample,wemighttrytodrawastringat(0,0)expectingittoappearatthetopleftofthespace.However,becauseofthebaseline,wewillonlyseethedescendersofthestring,whichmightmeanthatweseenothingatall.

Bydefault,agraphicscontextusesthefontoftheassociatedcomponenthowever,wecansetadifferentfontbycallingthegraphicscontext’ssetFont()method.

booleandrawImage(Imageimg,intx,inty,ImageObserverobserver)

Drawsasmuchofthespecifiedimageasiscurrentlyavailable.

Here, im is the image to be rendered, and x and y are the coordinates within thedestinationcomponentoftheupper-leftcorneroftheimage.Theimageobservermustbeanobjectthatimplementstheimageobserverinterface.

An image is an off-screen representation of a rectangular collection of pixel values.Java’simagesupportiscomplicated.

Fornow,assumethatwehavesomehowobtainedanimage(thatis,aninstanceofclassjava.awt,image) thatwewant torender to thescreenusingacertaingraphicscontext.Thewaytodothisistocallthegraphicscontext’sdrawImage()method.

Example19.2:

This example illustrates how to create an image and then draw on it using itsgraphics context . the image can then be displayed in the applet window usingdrawImage()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.Theimagecanthenbedisplayedintheappletwindowusingdrawimage()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:

Mostcallsthatprogrammersmakeongraphicscontextinvolvecolorselectionordrawingand filling.A lesscommonoperation is clipping.Clipping is simply restrictingtheregionthatagraphicscontextcanmodify.

Every graphics context that is, every instance of the graphics class has a clipregion,whichdefinesallorpartof theassociatedcomponent.Whenwecalloneof thedrawXXX()orfillXXX()methodofthegraphicsclass,onlythosepixelsthatliewithinthegraphicscontext’sclipregionaremodified.

Thedefaultclip regionforagraphicscontext is theentirevisible regionof theassociatedcomponent.Therearemethodsthatretrieveandmodifyaclipregion.Considerthefollowingpaintmethod.

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.Considerwhathappenswhenthis is the paint( ) method of an applet/ frame that is 200 * 200 pixels. Because loopcountersgoallthewayupto500,themethodattemptstodrawoutsidetheboundsoftheapplet/frame.

Thisisnotaproblem,becausethegraphicscontextbydefaulthasaclipregionthatcoincideswiththeapplet/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*300appletframeasshownabove.

ClippingisgoodtoKnowaboutinitsownright.Clippingalsocomesintoplaywhentheenvironmentneedstorepairexposedportionsofacomponent.

Summaryaboutthepaint()methodandthegraphicscontext:

AGraphicscontextisdedicatedtosinglecomponent.ToPaintonacomponent,wecall thegraphicscontext’sdrawXXXX()andfillXXXX()methods.Tochangethecolororfontofgraphicsoperations,wecallthegraphicscontext’ssetColor()orsetFont()methods,respectively.

GuIThreadandpainting:

TheJavaruntimeenvironmentcreatesandcontrolsitsownthreadsthatoperatebehindthescreanes,andoneofthethreadsisresponsibleforGUImanagement.

TheGUIthreadistheenvironment’stoolforacceptinguserinputeventsandforcallingthepaint()methodofcomponentsthatneedpainting.

Call topaint ( ) arenot all generatedby the environment. Javaprograms canof coursemaketheirowncalls,eitherdirectlyorindirectlyviatherepaint()method.

Itisalsopossibletodrawonacomponentusingitsgraphicscontext.Thereisnoneedtocallpaint()orrepaint()methodinthisapproach.

Differentapproachesfordrawingonacomponentareasfollows:

(i) DirectlydrawingafterobtainingGraphicsContextthecomponent.

(ii) Spontaneous painting (paint ( ) method is calledimplicitly/automaticallybyGUIthread)

(iii)Explicitlyinvokingpaint()method

(iv) Explicitly invoking repaint ( )method,which thenindirectlyinvokeshepaint()method().

DirectlydrawingafterobtainingGraphicsContextofthecomponent:

Sinceitispossibletogetareferencetoacomponent’sGraphicscontextusingthemethodgetGraphics(),itistemptingtobelievethatonecansimplydrawtoacomponentfromanyconvenientmethod.Generallythisapproachisseriouslyflawed.

Supposewehaveanapplet thatwants todrawa reddotat thepointof themost recentmouseclick.T

heremainderof theappletshouldbeyellow.Assumethat theapplet ishandlingitsownmouseevents.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.}

If thisappletevergetscoveredandexposed,theGUIthreadwillimplicitlycallpaint ( ), unfortunately, paint ( ) doesnotKnowabout the red circle thatwasdrawn inmethodmouseClicked(),sotheredcirclewillnotberepaired.

Theproperplaceforalldrawingoperationsis inpaint(),or inmethodscalledfrompaint ( ); this techniqueensure that theGUI threadwillbeable to repairexposuredamage.TheGUIthreadexpectspaint()tobeabletocorrectlyreconstructthescreenatanyarbitrarymoment.

One possible way to achieve this is to remove all drawing code from eventhandlersandothearbitrarymethodsandplacethatcodeintothepaint()method.

Next, when a method needs to draw, arrange for it to write to variables thatdescribethedescribethedesireddrawing,sothatthosevariableareaccessibletothepaint()methodandcanbeusedbythepaint()methodtoperformthedrawing.

Now when the paint ( ) methods gets called, whether by one of our generalmethods,orbytheGUIthread,itcandrawwhateverwasoriginallyintended.

Spontaneous Painting ( paint() method is called implicitly/automatically by GUIthread):

Spontaneous painting is not an official Java term, but it gets the point across.Somepaintinghappensbyitself,withnoimpetusbytheprogram.Forexample,aseveryintroductory

Javabookexplains,whenabrowserstarts-upanapplet,shortlyaftertheinit()methodcompletes,callismadetothepaint()method.Also,whenpartorallofabrowseroraframeiscoveredbyanotherwindowandthenbecomesexposedacallismadetothepaint()methodsoastorefreshtheappletwindow.

It is the GUI thread that executes these calls to paint ( ). Every applet and everyapplicationthathasaGUI,hasaGUIthread.

TheGUIthreadspontaneouslycallspaint()wheneverallorpartofacomponentneedsredrawingafteranyofthefollowingevents:

Afterexposure.

Afterde-iconification.

Afterfirstdisplay.

Whenabrowserreturnstoapreviouslypagecontaininganapplet,providedthatapplet is at least partially visible.When theGUI thread calls paint ( ), itmust supply agraphics context, since the paint ( ) method’s input parameter is an instance of theGraphicsclass.

Anearliersection(“clipping”)discussedthefactthateverygraphicscontexthasa clip region. TheGUI threadmakes sure that the graphics contexts that get passed topaint ( ) have their clip regions appropriately set.Most often, the default clip region isappropriate.

However, when a component is exposed, the clip region is set to be just thatportionofthecomponentthatrequiresrepair.Ifonlyasmallpieceofthecomponentwasexposed,thentheclipregionensuresthatnotimeiswasteddrawingpixelsthatarealreadythecorrectcolor.

Ifanexposedregionisnon-rectangular,thenmultiplecallstopaint()mightoccur,withtheclipregionofeachsuccessivelybuildinguptoensurethatthewholeexposedareagetsrepaintedeventually.

Explicitlyinvokingpaint()method:

The component may not get refreshed if the drawing operations on it areperformed inamethodother than thepaint ( )method. Ifdrawing isdone in thepaintmethod() thenitgetsdisplayedwhenwecall thepaint()methodexplicitlyaswellaswhenthepaint()methodiscalledimplicitlyGUIthread.

The mouse Clicked ( ) method of the previous example is rewritten so that it simplymodifiestheinstancevariablesmouseXandmouseYwhenevermouseclickhappens.

Thereddoisdrawninthepaint()methodonlysothatitgetsrepairedevenifappletgetscoveredandexposed.

Example19.7:

The example in the previous section is modified so that the components display getsrefreshedinthesituationsdescribedabove.Thishappensbecausethereddotisdrawninthepaint()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 theGUI thread is calling thepaint ( )method as andwhen it needs to It occurs when exposure needs to be handled. This can cause threadinteractionissues.

Tobe fair,wewill see thatwemight have to handle someof these issues anyway,evenwhenusingthepreferredapproach,sincethepaint()methodwillusedatathatwearemodifying inother threads.However,wewillminimize theproblemifweallowpaint()tobecalledonlyintheGUIthread.

TheSecondproblemisoneofCPUusage.Considerthisscenario:ourprogramisgetting regular notification that it should update the display with the next frame of ananimationorsimilarcontinuouslymovinggraphic.

Alsosupposethatthedrawingiscomplexandtime-consuming.Itwesimplycallthewholepaint()method,wemightbeonlypartwaythroughthedrawingwhenframetriggeroccurs.

Thiswould result in our program spending.Or trying to spend, all its time indrawingFurther,thedrawingwouldgetfurtherandfurtherbehindwhereitshouldbe.

Theseproblemscanbedealt simplybyusing thepreferredmethodofhandlingprogram initiated drawing. The idea is that the main program maintains data set thatdescribes thedrawing thatshouldbepresented to theuser,butdoesnotdirectlycall thedrawingroutines.

Instead, the program requests that the GUI thread should run the paintingroutines,inbroadlythesamewaythatthreadwoulddoifitwerehandlingexposure.

TheGUIthreadusesthedatasetpresentedbymainprogramtodecidewhatandhowtodraw.

To support this approach, theGUI systemprovides amethod called repaint( ).ThismethodisdefinedintheComponentclass,andsoisavailableonanythingvisibleinaGUI.Whenwecallthismethod,weareissuingarequesttotheGUIthreadthatitshouldperformthepaintingsystemroutines.

TheGUI threaddoessowithina reasonable timescale,although thismightbelimited by other high- priority thread activity.This approach ensures that the threadinteractionsbetweentheGUIthreadanduserthreadsareminimized.

Wemust,naturally,ensurethatourdatasetisneverusedbytheGUIthreadwhilethatdataisinaninconsistentstate.However,thiscanbeachievedquiteeasilyusingeithersynchronizationordoublebufferingtechnique.

Anotherconsequenceofthisbehavioristhat,nomatterhaowmuchdrawingtheprogramtriestodo,thesystemgenerallyremainssynchronizedwithcurrentframe.

Thishappensbecause ifwe 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 singleexecutionofthepaintingsystem.

Therefore, in overloaded conditions, the painting system automatically skipsframesthat thehostCPUsimplycannotdealwith.Thismeansthat theprogrammercanwritecodethatreliablygetsthebestavailablevideoperformanceonagivenplatform,butstillworkstolerablywellonanyotherplatform.Thefollowingcodeimplementsthiskindofscheme.

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,regardlessofhowfrequentlytheeventhandleriscalled,callstopaint()willnotoutstripthesystem’sabilitytodraw,andtheprogramcannotfallincreasinglybehind.

The previous code shows the essence of the preferred approach to programinitiateddrawing.Themainprogramstoresinformationinistancevariablesandthencallstherepaint()method.

Therepaint()methodrequeststhattheGUIthreaddrawsthescreen.TheGUIthreaduses thepaint ( )method todo thedrawing,and thatmethodshouldperformthedrawingaccordingtotheinformationintheinstancevariable.

Thebenefitsofthisapproachare:

Thescreeniscorrectlyrepairedwhentheenvironmentspontaneouslycallspaint().

The thread interactions,between foreground threads trying todrawand theGUI thread,arecontrolledandpredictable.

Thevirtualmachineisneveroverwhelmedbypainting.

When all the code is written this way, there are no surprises for otherprogrammerstryingtodebugthecode.

Although this approach works well, there is a situation where still furtherimprovementisneeded:animation.Ifweusetheapproachexactlyasdescribed,wewillprobablynoticethatananimationflickersunpleasantlywhileitruns.

SmoothAnimation:

One featureof thedefaultbehaviorof the repaintingmechanism thatwemightnotalwayswant is that the systemclearsourdrawingareaaspartof thepreparation torespond to our call to repaint ( ). This can make animations and another real timedrawings flicker unpleasantly. It turns out thatwhenwe call repaint( ), theGUI threaddoes not call paint ( ); instead it calls the update ( )method. The default behavior ofupdate()istodotwothings.Clearthebackgroundandthencallpaint.Likethis:

publicvoidupdate(Graphicsg)

{

g.clearRect(0,0,width,height);

paint(g);

}

Wemight reasonably ask why repaint () starts by clearing the window if thiscauses flickering.Well, inmany cases, drawings are done using lines, rectangles, ovalsandsoforthdrawnonabackground.

Ifwearetryingtomakeaspinningstick,weneedtoremovetheoldlinebeforewedrawthenewone.Anotherwaytothinkaboutthisistoconsiderthatifwearetryingtodrawanewdrawing,weshouldfirsterasetheoldone.

So,howcanwearrangefor thenewdrawing toappearwithouthaving toclearthewholedisplayfirst?Wesimplyneedtofindanotherwaytoremovetheolddrawing.Thegeneralapproachistoensurethatwedrawthewholedrawing-bothbackgroundandforeground each timewedrawa frame. Ifwe can arrange this, thenwedonot need toclearthecomponent,andtheflickeringgoesaway.

To prevent the component being cleared before paint ( ) is called, we simplyoverridetheupdate()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 tohandlethisistouseanoffscreenimagetostoreadrawingofwhatshouldbeshownonthedisplay.

Thistechniqueisnotalwaysthemostefficient,ineitherspeedormemoryterms,but it is simple and easy to implement, and generally well understood by Javaprogrammers.

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), itimplicityextendbuilt-inObjectclass.Thusthefeaturesofthisclasswillbeavailableinalltheclasses.

MethodsinObjectclass:

Theobjectclassdefinesfollowingmethods,whichareinheritedbyalltheclasses.

1. publicinthashCode()2. publicbooleanequals(Objectobj)3. publicfinalClassgetClass()4. publicStringtoString()5. protectedvoidfinalize()throwsThrowable6. protectedObjectclone()throwsCloneNotSupportedException

7. publicfinalvoidwait(longtimeout)throwsInterrputedException8. publicfinalvoidwait(longtimeout,intnanos)throwsInterrputedException9. publicfinalvoidwait()throwsInterrputedException10. publicfinalvoidnotify()11. publicfinalvoidnotifyAll()

1.publicinthashCode():

Whenstoringobjects inhash tables, thismethodcanbeused togetahashvalue foranobject.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 classjava.lang.Classatruntime.

Example20.1:Thefollowingexample illustrates that thismethodcanbeused toget theClassobjectcorrespondingtoanyjavaobject.WecanthenusemethodsoftheclassClasstogetinformationabouttheobject’sclassusingreflection/introspection.getMethods()andgetFields() will display all the public members only, but get DeclaredMethods() andgetDeclaredFields()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.Stringjava.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)throwsjava.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.Stringjava.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.Stringjava.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)throwsjava.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.Stringjava.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:

Thepreviousexampleismodifiedsoastoreadthefullyqualifiedclassnameascommandlineargumentandthendisplaytheinformationabouttheclass’smethodsandfieldsusingreflection/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,itreturnsatextualrepresentationoftheobject,whichhasthefollowingformat:

“<nameoftheclass>@<hashcodevalueofobject>”

Themethodisusuallyoverriddenandusedfordebuggingpurposes.Themethodcall System.out.println(Objref) will implicitly convert its argument to a textualrepresentationusingtoString()method.

Example20.3:

ThisexampledemonstrateswhatgetsdisplayedifwetrytodisplayobjectofclassBox.theobjectisconvertedtothetextualrepresentationusingthetoStringmethodoftheobjectclass.

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()methodintheBoxclassthentheoverriddenmethodisusedtoconverttheobjecttoitstextualrepresentation.

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,sothatanycleaningupcan be done. However, the default finalize() method in the object class does not doanything useful. This may be useful for releasing non-java resources but notrecommended.Itispossiblethatfinalize()methodmayneverbecalledifenoughmemoryisavailableandinthatcaseresourcesmayneverbereleased.

6.protectedObjectclone()throwsCloneNotSupportedException

Newobjects that are exactly the same (i.e. have identical states) as the currentobjectcanbecreatedbytheclone()method,thatis,primitivevaluesandreferencevaluesarecopied,thisiscalledshallowcloning.

Aclasscanoverridetheclone()methodtoprovideitsownnotionofcloning.Forexample,cloningacompositeobjectbyrecursivelycloningtheconstituentobjectiscalleddeepcloning.Whenoverridden,themethodinthesubclassisusuallydeclaredpublictoallowanyclienttocloneobjectsoftheclass.

Ifoverridingclone()methodreliesontheclone()methodintheObjectclass,thenthesubclassmustimplementthecloneablemarkerinterfacetoindicatethatitsobjectscanbesafelycloned.Otherwise,theclone()methodintheObjectclasswillthrowacheckedCloneNotSupportedException.

Usingclone()andtheCloneableinterface:

Theclone()methodgeneratesaduplicatecopyoftheobjectonwhichitiscalled.Thesearefewimportantfactsrelatedtoclone()method:

Only classes that implement the Cloneable interface can be cloned. TheCloneableinterfacedefinesnomembers.Itisusedtoindicatethataclassallowsabit-wisecopyofanobject(thatis,aclone)tobemade.

Ifyoutrytocallclone()onobjectofaclassthatdoesnot implementcloneableinterface,CloneNotSupportedExceptionisthrown.

Cloneableinterfaceisanemptyinterface.Suchaninterfaceiscalledmarker/taginterface.Whenacloneismade,theconstructorfortheobjectbeingclonedisnotcalled.

A clone is simply an exactly copy of the original. Cloning is potentially adangerousaction,becauseitcancauseunintendedsideeffects.

For example, if the object being cloned contains a reference variable calledobjRef,thenwhenthecloneismadetheobjRefinclonewillrefertothesameobjectasdoesobjRefinoriginal.IftheclonemakesachangetothecontentsoftheobjectreferredtobyobjRef,thenitwillbechangedfortheoriginalobject,too.

Example20.5:

Thefollowingexampledemonstratestheuseofclone()method.TheCloneDemo1classismakingcloneof theobjectof classTestClone1by indirectly calling theclone()methodthroughclone2()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.Noticethattheobjectreturnedbyclone()mustbecastintoitsappropriatetypei.e.TestClone1.

Example20.6:Inthefollowingexample,theclone()methodisoverriddensothatitcanbecalledfromcodeoutsideofitsclass.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

Example20.7: In the following example, the clone()method is overridden such that itdoes notmake use of the clone()method of theObject class.We arewriting our ownclone()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 implementCloneableinterfaceifimplementingyouownclone()method.

SideEffectofCloning-Thesideeffectscausedbycloningaresometimesdifficulttoseeatfirst.Itiseasytothinkthataclassissafeforcloningwhenitactuallyisnot.

In general, you should not implement Cloneable interface for any class without goodreason.

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,objectclassprovidessupportforthreadcommunication in synchronized code through the following methods: Causes currentthreadtowaituntilanotherthreadinvokesthenotify()methodorthenotifyAll()methodforthisobject.

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.Athreadwaitsonanobject’smonitorbycallingoneofthewaitmethods.

Athreadinvokesthesemethodsontheobjectwhoselockitholds.Athreadwaitsfornotificationbyanotherthread.

CHAPTER∞21∞

(CollectionFramework)

Introduction-TheJavaCollectionsframeworkstandardizesthewayinwhichgroupofobjects

arehandledbyyourprograms.PriortoJava2,JavaprovidedadhocclassessuchasVector,Stack,Dictionary,HashtableandPropertiestostoreandmanipulategroupsofobjects.

Although theseclasseswerequiteuseful, they lackedacentralunifying theme.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 followingobjectives:

The Framework has to be high-performance. The implementations for thefundamentalcollections(dynamicarrays,linkedlists,trees,andhashtables)arehighlyefficient.

TheFrameworkhas toallowdifferent typesofcollections towork inasimilarmannerandwithahighdegreeofinteroperability.

Extendingand/oradaptingtoacollectionhadbeeneasy.Toachievetheabovegoals,thecollectionframeworkdesignthefollowingfeatures:

EntireCollectionframeworkisdesignedaroundasetofstandardinterfaces.Theseveralstandardimplementationsoftheseinterfacesareprovided.Wemayalsoimplementourowncollection.

Another itemcreatedby thecollections framework is the Iterator interface.AnIteratorgivesyouageneral-purpose,standardizedwaysofaccessingtheelementwithinacollection,oneatatime.

Thus,anIteratorprovidesameansofenumerating thecontentsofacollection.BecauseeachcollectionimplementIterator, theelementsifanycollectionclasscanbeaccessed throughthemethodsdefinedbyIterator.This,withonlysmallchanges,thecodethatcyclethroughasetcanalsobeusedtocyclethroughalist,forexample.

In addition to collections, the framework defines several map interfaces andclasses.Maps storekey/valuepairs.Althoughmaps arenot “collection” in theproperuseoftheterm,theyarefullyintegratedwithcollections.

Inthelanguageofthecollectionframework,wecanobtainacollectionviewofmap. Such a view contains the elements form themap stored in a collection.Thus,wecanprocessthecontentsofamapasacollection,ifyouchoose.

Thecollectionmechanismwasretrofittedtosomeoftheoriginalclassesdefinedbyjava.utilpackage,sothattheytoocouldbeintegratedintothenewsystem.

Itisimportanttounderstandthatalthoughtheadditionofcollectionsalteredthearchitecture of many of the original utility classes, it did not cause thedeprecation of any. Collections simply provide a better way of doing severalthings.

TheCollectionInterfaces:

The collections framework defines several interfaces. The concrete classessimply provide different implementations of the standard interfaces. The interfaces thatunderpincollectionsare:

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 arecompared;IteratorandListIteratorenumeratetheobjectswithinacollection.

By implementing RandomAccess, a list indicates that it supports efficient,randomaccesstoitselements.Toprovidethegreatestflexibilityintheiruse,thecollectioninterfacesallowsomemethodstobeoptional.

The optional methods enable you to modify the contents of a collection.Collectionsthatsupportthesemethodsarecalledmodifiable.Collectionsthatdonotallowtheircontentstobechangedarecalledunmodifiable.

IfanattemptismadetouseoneofthesemethodsonanunmodifiablecollectionanUnsupportedOperationExceprinisthrown.Allthebuilt-incollectionsaremodifiable.

TheIteratorInterface:Iteratorinterfacedefinesthefollowingmethods:

Boolean hasNext()

returnstrueiftheiterationhasmoreelements.

Object next()

returnsthenextelementintheiteration.

void remove()

Removesfromtheunderlyingcollectionthelastelementreturnedbytheiterator(maynotallowtodosoinsomecircumstancesasinEJB’s).itisanoptionaloperation,soitmaythrowUnsupportedOperationException,ifiteratordoesnotsupportthisoperation.

Iteratorsdifferfromenumerationsintwoways:

Iterators allow the caller to remove elements from the underlying collectionduringtheiterationwithwell-definedsemantic.

Methodnameshavebeenimproved.

TheListIteratorInterface:

ThisisasubinterfaceofIterator.

publicinterfaceListIteratorextendsIterator

Itisaniteratorforliststhatallowstheprogrammertotraverse4thelistineitherdirection,modify the listduring iteration,andobtain the iteator’scurrentposition in thelist.

Methodsummary:

voidadd(Objectobj)

Insertsthespecifiedelementintothelist(optionaloperation).

booleanhasNext()

Returnstrueifthislistiteratorhasmoreelementswhentraversingthelistintheforwarddirection.

booleanhasPrevious()

Returnstrueifthislistiteratorhasmoreelementswhentraversingthelistinthereversedirection.

Objectnext()

Returnthenextelementinthelist.

intnextIndex()

Returnstheindexiftheelementthatwouldbereturnedbyasubsequentcalltonext.

Objectprevious()

Returnthepreviouselementinthelist.

intpreviousIndex()

Returns the index if the element that would be returned by a subsequent call toprevious.

voidremove()

Removefromthelist thelastelementthatwasreturnedbynextorprevious(optionaloperation).

voidset(Objectobj)

Replaces the last element returned by next or previous with the specified element(optionaloperation).

RandomAccessInterface:

This isamarker interfaceusedbyList implement to indicate that they supportrandomaccess.TheArrayListandVectorimplementthisinterface.

TheComparatorInterface:

Comparators are used to control the order of certain data structures(such as TreeSet ofTreeMap).

Methods:

Int compare(Objecto1,Objecto2)

Comparesitstwoargumentsfororder.

Boolean equal(Objectobj)

Indicatewhathersomeotherobjectis“equalto”thisComparator.

TheCollectionInterface:

Thecollectioninterfaceisthefoundationuponwhichthecollectionsframeworkisbuilt.Itdeclaresthecoremethodsthatallcollectionswillhave.Becauseallcollectionsimplement collection interface, familiarity with its methods is necessary fir a clearunderstanding of the framework. Several if thse methods can throw anUnsupportedOperationException.AClassCastException isgeneratedwhenoneobject isincompatiblewithanother,suchaswhenanattemptismadetoaddanincompatibleobject

toacollection.

MethodsintheCollectionInterface:

booleanadd(Objectobj)

Ensures that this collection contains the specified element (optional operation).Addsobject to the invoking collection. Returns trueif ekement obj was added to thecollection.Returnsfalseifelementobjiosalreadyamemberofthecollectionandthecollectiondoesnotallowduplicate.

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 theelement that are alsocontained in the specified collection (optionaloperation)

booleanretainAll(Collectionc)

Retains the element of this collection that are contained in the specified collection(optionaloperation).

intsize()

Returnsthenumberofelementsinthiscollection.

Object[]toArray()

Returnsanarraycontainingalloftheelementsinthiscollection.

Twocollections canbecompared for equalitybycallingequals()method.Theprecisemeaningof“equality”maydifferfromcollectiontocollection.

For example, you can implement equals() so that it compares the values ofelemensstored in thecollection.Alternatively,equals()cancompare references to theseelements.

TheListInterface:

Alistisanorderedcollectionaksiknownassequence.TheListinterfaceextendsCollectionanddeclaresthebehaviorofacollectionthatstoresasequenceofelements.

Elements can be inserted or accessed by their position in the list, using a zerobasedindex.Alistmaycontainduplicateelements.Inadditiontothemethodsdefiedbycollection,Listdefinessomeofitsown.

MethodsintheListInterface:

booleanadd(Objecto)

Appendsthespecifiedelementtotheendofthislist(optionaloperation).Themethodisdefined in the Collection interface but as part of the List interface it should beimplementedsoastoalwaysaddtheelementattheendofthelist.

voidadd(intindex,Objectelement)

Inserts the specifiedelement at the specifiedposition in this list (optionaloperation).Anypre-existingelements atorbeyond thepointof insertion are siftedup.Thus,noelementsareoverwritten.

booleanaddAll(Collectionc)

Appendsalloftheelementinthespecifiedcollectiontotheendofthislist,intheorderthat thet are returned by the specified collections iterator(optional operation). ThemethodisdefinedintheCollectioninterfacebutaspartoftheListinterfaceitshouldbeimplementedsoastoalwaysaddtheelementattheendofthelist.

booleanaddAll(intindex,Collectionc)

inserts all of the elements in the specified collection into this list at the specifiedposition(optionaloperation).Returnstrueiftheinvokinglistchangesandreturnsfalseotherwise.

booleanaddAll(intindex,Collectionc)

Inserts all of the elements in the specified collection into this list at the specitiedposition(optionaloperation).Returnstrueiftheinvokinglistchangesandreturnsfalseotherwise.

Objectget(intindex)

Returnstheelementatthespecifiedpositioninthislist.

intindexOf(Objecto)

Returnstheindexinthislistofthefirstoccurrenceofthespecifiedelement,or-1iflistdoesnotcontaintheelement.

intlastIndexOf(Objecto)

Returnstheindexinthislistofthelastoccurrenceofthespecifiedelement,or-1iflistdoesnotcontaintheelement.

ListIteratoriterator()

Returnsalistiteratorofelementsinthislist(inpropersequence).

ListIteratoriterator(intindex)

Returns a list iterator of elements in this list (in proper sequence), starting at thespecifiedpositioninthislist.

Objectremove(intindex)

Removestheelementsatthespecifiedposition(optionaloperation)andreturnsdeletedelement.Theresultinglistiscompacted.Thatis,theindexesofsubsequentelementaredecrementedbyone.

Objectset(intindex,Objectelement)

Replaces the element at the specified position in this list with the specified element(optionaloperation).

ListsubList(intfromIndex,inttoIndex)

Returnsalistthatincludeselementsfromstarttoend-1intheinvokinglist.Elementsinthereturnedlistarealsoreferencedbytheinvokingobject.

Note:thatseveralofthesemethodswillthrowanUnsupportedOperationExceptionifthecollectioncannotbemodified,andaClassCastExceptionisgenerated,whenanobjectisincompatibleobjecttoacollection.

Semantics of add(Object o) and addAll(Collection c) methods defined by collectioninterfaceischangedbylistsothattheyaddelementstotheendofthelist.

TheSetinterface:

TheSetinterfacedefinesaset.ItextendsCollectionanddeclaresthebehaviorofacollectionthatdoesnotallowduplicateelements.

Therefore,add()methodreturnfalseifanattemptismadetoaddduplicateelementstoaset.Itdoesnotdefineanyadditionalmethodsofitsown.

TheSortedSetInterface:

TheSortedSetinterfaceextendsSetanddeclaresthebehaviorofasetsortedinascendingorder.

Comparatorcomprator()

Returns the coparator associated with this sorted set, or null if it uses its elementsnaturalordering.

Objectfirst()

Returnthefirstelementinthissortedset.

SortedSetheadSet(ObjecttoElement)

Returns a viewof the portion of this sorted setwhose elements are strictly less thantoElement.

Objectlast()

Returnsthelastelementinthissortedset.

SortedSetsubSet(ObjectfromElement,ObjecttoElement)

Returns a view of the portion of this sorted set whose elements range fromfromElement,inclusive,totoElement,exclusive.

SortedSettailSet(ObjectfromElement)

ReturnsaviewoftheportionofthissortedsetwhoseelementsaregreaterthanorequaltofromElement.

Several methods throw a NoSuchElementException when no items arraycontained in the invoking set. A ClassCastException is thrown when an object is

incompatiblewiththeelementsinaset.ANullPointerExceptionisthrownifanattemptismadetouseanullobjectandnullisnotallowedintheset.

CollectionClasses:

Someof thecollectionclassesprovede full implementation that canusedas is.Othersareabstract,providingskeletonimplementationthatareusedasstartingpointsforcreatingconcretecollection

Noneofthecollectionclassesaresynchronizedversions.

Thestandardcollectionclassesare:

AbstractCollectionImplementsmostoftheCollectioninterface.

AbstractListExtendsAbstractCollectionandimplementmostoftheListinterface.

AbstractSequenceListExtendsAbstractListforusebyacollectionthatusessequentialratherthanrandomaccessofitselements.

AbstractSetExtendsAbstractCollectionandimplementstheSetinterface.

LinkedListImplementsalinkedlestbyextendingAbsractSuquentialList.

ArrayList Impelments a dynamic array by extending AbstractList. It uses randomaccessofelements.

HashSetExtendAbstractSetforusewithahashtable.

LinkedHashSetExtendsHashSettoallowinsertion-orderiterations.

TreeSetExtendsAbstractSetandimplementSortedSetinterface.Itusesbinarysearchtreetostoreelementsinsortedorder.

Note:- In addition to collection classes, several legacy classes, such as Vector Stack,Hashtablehavebeenreengineeredtosupportcollections.

AccessinganCollectionviaIteratorandListIterator:

Often, youwillwant to cycle through the elements in a collection.By far, theeasiestwaytodothisistoemployaniterator,anobjectthatimplementseithertheIteratorortheListIteratorinterface.

Iterator enables you to cycle through a collection obtaining or removing elements.ListIteratorextendsIteratortoallowbi-directionaltraversalofalist,andthemodificationofelements.

Beforeyoucanaccessacollectionthroughaniterator,youmustobtainone.Eachofthecollectionclassesprovidesaniterator()methodthatreturnsaniteratortothestarofthecollection.Byusingthisiteratorobject,youcanaccesseachelementinthecollection,oneelementatatime.

For collections that implement List, you can also obtain an iterator by callingListIterator. A list iterator gives you the ability to access the collection in either theforwardorbackwarddirectionandyoucanmodifyanelement.Otherwise,ListIteratorisusedjustlikeIterator.

ArrayListClass:

TheArrayListclassextendsAbstractListandimplementstheListinterface.TheArrayListsupportsdynamicarraysthatcangrowasneeded.Injava,standardarrayareofafixedlength.

Afterarraysarecreated,theycannotgroworshrink,whichmeansthatwemustknowinadvancehowmanyelementsanarraywillhold.But,sometimes,wedon’tknowsizeofanarrayuntilrun-time.Tohandlethissituation,thecollectionsframeworkdefinesArrayList.

AnArrayListisavariable-lengtharrayofobjectreferencesthatis,anArrayListcandynamicallyincreaseordecreaseinsize.Arraylistsarecreatedwithaninitialsize.

Whenthesizeisexceeded,thecollectionisautomaticallyenlarged,whenobjectsare removed, the arraymay shrunk.Using generics feature introduced in J2SE5, it ispossibletorestrictthetypeofelementstobeaddedintheArrayList.

Note:-ThelegacyclassVectoralsosupportsdynamicarrays.

Constructors&MethodsofArrayListclass:

publicArrayList(int);

Constructs an empty list with the specified initial capacity. The capacity growsautomaticallyaselementsareaddedtoanarraylist.

publicArrayList();

Constructsanemptylistwithaninitialcapacityoften.

publicArrayList(Collection);

Constructsa listcontaining theelementsof thespecifiedcollection. In theorder theyarereturnedbythecollection’sIterator.

publicvoidtrimToSize();

Conversely, if we want to reduce the size of the array that underlines an ArrayListobjectsothatitispreciselyaslargeasthenumberofitemsthatitiscurrentlyholdingcalltrimTosize()method.

publicvoidensureCapacity(int);

Although the capacity of an ArrayList object increases automatically as objects arestored in it,we can increase the capacity of anArrayList objectmanually by callingensureCapacity()method.Byincreasingitscapacityonce,atthestart,wecanpreventseveral reallocation later.Because reallocationarecostly in termsof time,preventingunnecessaryonesimprovesperformance.

publicintsize();

publicBooleanisEmpty();

publicObjectclone();

publicObject[]toArray();

ObtaininganarrayfromanArrayListwhenworkingwithArrayList,wewillsometimeswant toobtainanactualarray thatcontain thecomtents if the list.Wecando thisbycallingtoArray()method.

Severalreasonsexistwhywemightwanttoconvertacollectionintoanarraysuchas:

Toobtainfasterprocessingtimesforcertainoperations.Topassanarraytoamethodthatisnotoverloadtoacceptacollection.To integrate our newer, collection-based codewith legacy code that does notunderstandcollection.

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

Sumis50TheLinkedListClass:

The LinkedList class extends AbstractSequentialList and implements the List interfaces. It provides alinked-listdatastructure.

Constructors&Methods

publicLinkedList();

Constructsanemptylist.

publicLinkedList(Collection);

Constructsalistcontainingtheelementsifthespecifiedcollection,intheordertheyarereturnedbythecollection’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-BecauseLinkedList implements theList interface, call toadd(Objectobj)appenditemstotheendofthelist,asdocallstoaddLast().Toinsertitemsataspecificlocationusetheadd(intindex,Objectobj)formofadd.

TheHashSetClass:

The HashSet class extends AbstractSet and implements the Set interface. Itcreatesacollectionthatusesahashtableforstorage

Theadvantageofhashingisthatitallowstheexecutiontimeofbasicoperations,suchasadd(),contains(),remove(),andsize()toremainconstantevenforlargesets.

Constructors&OtherMethods:

HashSet()

Constructs a new, empty set, the backing HashMap instance has default initialcapacity(16)andloadfactor(0.75).

HashSet(Collectionc)

Constructsanewsetcontainingtheelementsinthespecifiedcollection.

HashSet(intinitialCapacity)

Constructsanew,emptyset,thebackingHashMapinstancehasspecifiedinitialcapacityandloadfactorwhichis0.75.

HashSet(intinitialCapacity,floatfillRatio)

Constructsanew,emptyset,thebackingHashMapinstancehasspecifiedinitialcapacityandthespecifiedloadfactor.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,becausetheprocessofhashing does not usually lend itself to the creation of sorted sets. If you need sortedstorage,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.TheLinkedHashSetclassmaintainsalinkedlistoftheentriesintheset,intheorderinwhichtheywereinserted.

This is also the order in which they are contained in the string returned bytoString() method when called on a LinkedHashSet object. To see the effect ofLinkedHashSet, try substituting LinkedHashSet for HashSet in the preceding program.Theoutputwillbe:[B,A,E,C,F]Whichistheorderinwhichtheelementswereinserted.

TheTreeSetClass:

TheTreeSetprovidesanimplementationoftheSetinterfacethatusesatreeforstorage.Objectsarestoredinsorted,ascendingorder.Accessandretrievaltimesarequitefast, which makes TreeSet an excellent choice when storing large amounts of sortedinformationthatmustbefoundquickly.

Constructors

Ithasthefollowingconstructors:

TreeSet()

Constructsanew,emptyset,sortedaccordingtotheelementsnaturalorder.

TreeSet(Collectionc)

Constructs a new set containing the elements in the specified collection sortedaccordingtotheelements’naturalorder.

TreeSet(Comparatorc)

Constructsanew,emptyset,sortedaccordingtothecomparator.

TreeSet(SortedSetss)

Constructsanewsetcontainingtheelementsinthespecifiedsortedaccordingtothesameordering.

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 thecomparatorthatdefinespreciselywhat“sortedorder”means.

By default, these classes store their elements by using what java refers to as“naturalordering”,whichisusuallytheorderingthatwewouldexpect.Ifwewanttoorderelementsinadifferentway,thenspecifyacomparatorobjectwhenyouconstructthesetormap.Doing so gives us the ability to govern precisely how elements are storedwithinsortedcollectionsmaps.

The comparator interface defines two methods: compare() and equals () asdiscussedearlier.Thecompare()method,comparestwoelementsfororder:

intcompare(Tobj1,Tobj2)

obj1andobj2aretheobjectstobecompared.

Thismethodreturnszeroiftheobjectsareequal.

Itreturnsapositivevalueifobj1isgreaterthanobj2.

Itreturnsanegativevalueifobj1islessthanobj2.

ThemethodscanthrowaClassCastExceptionifthetypeofobjectsarenotcompatibleforcomparison.

Byoverridingcompare(),youcanalterthewaythatobjectsareordered.

For example, to sort in reverse order, you can create a comparator that reverses theoutcomeofacomparison.

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/valuepairs.Givenakey,wecanfinditsvalue.

Bothkeysandvaluesareobjects.Thekeysmustbeunique,butthevaluemaybeduplicated.Somemapscanacceptanullkeyandnullvalues,othercannot

MapInterfaces:

Mapclassesbasedonthefollowinginterfaces:

MapMapsuniquekeystovalues.

Map.EntryDescribesanelement(akey/valuepair)inamap.

SortedMapExtendsMapsothatthekeysaremaintainedinascendingorder.

TheMapInterface:

TheMapinterfacemapsuniquekeystovalues.GivenakeyandvalueyoucanstorethevalueinaMapobject.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 typeMap.Entry.thismethodprovidesasetviewoftheinvokingmap.

booleanequals(Objecto)

ReturnstrueifoisMapandcontainstheentries,otherwise,returnsfalse.

Objectget(Objectkey)

Returnsthevaluetowhichthismapmapsthespecifiedkey.

inthashCode()

Returnsthehashcodevalueforthismap.

booleanisEmpty()

Returnstrueifthismapcontainsnokey-valuemappins.

SetkeySet()

Returnsasetviewofthekeyscontainedinthismap.

Objectput(Objectkey,Objectvalue)

Associates the specifiedvaluewith the specifiedkey in thismap(optionaloperation),overwritinganypreviousvalueassociatedwiththekey.Retrunsnullifthekeydidnotalreadyexist.Otherwise,theperviousvaluelinkedtothekeyisreturned.

voidputAll(Mapm)

Copiesallofthemappingsfromthespecifiedmaptothismap(optionaloperation).

Objectremove(Objectkey)

Removesthemappingforthiskeyfromthismapifitispresent(optionaloperation).

intsize()

Returnsthenumberofkey-valuemappingsinthismap.

Collectionvalues()

Returnsacollectionviewofthevaluescontainedinthismap.

SeveralmethodsthrowaNoSuchElementExceptionwhennoitemsexistintheinvokingmap.AClassCastExceptionisthrownwhenanobjectisincompatiblewiththeelementsinamap.

ANullPointerExceptionisthrownifanattemptismadetouseanullobjectandnullisnotallowedintheMap.AnUnsupportedOperationExceptionisthrownwhenanattemptismadetochangeanunmodifiablemap.

Mapresolvearoundtwobasicoperationsget()andput().

MapsarenotcollectionsbecausetheydonotimplementtheCollectioninterface,butwecanobtainacollection-viewofthemap.Collection-viewmeansbywhichmapsareintegratedintothecollectionsframework..

TheSortedMapInterface:

TheSortedMapinterfaceextendsMap.Inensuresthattheentriesaremaintainedinascendingorder.

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)

ReturnsaviewoftheportionofthissortedmapwhosekeysaregreaterthanequaltotoKey.,exclusive

SortedMaptailMap(ObjectfromKey)

ReturnsaviewoftheportionofthissortedmapwhosekeysaregreaterthanorequaltofromKey.

Severalmethods throwaNoSuchElementExceptionwhenno itemsare in the invokingmap.AClassCastExceptionisthrownwhenanobjectisincompatiblewiththeelementsinamap.

ANullPointerExceptionisthrownifanattemptismadetouseanullobjectandnullisnotallowedintheMap.

TheMap.EntryInterface:

TheMap.Entry interfaceenablesyou toworkwithamapentry.Recall that theentrySet()methoddeclaredbytheMapinterfacereturnsasetcontainingthemapentries.EachofthesesetelementsisaMap.Entryobject.

MethodSummary:

booleanequals(Objecto)

Compares the specified object with this entry for equality. Returns true if o is aMap.Entryobject,whosekeyandvalueareequaltothatoftheinvokingobject.

ObjectgetKey()

Returnsthekeycorrespondingtothisentry.

ObjectgetValue()

ReturnstheValuecorrespondingtothisentry.

inthashCode()

Returnsthehashcodevalueforthismapentry.

ObjectsetValue(Objectvalue)

Replaces the value corresponding to this entry with the specified value (optionaloperation).AClassCastException is thrown if value is not of the correct type of themap.

ANullPointerExceptionisthrownifvalueisnullandthemapdoesnotpermitnullkey.AnUnsupportedOperationExceptionisthrownifthemapcannotbechanged.

TheMapclasses:

Severalclassesprovideimplementationofthemapinterfaces.

AbstractMapThisclassprovidesa skeleton implementationof themap interface, tominimizetheeffortsrequiredtoimplementthisinterface.

HashMapHashtablebasedimplementationofthemapinterface.ExtendsAbstractMapclass.

TreeMapExtendsAbstractMapandimplementsSortedMapinterfacetouseatree.

LinkedHashMapExtendsHashMaptoallowinsertion-orderiteration.

AbstractMapisasuperclassforallconcretemapimplementations.

TheHashMapclass:

TheHashMapclassusesahashtabletoimplant theMapinterface.Thisallowstheexecutiontimeofbasicoperations,suchasget()andput()toremainconstantevenforlargesets.

Constructors:

TheHashMaphasthefollowingconstructors:

HashMap()

Constructs an empty HashMap with the default capacity(16) and default loadfactor(0.75)

HashMap(intinitialCapacity)

ConstructsanemptyHashMapwiththespecifiedinitialcapacityanddefaultloadfactor(0.75)

HashMap(Mapm)

ConstructanewHashMapwiththesamemappingasthespecifiedMap.

The HashMap class extends AbstractMap and implements Map. It does not add anymethodsofitsown.Youshouldnotethatahashmapdoesnotguaranteetheorderofitselements.

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.ATreeMapprovidesanefficientmeansofstoringkey/valuepairinsortedorder,andtreemapguaranteesthatitselementswillbesortedinascendingkeyorder.

Constructors:

TheTreeMaphasthefollowingconstructors:

TreeMap()

Constructsanemptymap,sortedaccordingtothekey’snaturalorder.

TreeMap(Comparatorc)

Constructsanew,emptymap,sortedaccordingtothegivencomparator.

TreeMap(Mapm)

Constructanewmapwithcontainingthesamemappingasthegivenmap,sortedaccordingtothekeys’naturalorder.

TreeMap(SortedMapm)

ConstructanewmapwithcontainingthesamemappingasthegivenSortedMap,sortedaccordingtothesameordering.

TreeMap implements SortedMap and extends AbstradtMap. It does not define anyadditionalmethodsofitsown.

Example21.7

ThefollowingprogramreworkstheprecedingexamplesothatitusesTreeMap.Thekeyswillbesortedbyfirstname.itispossibletoalterthisbehaviorbyspecifyingacomparatorwhen themap is created, so thatkeysmaybe sortedon last nameor anyotherdesiredorder.

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.LinkedHashMapmaintains a linked list of the entries in themap, in theorder inwhichtheywereinserted.

This allows insertion-order iteration over the map. That is, when iterating aLinkedHashMap,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 ofstoringobject.With theadditionofCollectionby Java2, severalof theoriginal classeswerereengineeredtosupporttheCollectioninterfaces.

Thus, they are fully compatible with the framework. While no classes haveactuallybeendeprecated,onehasbeenobsolete.Ofcourse,whereacollectionduplicatesthefunctionalityoflegacyclass,youwillusuallywanttousethecollectionfornewcode.Ingeneral,thelegacyclassesaresupportedbecausethereisstillcodethatusesthem.

Someofthecollectionclassesaresynchronized,butallthelegacyclassesaresynchronized.Thisactionmaybeimportantinsomesituations.Ofcourse,wecaneasilysynchronizecollectionstoo.

TheEnumerationInterface:

Enumerationinterfacedefinesthemethodsbywhichyoucanenumerate(obtainone at a time) the elements in a collection of objects. The legacy interface has beensupercededbyIterator.

Although not deprecated, Enumeration is considered obsolete for new code.However, it is used by several methods used by legacy classes (such as Vector andProperties), is used by several otherAPI classes, and is recently inwide spread use inapplicationcode.

Enumerationspecifiersthefollowingtwomethods:

BooleanhasMoreElements()

Tests if thisenumerationcontainsmoreelements.Thismethodmustreturn truewhiletherearestillmoreelementstoextract.Andfalsewhenalltheelementshavebeenenumerated.

ObjectnextElement()

Returns the next element of this enumeration if this enumeration object has atleastonemoreelementtoprovide.

TheVectorclass

Vector implements a dynamic array. It is similar to ArrayList, but with twodifferences:

Vectorissynchronized,andVectorcontainsmanylegacymethodsthatarenotpartofthecollectionsframework.

With the advent of collections, Vector was reengineered to extend AbstractList and toimplementtheListinterface.

This means that Vector is fully compatible with collections, and a vector can have itscontentsiteratedbytheenhancedforloop.

Constructors:

TheVectorhasthefollowingconstructors:

Vector()

Constructoranemptyvectorsothatitsinternaldataarrayhassize10anditsstandardcapacityincrementiszero.

Vector(Collectionc)

Constructsavectorcontainingtheelementsofthespecifiedxollectionintheordertheyarereturnedbythecollection’siterator.

Vector(intinitialCapacity)

Constructs an empty vector with the specified initial capacity and with its capacityincrementequaltozero.

Vector(intinitialCapacity,intcapacityIncrement)

Constructsanemptyvectorwiththespecifiedinitialcapacityandcapacityincrement.

Thesizeofextraspaceallocatedduringeachreallocationisdeterminedbythespecifiedincrement. If you do not specify an increment, the vector’s size is doubled by eachallocationcycle.Vectordefinesthreeprotecteddatamembers:

protectedintcapacityIncrement

Theamountbywhichthecapacityofthevectorisautomaticallyincrementedwhenitssizebecomesgreaterthanitscapacity.

protectedintelementCount

ThenumberofvalidcomponentsinthisVectorobject.

protectedObject[]elementData

Thearraybufferintowhichthecomponentsofthevectorarestored.

Inaddition to thecollectionmethodsdefinedby list,Vectorclassdefinesseveral legacymethods.

MethodSummary:

voidaddElement(Objectobj)

Addsthespecifiedcomponentstotheendofthisvector,increasingitssizebyone.

intcapacity()

Returnsthecurrentcapacityofthisvector.

Objectclone()

Returnsacloneofthisvector.

voidcopyInto(Object[]anArray)

Copiesthecomponentsofthisvectorintothespecifiedarray.

ObjectelementAt(intindex)

Returnsthecomponentatthespecifiedindex.

Enumerationelements()

Returnsanenumerationofthecomponentsofthisvector.

voidensureCapacity(intminCapacity)

Increasethecapacityofthisvector,ifnecessary,toensurethatitcanholdatleastthenumberofcomponentsspecifiedbytheminCapacityArgument.

ObjectfirstElement()

Returnsthefirstcomponent(theitematindex0)ofthisvector.

intindexOf(Objectelement)

Searchesfor thefirstoccurrenceof thegivenargument, testingforequalityusing theequalsmethods.

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, andreturnsanindextoit.

voidremoveAllElements()

Removesallcomponentsfromthisvectorandsetsitssizetozero.

booleanremoveElement(Objectobj)

Removesthefirst(lowest-indexed)occurrenceoftheargumentfromthisvector.

voidremoveElementAt(intindex)

Deletesthecomponentatthespecifiedindex.

protectedvoidremoveRange(intfromIndex,inttoIndex)

RemovesfromthislistalloftheelementswhoseindexisbetweenfromIndexinclusiveandtoIndexexclusive.

voidsetElementAt(Objectobj,intindex)

Setsthecomponentatthespecifiedindexofthisvectortobethespecifiedobject.

voidsetSize(intnewSize)

Setsthesizeofthisvector.Ifthenewsizeislessthantheoldsize,elementsarelost.Ifthenewsizeislargerthantheold,nullelementsareadded.

intsize()

Returnsthenumberofcomponentsinthisvector.

ListsubList(intfromIndex,inttoIndex)

Returns a view of the portion of this list between fromIndex inclusive, and toIndexexclusive.

Object[]toArray()

Retumsanarraycontainingalloftheelementsinthisvectorinthecorrectorder.

StringtoArray()

Returnsastringrepresentationofthisvector,containingthestringrepresentationofeachelement.

voidtrimToSize()

Setsthevector’scapacityequaltothenumberofelementsthatitcurrentlyholds.

Because vector implement List, you can use a vector just like you use an ArrayListinstance.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 ofVector that implements a standardLIFO stack. The Stackonly defines the default constructor, which creates an empty stack. Stack includes allmethodsdefinedbyVector,andaddsseveralofitsown.

MethodsSummary:

booleanempty()

Testsifthestackisempty.

Objectpeek()

Returnstheobjectatthetopofthisstackwithoutremovingitfromthestack.

Objectpop()

Removestheobjectatthetopofthisstackandreturnsthatobjectasthevalueofthismethods.AnEmptyStackExceptionisthrownifthestackisempty.

Objectpush(Objectitem)

Pushesanitemontothetopofthisstack.

intsearch(Objecto)

Returnsthe1-basedpositionwhereanobjectisonthisstack.

Example21.9:

The following example creates a stack, pushes several Integer objects onto it and popsthemoffagain:

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 andoperates much like Map. Given a key and value pair, you can store the value in adictionaryobjectoncethevalueisstored,youcanretrieveitbyusingitskey.

Thus, likeamap,dictionarycanbethoughtofasalistofkey/valuepairs.Althoughnotactuallydeprecatedbyjava2,Dictionaryisclassifiedasobsolete,becauseitissupercededbyMap.

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.utilandisaconcreteimplementationofaDictionary.However, Java2 reengineeredHashtable so that it also implements theMapinterface.

Thus, Hashtable is now integrated into the collections framework. It is similar toHashMap,butissynchronized.LikeHashMap.

Hashtablestoreskey/valuepairsinahashtable.WhenusingaHashtable,youspecifyanobjectthatisusedasakey,andthevaluethatyouwanttolinkedtothatkey.

Thekeyisthenhashed,andtheresultinghashcodeisusedastheindexatwhichthevalueisstoredwithinthetable.

Ahashtablecanonlystoreobjectsthatoverridethehashcode()andequals()methodsthataredefinedbytheObjectclass.Mostlystringobjectisusedasthekey,whichalreadyimplementsbothhashCode()andequals().

Constructors:

TheHashtablehasthefollowingconstructors:

Hashtable()

Constructs a new, emptyHashtable with the default initial capacity(11) andloadfactor,whichis0.75.

Hashtable(intinitialCapacity)

Constructsanew,emptyHashtablewiththespecifiedinitialcapacityanddefaultloadfactor(0.75)

Hashtable(intinitialCapacity,floatloadFactor)

Constructs a new, empty Hashtable with the specified initial capacity andspecifiedloadfactor.

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)

CopiesallofthemappingsfromthespecifiedMaptothisHashtablethesemappingswillreplaceanymappingsthatthisHashtablehadforanyofthekeyscurrentlyinthespecifiedMap.

Protectedvoidrehash()

Increasethesizeofthehashtableandrehashesallofitskeys.

Objectremove(Objectkey)

Removesthekey(anditscorrespondingvalue)fromthishashtable.

intsize()

Returnsthenumberofentries(distinctkeys)inthishashtable.

StringtoString()

Returnsastringrepresentationofthishashtableobjectintheformofasetofentries,enclosedinbracesandseparatedbytheASCIIcharacter“,”(commaandspace).

Collectionvalues()

ReturnsacollectionofthevaluescontainedinthisHashtable.

Example21.10:

ThefollowingexampleusesaHashtabletostorethenameofdepositorsandtheircurrentbalance.

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.Itisusedtomaintainlistofvaluesinwhich thekey is aStringand thevalue is alsoa string.Theproperties class isusedbymanyotherJavaclasses.

For example, it is the type of object returned by System getProperties() whenobtainingenvironmentalvalues.

Propertiesclassdefinesthefollowinginstancevariable:

Propertiesdefaults

ThevariableholdsadefaultpropertylistassociatedwithaPropertiesobject.

Constructors:

ThePropertieshasthefollowingconstructors:

Properties()

Createsanemptypropertylistwithnodefaultvalues.

Properties(Propertiesdefaults)

Createsanemptypropertylistwiththespecifieddefaults.

InadditiontothemethodsthatpropertiesinheritsfromHashtable,Propertiesdefinessomemoremethods.Propertiesalsocontainsonedeprecatedmethodsave().Thiswasreplacedbystore()becausesave()didnothandleerrorscorrectly.

Methodsummary:

StringgetProperty(Stringkey)

Returnsthevalueassociatedwithkey.Anullobjectisreturnedifkeyisneitherinthelistnorinthedefaultpropertylist.

StringgetProperty(Stringkey,StringdefaultValue)

Returnsthevalueassociatedwithkey.Adefaultpropertyisreturnedifkeyisneitherinthelistnorinthedefaultpropertylist.

voidlist(PrintStreamout)

Printsthispropertylistouttothespecifiedoutputstream.

voidlist(PrintWriterout)

Printsthispropertylistouttothespecifiedoutputstream.

voidload(InputStreaminStream)

Readsapropertylist(keyandelementpairs)fromtheinputstream.

EnumerationpropertyNames()

Returnsanenumerationofallthekeys.Thisincludesthosekeysfoundinthedefaultproperty,too.

voidsave(OutputStreamout,Stringcomments)

Deprecated.ThismethoddoesnotthrowanIOExceptionifanI/Oerroroccurswhilesaving the property list. The preferredway to save a properties list is via the store(OutputStreamout,Stringcomments)method.

ObjectsetProperty(Stringkey,Stringvalue)

CallstheHashtablemethodput.Returnspreviousvalueassociatedwithkey,ornullifnosuchassociationexists.

voidstore(OutputStreamout,Stringcomments)

Writesthispropertylist(keyandelementpairs) inthispropertiestabletotheoutputstreaminaformatsuitableforloadingintoaPropertiestableusingtheloadmethod.

Example21.11:

Thefollowingprogramcreatesapropertylistinwhichthekeysarethecoursenamesandthevaluesarethedurationofthecourses.

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

OneofthemostusefulaspectsofPropertiesisthattheinformationcontainedinaPropertiesobjectcanbeeasilystoredtoorloadedfromdiskwiththestore()andload().

Atanytime,youcanwriteaPropertiesobject toastreamorreaditback.Thismakespropertylistsespeciallyconvenientforimplementingsimpledatabases.

For example, the following program use a property list to create a simplecomputerized telephone book that stores names and phone numbers.To find a person’snumberyouenterhisorhername.

The program uses the store() and load()methods to store and retrieve the list.Whentheprogramexecutes,itfirsttriestoloadthelistfromafilecalledphonebook.dat.ifthisfileexists,thelistisloaded.Youcanthenaddtothelist.

CHAPTER∞22∞

Java8FeaturesforDevelopersLambdas,Functionalinterface,

Java8isreleasedin18thMarch2014,soit’shightimetolookfortheJava8featuresforthedevelopers.Andnoenoghmaterialisavailableforjava8.ButhereafteralotsofhardworkiamwritingSomeoftheimportantfeaturesintroducedinJava8thatIamlookingforwardtoare:

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. Iwill provide some code snippets forbetterunderstanding,soifyouwanttorunprogramsinJava8,youwillhavetosetupJava8environmentbyfollowingsteps.

Download JDK8 and install it. Installation is simple like other java versions. JDKinstallationisrequiredtowrite,compileandruntheprograminJava.

NOTE: Current Eclipse IDE doesn’t support Java8, so you will have to download itfromefxclipse.orgEclipseforJava8.TherearedifferentversionsforMacOS,WindowsandLinuxsystemswithstablebuilds,sodownloadthelatestoneformostfeatures.

Ijustcheckedtoday(28-July-2014)andEclipseKepler4.3.2SR2packagecanbeusedforJava8.Youneedtodownloaditfirstandtheninstall“Java8supportforEclipseKeplerSR2″pluginfromEclipseMarketplace.Ihavetriedthisanditseemstobeworkingfine.

1.forEach()methodinIterableinterface-

WheneverweneedtotraversethroughaCollection,weneedtocreateanIteratorwhosewholepurposeistoiterateoverandthenwehavebusinesslogicinaloopforeachoftheelementsintheCollection.WemightgetConcurrentModificationExceptionifiteratorisnotusedproperly.

Java 8 has introduced FOREACH method in java.lang.Iterable interface so that whilewriting code we focus on business logic only. FOREACH methodtakes java.util.function.Consumerobject as argument, so it helps inhavingourbusinesslogic at a separate location that we can reuse. Let’s see forEach usage with simpleexample.

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 foriterationandbusinesslogicatseparateplaceresultinginhigherseparationofconcernandcleanercode.

2.defaultandstaticmethodsinInterfaces-

IfyoureadforEachmethoddetailscarefully,youwillnotice that it’sdefined in Iterableinterfacebutweknowthatinterfacescan’thavemethodbody.FromJava8,interfacesareenhanced tohavemethodwith implementation.Wecanuse ‘DEFAULT‘ and ‘STATIC‘keywordtocreateinterfaceswithmethodimplementation.

ForeachmethodimplementationinIterableinterfaceis:

default void forEach(Consumer<?super T>action){Objects.requireNonNull(action);

for (Tt:this){action.accept(t);

}

}

Remember:

WeknowthatJavadoesn’tprovidemultiple inheritance inClasses because itleads to Diamond Problem. So how it will be handled with interfaces now, sinceinterfacesarenowsimilartoabstractclasses.

The solution is that compilerwill throwexception in this scenario andwewillhavetoprovideimplementationlogicintheclassimplementingtheinterfaces.

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”);

}

}

AsyoucanseethatInterface1hasstaticmethodimplementationthatisusedinMYCLASS.LOG() method implementation. Java 8 uses default and static methodsheavily in Collection API and default methods are added so that our code remainsbackwardcompatible.

If any class in the hierarchy has a method with same signature, then defaultmethodsbecomeirrelevant.SinceanyclassimplementinganinterfacealreadyhasObjectassuperclass,ifwehaveequals(),hashCode()defaultmethodsininterface,itwillbecomeirrelevant. Thats why for better clarity, interfaces are not allowed to haveObject classdefaultmethods.

ForcompletedetailsofinterfacechangesinJava8,pleasereadJava8interfacechangesBelow.

Java 8 Interface Changes – static methods, default methods, functionalInterfaces-

OneofthebiggestdesignchangeinJava8iswiththeconceptofinterfaces.PriortoJava7,wecouldhaveonlymethoddeclarationsintheinterfaces.ButfromJava8,wecanhavedefaultmethodsandstaticmethodsintheinterfaces.

Designing interfaces have always been a tough job because ifwewant to addadditionalmethodsintheinterfaces,itwillrequirechangeinalltheimplementingclasses.

Asinterfacegrowsold,thenumberofclassesimplementingitmightgrowtoanextent that it’s not possible to extend interfaces. That’s why when designing anapplication, most of the frameworks provide a base implementation class and then weextenditandoverridemethodsthatareapplicableforourapplication.Let’slookintothedefaultandstaticinterfacemethodsandthereasoningoftheirintroduction.

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.NowwhenaclasswillimplementInterface1,itisnotmandatorytoprovideimplementationfordefaultmethods.Thisfeaturewillhelpusinextendinginterfaceswithadditionalmethods,allweneedistoprovide a default implementation. Let’s say we have another interface with followingmethods:

Interface2.java

packagecom.journaldev.java8.defaultmethod;

publicinterfaceInterface2{

voidmethod2();

defaultvoidlog(Stringstr){

System.out.println(“I2logging::”+str);

}

}

We know that Java doesn’t allow us to extendmultiple classes because itwillresultinthe“DiamondProblem”wherecompilercan’tdecidewhichsuperclassmethodtouse.Withthedefaultmethods,thediamondproblemwouldariseforinterfacestoo.

Because if a class is implementing both Interface1 andInterface2 and doesn’t

implementthecommondefaultmethod,compilercan’tdecidewhichonetochose.

ExtendingmultipleinterfacesareanintegralpartofJava,youwillfinditinthecore javaclassesaswellas inmostof theenterpriseapplicationand frameworks.So tomake sure, this problem won’t occur in interfaces, it’s made mandatory to provideimplementationforcommondefaultmethods.

So if aclass is implementingboth theabove interfaces, itwillhave toprovideimplementationforlog()methodotherwisecompilerwillthrowerror.AsimpleclassthatisimplementingbothInterface1andInterface2willbe:

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:

Defaultmethodswillhelpusinextendinginterfaceswithouthavingthefearofbreakingimplementationclasses.

Defaultmethodshasbridgedown thedifferencesbetween interfaces andabstractclasses.

Defaultmethodswill help us in avoiding utility classes, such as all theCollectionsclassmethodcanbeprovidedintheinterfacesitself.

Defaultmethodswillhelpusinremovingbaseimplementationclasses,wecan provide default implementation and the implementation classes can chosewhichonetooverride.

OneofthemajorreasonforintroducingdefaultmethodsistoenhancetheCollectionsAPIinJava8tosupportlambdaexpressions.

Ifanyclassinthehierarchyhasamethodwithsamesignature,thendefaultmethods become irrelevant. A default method cannot override a methodfromjava.lang.Object.

Thereasoningisverysimple,it’sbecauseObjectisthebaseclassforallthe java classes. So even if we have Object classmethods defined as defaultmethodsininterfaces,itwillbeuselessbecauseObjectclassmethodwillalwaysbeused.That’swhytoavoidconfusion,wecan’thavedefaultmethodsthatareoverridingObjectclassmethods.

Default methods are also referred to as Defender Methods or Virtualextensionmethods.

Interfacestaticmethods-

Staticmethodsaresimilartodefaultmethodsexceptthatwecan’toverridethemintheimplementationclasses.Thisfeaturehelpsusinavoidingundesiredresultsincaseofpoorimplementationinchildclasses.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 poorimplementation.

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 interfacemethod.

For example, ifwewill add@Overrideannotation to the isNull()method, itwill result in compiler error. Nowwhenwewill run the application, we get followingoutput.

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 fortheMyDataImpl object. However like other staticmethods,we can use interface staticmethodsusingclassname.Forexample,avalidstatementwillbe:

1 booleanresult=MyData.isNull(“abc”);

Importantpointsaboutinterfacestaticmethods:

Interfacestaticmethodsarepartofinterface,wecan’tuseitforimplementationclassobjects.

Interfacestaticmethodsaregoodforprovidingutilitymethods,forexamplenullcheck,collectionsortingetc.

Interfacestaticmethodhelpsusinprovidingsecuritybynotallowingimplementationclassestooverridethem.

Wecan’tdefinestaticmethodsforObjectclassmethods,wewillgetcompilererroras“ThisstaticmethodcannothidetheinstancemethodfromObject”.Thisisbecauseit’snotallowedinjava,sinceObjectisthebaseclassforalltheclassesandwecan’thaveoneclasslevelstaticmethodandanotherinstancemethodwithsamesignature.

WecanusestaticinterfacemethodstoremoveutilityclassessuchasCollectionsandmoveallofit’sstaticmethodstothecorrespondinginterface,thatwouldbeeasytofindanduse.

FunctionalInterfaces-

Before I conclude the topic, I would like to provide a brief introduction toFunctional interfaces. An interface with exactly one abstract method is known asFunctionalInterface.

Anewannotation@FunctionalInterfacehasbeenintroducedtomarkaninterfaceasFunctionalInterface.@FunctionalInterfaceannotation isafacility toavoidaccidentaladditionofabstractmethodsinthefunctionalinterfaces.It’soptionalbutgoodpracticetouseit.

Functional interfaces are long awaited andmuch sought out feature of Java 8because it enables us to use lambda expressions to instantiate them. A newpackagejava.util.functionwithbunchoffunctionalinterfacesareaddedtoprovidetargettypesforlambdaexpressionsandmethodreferences.

3.FunctionalInterfacesandLambdaExpressions-

If you notice above interfaces code, you will notice@FunctionalInterfaceannotation. Functional interfaces are new concept introduced in

Java8.AninterfacewithexactlyoneabstractmethodbecomesFunctionalInterface.

Wedon’t need to use@FunctionalInterface annotation tomark an interface asFunctional Interface. @FunctionalInterface annotation is a facility to avoid accidentaladditionofabstractmethodsinthefunctionalinterfaces.

You can think of it like@Override annotation and it’s best practice to useit. java.lang.Runnablewith single abstractmethod run() is a great example of functionalinterface.

Oneofthemajorbenefitsoffunctionalinterfaceisthepossibilitytouselambdaexpressionstoinstantiatethem.Wecaninstantiateaninterfacewithanonymousclassbutthecodelooksbulky.

Runnabler=new Runnable(){@Override

public void run(){System.out.println(“MyRunnable”);

}};

Sincefunctionalinterfaceshaveonlyonemethod,lambdaexpressionscaneasilyprovidethemethodimplementation.

Wejustneedtoprovidemethodargumentsandbusinesslogic.Forexample,wecanwriteaboveimplementationusinglambdaexpressionas:

Runnabler1=()->{

System.out.println(“MyRunnable”);

};

Ifyouhavesinglestatementinmethodimplementation,wedon’tneedcurlybracesalso.For example above Interface1 anonymous class can be instantiated using lambda asfollows:

Interface1i1=(s)->System.out.println(s);

i1.method1(“abc”);

So lambda expressions are means to create anonymous classes of functionalinterfaceseasily.Therearenoruntimebenefitsofusinglambdaexpressions,soIwilluseitcautiouslybecauseIdon’tmindwritingfewextralinesofcode.

A new package java.util.function has been added with bunch of functionalinterfacestoprovidetargettypesforlambdaexpressionsandmethodreferences.

Lambdaexpressionsareahugetopic,Iwillwriteaseparate+(Note)onthatinfuture(NextEditionofthisBook).YoucanreadcompletetutorialbelowJava8LambdaExpressionsTutorial.

Java8LambdaExpressionsandFunctionalInterfacesTutorial-

Java has always been anObject Oriented Programming language. What ismeans that everything in java programming revolves around Objects (except someprimitivetypesforsimplicity).Wedon’thaveonlyfunctionsinjava,theyarepartofClassandweneedtousetheclass/objecttoinvokeanyfunction.

IfwelookintosomeotherprogramminglanguagessuchasC++,JavaScript;theyare called functional programming language becausewe canwrite functions and usethemwhen required.Someof these languagessupportObjectOrientedProgrammingaswellasFunctionalProgramming.

Being object oriented is not bad, but it brings a lot of verbosity to the program. Forexample, let’s say we have to create an instance of Runnable. Usually we do it usinganonymousclasseslikebelow.

1

2

3

4

5

Runnabler=newRunnable(){

@Override

publicvoidrun(){

System.out.println(“MyRunnable”);

}

};

Ifyoulookattheabovecode,theactualpartthatisofuseisthecodeinsiderun()method.Restallofthecodeisbecauseofthewayjavaprogramsarestructured.

Java8bringsustheconceptofFunctionalInterfacesandLambdaExpressionstoavoidwritingalltheuselesscodethatwecaneasilyavoidbymakingourjavacompilerintelligent.

FunctionalInterface-

An interface with exactly one abstract method is called Functional Interface.@FunctionalInterfaceannotation is added so thatwecanmarkan interfaceas functionalinterface. It is not mandatory to use it, but it’s best practice to use it with functionalinterfaces to avoid addition of extra methods accidentally. If the interface is annotatedwith@FunctionalInterfaceannotationandwetrytohavemorethanoneabstractmethod,itthrowscompilererror.

The major benefit of functional interface is that we can use lambdaexpressionstoinstantiatethemandavoidusingbulkyanonymousclassimplementation.

Java8CollectionsAPIhasrewrittenandnewStreamAPIisprovidedthatusesalot of functional interfaces. Java 8 has defined a lot of functional interfacesin java.util.function package, some of the useful onesareConsumer, Supplier, Function and Predicate. You can find more detail about theminJava8StreamExample.

java.lang.Runnable is a great example of functional interface with single abstractmethodrun().

Belowcodesnippetprovidessomeguidanceforfunctionalinterfaces:

interfaceFoo{booleanequals(Objectobj);}

//Notfunctionalbecauseequalsisalreadyanimplicitmember(Objectclass)

interfaceComparator<T>{

booleanequals(Objectobj);

intcompare(To1,To2);

}

//FunctionalbecauseComparatorhasonlyoneabstractnon-Objectmethod

interfaceFoo{

intm();

Objectclone();

}

//NotfunctionalbecausemethodObject.cloneisnotpublic

interfaceX{intm(Iterable<String>arg);}

interfaceY{intm(Iterable<String>arg);}

interfaceZextendsX,Y{}

//Functional:twomethods,buttheyhavethesamesignature

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

interfaceX{intm(Iterable<String>arg,Classc);}

interfaceY{intm(Iterablearg,Class<?>c);}

interfaceZextendsX,Y{}

//Notfunctional:Nomethodhasasubsignatureofallabstractmethods

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 theway throughwhichwe can visualize functionalprogramminginthejavaobjectorientedworld.ObjectsarethebaseofjavaprogramminglanguageandwecanneverhaveafunctionwithoutanObject,that’swhyJavalanguageprovidesupportforusinglambdaexpressionsonlywithfunctionalinterfaces.

Sincethereisonlyoneabstractfunctioninthefunctionalinterfaces,thereisnoconfusioninapplyingthelambdaexpressiontothemethod.LambdaExpressionssyntaxis (argument) -> (body).Now let’s see howwe canwrite above anonymousRunnableusinglambdaexpression.

1 Runnabler1=()->System.out.println(“MyRunnable”);

Let’strytounderstandwhatishappeninginthelambdaexpressionabove.

Runnableisafunctionalinterface,that’swhywecanuselambdaexpression

tocreateit’sinstance.

Sincerun()methodtakesnoargument,ourlambdaexpressionalsohavenoargument.

Justlikeif-elseblocks,wecanavoidcurlybraces({})sincewehaveasinglestatement in themethod body. Formultiple statements,wewould have to usecurlybraceslikeanyothermethods.

WhydoweneedLambdaExpressions-

1.ReducedLinesofCode–

Oneoftheclearbenefitofusinglambdaexpressionisthattheamountofcodeisreduced,wehavealreadyseenthathoweasilywecancreateinstanceofafunctionalinterfaceusinglambdaexpressionratherthanusinganonymousclass.

2.SequentialandParallelExecutionSupport-

Anotherbenefitofusing lambdaexpression is thatwecanbenefit fromtheStreamAPIsequential and parallel operations support. To explain this, let’s take a simple examplewhereweneedtowriteamethodtotestifanumberpassedisprimenumberornot.

Traditionallywewouldwrite it’s code like below. The code is not fully optimized butgoodforexamplepurpose,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,ifthenumberisveryhugethenitwilltakesignificantamountoftime.Anotherproblemwithcodeisthattherearesomanyexitpointsandit’snotreadable.Let’sseehowwecanwritethesamemethodusinglambdaexpressionsandstreamAPI.

1

2

3

//Declarativeapproach

privatestaticbooleanisPrime(intnumber){

returnnumber>1

4

5

6

&&IntStream.range(2,number-1).noneMatch(

index->number%index==0);

}

IntStreamisasequenceofprimitiveint-valuedelementssupportingsequentialandparallelaggregate operations. This is the int primitive specialization of Stream. For morereadability,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 familiarwith IntStream, it’s range()method returns a sequential orderedIntStream from startInclusive (inclusive) to endExclusive (exclusive) by an incrementalstep of 1. noneMatch() method returns whether no elements of this stream match theprovidedpredicate.

It may not evaluate the predicate on all elements if not necessary for determining theresult.

3.PassingBehaviorsintomethods-

Let’sseehowwecanuselambdaexpressionstopassbehaviorofamethodwithasimpleexample.Let’ssaywehavetowriteamethodtosumthenumbersinalistiftheymatchagivencriteria.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-

Onemoreadvantageofusinglambdaexpressionis thelazyevaluation,forexamplelet’ssayweneedtowriteamethodtofindoutthemaximumoddnumberintherange3to11andreturnsquareofit.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;

}

AboveprogramwillalwaysruninsequentialorderbutwecanuseStreamAPItoachievethis and get benefit of Laziness-seeking. Let’s see how we can rewrite this code infunctionalprogrammingwayusingStreamAPIandlambdaexpressions.

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’sintroducedinJava8andusedformethodreferences.JavaCompilertakescareofmappingtheargumentstothecalledmethod. It’s short form of lambda expressions i -> isGreaterThan3(i) or i ->NumberTest.isGreaterThan3(i).

LambdaExpressionExamples-

BelowIamprovidingsomecodesnippets for lambdaexpressionswithsmallcommentsexplainingthem.

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 constructorreferenceissimilarlyusedtorefertoaconstructorwithoutcreatinganewinstanceofthenamedclassorarraytype.

Examplesofmethodandconstructorreferences:

1

2

3

System::getProperty

System.out::println

“abc”::length

4

5

ArrayList::new

int[]::new

That’sallforFunctionalInterfacesandLambdaExpressionTutorial,IwouldstronglysuggesttolookintousingitbecausethissyntaxisnewtoJavaanditwilltakesometimetograspitanduseitinabetterway.

4.JavaStreamAPIforBulkDataOperationsonCollections-

Anewjava.util.streamhasbeenaddedinJava8toperformfilter/map/reducelikeoperations with the collection. Stream API will allow sequential as well as parallelexecution.

ThisisoneofthebestfeatureformebecauseIworkalotwithCollectionsandusuallywithBigData,weneed to filterout thembasedonsomeconditions.Collectioninterface has been extended with STREAM() and PARALLELSTREAM() defaultmethodstogettheStreamforsequentialandparallelexecution.Let’sseetheirusagewithsimpleexample.

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,soparallelprocessingwillbeveryhelpfulwhileworkingwithhugecollections.CoveringeverythingaboutStreamAPIisnotpossibleinthistopic,youcanreadeverythingaboutStreamAPIatJava8StreamAPITutorialinnextchapter.

CHAPTER∞23∞

Java8StreamAndTimeAPI

Java8StreamAPIExampleTutorial-

Inthelasttopics,welookedintoJava8InterfaceChangesandFunctionalInterfacesandLambdaExpressions.

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.Supposewewanttoiterateoveralistofintegersandfindoutsumofalltheintegersgreaterthan10.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)Wejustwanttoknowthesumofintegersbutwewouldalsohavetoprovidehowthe iterationwill takeplace, this isalsocalledexternal iterationbecauseclientprogramishandlingthealgorithmtoiterateoverthelist.

2) The program is sequential in nature, there is nowaywe can do this inparalleleasily.

3)Thereisalotofcodetodoevenasimpletask.

To overcome all the above shortcomings, Java 8 introduces Stream API. We can useStreamAPI to implementinternal iteration, that is better because java framework is incontroloftheiteration.Internaliterationprovidesseveralfeaturessuchassequentialandparallelexecution,filteringbasedonthegivencriteria,mappingetc.

Most of the Stream API method arguments are functional interfaces, so lambdaexpressionsworkverywellwiththem.Let’sseehowcanwewriteabovelogicinasinglelinestatement.

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 andmappingmethods andwould increase efficiency. First of allwewill look into the coreconcepts ofStreamAPI and thenwewill go through someexamples for understandingmostcommonlyusedmethods.

CollectionsandStreams-

Acollection is an in-memorydata structure to hold values andbeforewe startusingcollection,all thevaluesshouldhavebeenpopulated.WhereasaStream isadatastructurethatiscomputedon-demand.

Streamdoesn’tstoredata,itoperatesonthesourcedatastructure(collectionandarray)andproducepipelineddatathatwecanuseandperformspecificoperations.Suchaswecancreateastreamfromthelistandfilteritbasedonacondition.

Stream operations use functional interfaces, that makes it a very good fit forfunctionalprogrammingusinglambdaexpressions.Asyoucanseeintheaboveexamplethatusinglambdaexpressionsmakeourcodereadableandshort.

Streaminternaliterationprinciplehelpsinachievinglazy-seekinginsomeofthestream operations. For example filtering, mapping, or duplicate removal can beimplementedlazily,allowinghigherperformanceandscopeforoptimization.

Streamsareconsumable, so there isnoway tocreatea reference to stream forfuture usage. Since the data is on-demand, it’s not possible to reuse the same streammultipletimes.

Streamsupportsequentialaswellasparallelprocessing,parallelprocessingcanbeveryhelpfulinachievinghighperformanceforlargecollections.

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 anothertype of argument. Function is the generic formwhere T is the type of the input to thefunctionandRisthetypeoftheresultofthefunction.Forhandlingprimitivetypes,therearespecificFunctioninterfaces-

ToIntFunction, ToLongFunction, ToDoubleFunction, ToIntBiFunction,

ToLongBiFunction,ToDoubleBiFunction, LongToIntFunction, LongToDoubleFunction,IntToLongFunction,IntToDoubleFunctionetc.

SomeoftheStreammethodswhereFunctionorit’sprimitivespecializationisusedare:

<R>Stream<R>map(Function<?superT,?extendsR>mapper)

IntStreammapToInt(ToIntFunction<?superT>mapper)–similarlyforlonganddoublereturningprimitivespecificstream.

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.Thisisusedtofilterelementsfromthestream.JustlikeFunction,thereareprimitivespecificinterfacesforint,longanddouble.

SomeoftheStreammethods-wherePredicateorBiPredicatespecializationsareusedare:

Stream<T>filter(Predicate<?superT>predicate)booleananyMatch(Predicate<?superT>predicate)booleanallMatch(Predicate<?superT>predicate)booleannoneMatch(Predicate<?superT>predicate)

3.ConsumerandBiConsumer:

Itrepresentsanoperationthatacceptsasingleinputargumentandreturnsnoresult.Itcanbe used to perform some action on all the elements of the stream.Some of the StreammethodswhereConsumer,BiConsumerorit’sprimitivespecializationinterfacesareusedare:

Stream<T>peek(Consumer<?superT>action)voidforEach(Consumer<?superT>action)voidforEachOrdered(Consumer<?superT>action)

4.Supplier:Supplierrepresentanoperationthroughwhichwecangeneratenewvaluesinthestream.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.Ifavalueispresent,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.SpliteratortrySplitmethodreturnsanewSpliteratorthatmanagesasubsetoftheelementsoftheoriginalSpliterator.

IntermediateandTerminalOperations-

Stream API operations that returns a new Stream are called intermediateoperations.Mostof the times, theseoperationsare lazyinnature,so theystartproducingnewstreamelementsandsend it to thenextoperation. Intermediateoperationsareneverthefinalresultproducingoperations.

Commonly used intermediate operations are filter and map.Stream APIoperations that returns a result or produce a side effect. Once the terminalmethod is called on a stream, it consumes the stream and after that we can’tuse stream. Terminal operations are eager in nature i.e they process all theelementsinthestreambeforereturningtheresult.

Commonly used terminal methods are forEach, toArray, min, max, findFirst,anyMatch, allMatch etc. You can identify terminal methods from the returntype,theywillneverreturnaStream.

ShortCircuitingOperations-

An intermediate operation is called short circuiting, if it may produce finitestream for an infinite stream. For example limit() and skip() are two short circuitingintermediateoperations.

Aterminaloperation iscalledshortcircuiting, if itmay terminate infinite timefor infinitestream.ForexampleanyMatch,allMatch,noneMatch, findFirstand findAnyareshortcircuitingterminaloperations.

JavaStreamExamples-

IhavecoveredalmostalltheimportantpartsoftheJavaStreamAPI.It’sexcitingtousethisnewAPIfeaturesandlet’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 itdoesn’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[]>toStream<Integer>

3. We can use Collection stream() to create sequential stream and parallelStream() tocreateparallelstream.

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’slookintocommonlyusedStreamintermediateoperationsexample.

1. Stream filter() example: We can use filter() method to test stream elements for aconditionandgeneratefilteredlist.

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);//filternumbersgreaterthan90

System.out.print(“HighNumsgreaterthan90=”);

highNums.forEach(p->System.out.print(p+”“));

7 //prints“HighNumsgreaterthan90=919293949596979899“

2.Streammap()example:Wecanusemap() toapplyfunctionstoanstream.Let’sseehowwecanuseittoapplyuppercasefunctiontoalistofStrings.

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()tosortthestreamelementsbypassingComparatorargument.

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()tocreateastreamfromthestreamoflist.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()toperformareductionontheelementsof the stream,usinganassociativeaccumulation function, and returnanOptional.Let’sseehowwecanuseitmultiplytheintegersinastream.

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:Wecanuse this terminaloperation tocount thenumberofitemsinthestream.

1

2

Stream<Integer>numbers1=Stream.of(1,2,3,4,5);

System.out.println(“Numberofelementsinstream=”+numbers1.count());//5

3.StreamforEach()example:Thiscanbeusedforiteratingoverthestream.Wecanusethisinplaceofiterator.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’s see someof theexamples formatchingmethods inStreamAPI.

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’sseehowwecanuseittofindthefirststringfromastreamstartingwithD.

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 somelimitationstoo.

1.Statelesslambdaexpressions:Ifyouareusingparallelstreamandlambdaexpressionsarestateful,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);

}}

Ifwe run above program, youwill get different results because it depends on thewaystreamisgettingiteratedandwedon’thaveanyorderdefinedforparallelprocessing.Ifweusesequentialstream,thenthisproblemwillnotarise.

2.OnceaStreamisconsumed,itcan’tbeusedlateron.AsyoucanseeinaboveexamplesthateverytimeIamcreatingastream.

3.TherearealotofmethodsinStreamAPIandthemostconfusingpartistheoverloadedmethods.Itmakesthelearningcurvetimetaking.

That’sallforStreamAPIinJava.Iamlookingforwardtousethisfeatureandmakethecodereadablewithbetterperformancethroughparallelprocessing.

5.JavaTimeAPI-

IthasalwaysbeenhardtoworkwithDate,TimeandTimeZonesinjava.Therewas no standard approach or API in java for date and time in Java. One of the niceadditioninJava8isthejava.timepackagethatwillstreamlinetheprocessofworkingwithtimeinjava.

JustbylookingatJavaTimeAPIpackages,Icansensethatitwillbeveryeasytouse. It has some sub-packages java.time.format that provides classes to print and parsedatesandtimesandjava.time.zoneprovidessupportfortime-zonesandtheirrules.

ThenewTimeAPIprefersenumsoverintegerconstantsformonthsanddaysoftheweek.OneoftheusefulclassisDateTimeFormatterforconvertingdatetimeobjectstostrings.

6.CollectionAPIimprovements-

Wehave already seen forEach()methodandStreamAPI for collections.SomenewmethodsaddedinCollectionAPIare:

Iteratordefaultmethodfor-EachRemaining(Consumeraction)toperformthegivenactionforeachremainingelementuntilallelementshavebeenprocessedortheactionthrowsanexception.

Collectiondefaultmethod- removeIf(Predicate filter) to removeallof theelementsofthiscollectionthatsatisfythegivenpredicate.

Collection spliterator()method- returningSpliterator instance that canbe

usedtotraverseelementssequentiallyorparallel.

MapreplaceAll(),compute(),merge()methods.

7.ConcurrencyAPIimprovements-

SomeimportantconcurrentAPIenhancementsare:

a) ConcurrentHashMapcompute(), forEach(), forEachEntry(), forEachKey(),forEachValue(),merge(),reduce()andsearch()methods.

b) CompletableFuturethatmaybeexplicitlycompleted(settingitsvalueandstatus).

c) ExecutorsnewWorkStealingPool()methodtocreateawork-stealingthreadpoolusingallavailableprocessorsasitstargetparallelismlevel.

8.JavaIOimprovements-

SomeIOimprovementsknowntomeare:

d) Files.list(Pathdir) that returnsa lazilypopulatedStream, theelementsofwhicharetheentriesinthedirectory.

e)Files.lines(Pathpath)thatreadsalllinesfromafileasaStream.

f) Files.find() that returns a Stream that is lazily populated with Path bysearchingforfilesinafiletreerootedatagivenstartingfile.

g)BufferedReader.lines()thatreturnaStream,theelementsofwhicharelinesreadfromthisBufferedReader.

9.MiscellaneousCoreAPIimprovements-

SomemiscAPIimprovementsthatmightcomehandyare:

h)ThreadLocalstaticmethodwithInitial(Suppliersupplier)tocreateinstanceeasily.

i) Comparator interfacehasbeen extendedwith a lot of default and staticmethodsfornaturalordering,reverseorderetc.

j) min(), max() and sum() methods in Integer, Long and Double wrapperclasses.

k)logicalAnd(),logicalOr()andlogicalXor()methodsinBooleanclass.

l) ZipFile.stream()methodtogetanorderedStreamovertheZIPfileentries.EntriesappearintheStreamintheordertheyappearinthecentraldirectoryoftheZIPfile.

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.Ifwetakealookattheenterprise side, more than $2.2 billion are being spent by the enterprises in Javaapplicationserver.

ThereisnodenyingthatJavaisusedextensivelyfordevelopingJavaenterpriseapplications reasonbeingSecurity. Javabrings someof themost fascinating featuresorbenefitsthatareimpossibletofindinanyotherprogramminglanguagesorplatforms.

Security isan importantaspectandJava’ssecuritymodel isoneof thekeyarchitecturalfeatures thatmake itmost trustful choicewhen it comes to developing enterprise-levelapplications.Securitybecomescriticalwhensoftwareisdownloadedacrossnetworkandexecutedlocally,andJavaeasilymitigatesthesecurityvulnerabilitiesassociatedwiththeprojects or applications. Don’t believe this? Have a look at a few arguments (securitymeasures/features)thatshowcasehowsecureJavaplatformis.

Java’ssecuritymodel

Java’s security model is intended to help and protect users from hostile programsdownloadedfromsomeun-trustedresourcewithinanetworkthrough“sandbox”.ItallowsalltheJavaprogramstoruninsidethesandboxonlyandpreventsmanyactivitiesfromun-trustedresourcesincludingreadingorwritingtothelocaldisk,creatinganynewprocessorevenloadinganynewdynamiclibrarywhilecallinganativemethod.

Nouseofpointers

C/C++languageusespointers,whichmaycauseunauthorizedaccess tomemoryblockswhenotherprogramsget thepointervalues.UnlikeconventionalC/C++ language, Javaneverusesanykindofpointers.Javahasitsinternalmechanismformemorymanagement.Itonlygivesaccesstothedatatotheprogramifhasappropriateverifiedauthorization.

Exceptionhandlingconcept

The concept of exception handling enables Java to capture a series of errors that helpsdeveloperstogetridofriskofcrashingthesystem.

Definedorderexecution

Alltheprimitivesaredefinedwithapredefinedsizeandalltheoperationsaredefinedinaspecific order of execution. Therefore, the code executed in different Java Virtual

Machineswon’thaveadifferentorderofexecution.

BytecodeisanotherthingthatmakesJavamoresecure

EverytimewhenausercompilestheJavaprogram,theJavacompilercreatesaclassfilewithBytecode,whicharetestedbytheJVMatthetimeofprogramexecutionforvirusesandothermaliciousfiles.

Testedcodere-usability

The Java object encapsulation provides support for the concept of “programming bycontract”.Thisallowsthedeveloperstore-usethecodethathasalreadybeentestedwhiledevelopingJavaenterpriseapplications.

AccessControlfunctionality

Java’s access-control functionality on variables andmethodswithin the objects providesecureprogrambypreventingaccesstothecriticalobjectsfromtheun-trustedcode.

Protectionfromsecurityattacks

ItallowsdeveloperstodeclareclassesormethodsasFINAL.Weallknowthatanyclassormethoddeclaredas finalcan’tbeoverridden,whichhelpsdevelopers toprotectcodefromsecurityattackslikecreatingasubclassandreplacingitwiththeoriginalclassandoverridemethods.

Garbagecollectionmechanism

Garbagecollectionmechanismaidsmore to thesecuritymeasuresofJava. Itprovidesatransparentstorageallocationandrecoveringunutilizedmemoryratherthande-allocatingmemory through manual action. It will help developers to ensure the integrity of theprogram during its execution and avoids any JVM crash due to incorrect freeing ofmemory.

Type-safereferencecastinginJVM

Whenever you use an object reference, the JVM monitors you. If you try to cast areferencetoadifferenttype,itwillmakethecastinvalid.

Apart fromall these, structurederrorhandlingcontributesa lot to thesecuritymodelofJava by helping to enhance the robustness of the programs. The above argumentsdefinitelyprove that theprojectsdeveloped in Javaaremore secureascompared to theotherprogramminglanguage.However,itistheresponsibilityofthedeveloperstofollowsomebestpracticeswhiledevelopingenterprise-levelJavaapplications.