DEITEL® HOWTOPROGRAMSERIESCover Theme The cover theme for the DEITEL®HOWTOPROGRAMSERIESemphasizes social consciousness issues such as going green, clean energy, recycling, sustainability and more. Within the text, in addition to conventional program- ming exercises, we’ve included our Making a Difference exercise set to raise awareness of issues such as global warming, population growth, affordable healthcare, accessibility, privacy of electronic records and more. In this book, you’ll use Java to program applications that relate to these issues. We hope that what you learn in Java How to Program, 9/e will help you to make a difference. Night at the Niagara Falls—Ontario and New York The Niagara Falls waterfalls straddle the border between Ontario, Canada and upstate New York in the United States. Horseshoe Falls is located on the Canadian side, and American Falls and Bridal Veil Falls are on the U.S. side. The Niagara Falls are an awe-inspiring, world-class tourist attraction, and a significant source of hydroelectric power. On average, nearly four million cubic feet of water falls over the crest line each minute. The U.S. and Canada harness the natu- ral energy from Niagara Falls to generate clean, inexpensive electricity. The first hydroelectric generating station on the Niagara River was built in 1881. Its electricity powered local mills and street lights. The Niagara Redevelopment Act, passed by the U.S. Congress in 1957, gave the New York Power Authority the right to develop the U.S. Niagara River hydroelectric power plants. The Niagara Falls hydroelectric project began operating in 1961. Up to 375,000 gallons of water per second is diverted from the river through conduits to the power plants. The water spins turbines that power generators that convert the mechanical energy into electrical energy. Today, the project generates 2.4 million kilowatts, which can power 24 million 100-watt light bulbs simultaneously. For further information visit: en.wikipedia.org/wiki/Niagra_falls www.nypa.gov/facilities/niagara.htm www.niagarafrontier.com/power.html About Deitel & Associates, Inc. Deitel & Associates, Inc., is an internationally recognized authoring and corporate training organization. The com- pany offers instructor-led courses delivered at client sites worldwide on programming languages and other software topics such as Java™, C#®, Visual Basic®, Visual C++®, C++, C, Objective-C®, XML®, Python®, JavaScript, object technology, Internet and web programming, and Android and iPhone app development. The company’s clients in- clude many of the world’s largest companies, as well as government agencies, branches of the military and academic institutions. To learn more about Deitel Pearson Higher Education publications and Dive Into®Series corporate training, [email protected] visit www.deitel.com/training/. Follow Deitel on Facebook®at www.deitel.com/deitelfan/and on Twitter®@deitel. D e i t e l ® S e r i e s P a g e How To Program Series (continued) SimplyVisualBasic2008:AnApp-Driven Java™HowtoProgram,9/E TutorialApproach,3/E Java™HowtoProgram,LateObjectsVersion,8/E VisualBasic®2010HowtoProgram C++HowtoProgram,8/E VisualBasic®2008HowtoProgram CHowtoProgram,6/E VisualC#®2010HowtoProgram,4/E Internet&WorldWideWebHowtoProgram,4/E VisualC#®2008HowtoProgram,3/E VisualBasic®2010HowtoProgram VisualC#®2010HowtoProgram,3/E Deitel® Developer Series VisualC++®2008HowtoProgram,2/E SmallJava™HowtoProgram,6/E AJAX,RichInternetApplicationsandWeb DevelopmentforProgrammers SmallC++HowtoProgram,5/E AndroidforProgrammers:AnApp-Driven Approach Simply Series C++forProgrammers SimplyC++:AnApp-DrivenTutorialApproach C#2010forProgrammers,3/E SimplyJava™Programming:AnApp-Driven iPhoneforProgrammers:AnApp-DrivenApproach TutorialApproach Java™forProgrammers SimplyC#:AnApp-DrivenTutorialApproach JavaScriptforProgrammers SimplyVisualBasic®2008,3/E:AnApp-Driven TutorialApproach LiveLessonsVideoLearningProducts CourseSmart Web Books www.deitel.com/books/LiveLessons/ Java™Fundamentals www.deitel.com/books/CourseSmart/ C#Fundamentals C++HowtoProgram,5/E,6/E,7/E&8/E C++Fundamentals Java™HowtoProgram,6/E,7/E,8/E&9/E iPhone®AppDevelopmentFundamentals SimplyC++:AnApp-DrivenTutorialApproach JavaScriptFundamentals (continuednextcolumn) VisualBasicFundamentals ToreceiveupdatesonDeitelpublications,ResourceCenters,trainingcourses,partneroffersandmore, pleaseregisterforthefreeDeitel®BuzzOnlinee-mailnewsletterat: www.deitel.com/newsletter/subscribe.html followusonTwitter® @deitel andbecomeaDeitel&AssociatesfanonFacebook® www.deitel.com/deitelfan/ Tocommunicatewiththeauthors,sende-mailto: [email protected] ForinformationongovernmentandcorporateDive-Into®Serieson-siteseminarsofferedbyDeitel& Associates,Inc.worldwide,visit: www.deitel.com/training/ orwriteto [email protected] ForcontinuingupdatesonPrenticeHall/Deitelpublicationsvisit: www.deitel.com www.pearsonhighered.com/deitel/ CheckoutourResourceCentersforvaluablewebresourcesthatwillhelpyoumasterJava,otherimpor- tantprogramminglanguages,softwareand,Internet-andweb-relatedtopics: www.deitel.com/ResourceCenters.html Paul Deitel Deitel & Associates, Inc. Harvey Deitel Deitel & Associates, Inc. VicePresidentandEditorialDirector:MarciaJ.Horton Editor-in-Chief:MichaelHirsch AssociateEditor:CaroleSnyder VicePresident,Marketing:PatriceJones MarketingManager:YezanAlayan SeniorMarketingCoordinator:KathrynFerranti VicePresident,Production:VinceO’Brien ManagingEditor:JeffHolcomb AssociateManagingEditor:RobertEngelhardt OperationsSpecialist:LisaMcDowell ArtDirector:LindaKnowle CoverDesign:AbbeyS.Deitel,HarveyM.Deitel,MartaSamsel CoverPhotoCredit:©GonzaloE.Brea/Flickr/GettyImages MediaEditor:DanielSandin MediaProjectManager:WandaRockwell Creditsandacknowledgmentsborrowedfromothersourcesandreproduced,withpermission,inthistextbookappear onpagevi. Theauthorsandpublisherofthisbookhaveusedtheirbesteffortsinpreparingthisbook.Theseeffortsincludethe development,research,andtestingofthetheoriesandprogramstodeterminetheireffectiveness.Theauthorsandpub- lishermakenowarrantyofanykind,expressedorimplied,withregardtotheseprogramsortothedocumentation containedinthisbook.Theauthorsandpublishershallnotbeliableinanyeventforincidentalorconsequentialdam- agesinconnectionwith,orarisingoutof,thefurnishing,performance,oruseoftheseprograms. Copyright©2012,2009,2007,2005,2003PearsonEducation,Inc.,publishingas PrenticeHall. Allrightsreserved. ManufacturedintheUnitedStatesofAmerica.ThispublicationisprotectedbyCopyright,andpermissionshouldbe obtainedfromthepublisherpriortoanyprohibitedreproduction,storageinaretrievalsystem,ortransmissioninany formorbyanymeans,electronic,mechanical,photocopying,recording,orlikewise.Toobtainpermission(s)touse materialfromthiswork,pleasesubmitawrittenrequesttoPearsonEducation,Inc.,PermissionsDepartment,501 BoylstonStreet,Suite900,Boston,Massachusetts02116. Manyofthedesignationsbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarks.Where thosedesignationsappearinthisbook,andthepublisherwasawareofatrademarkclaim,thedesignationshavebeen printedininitialcapsorallcaps. LibraryofCongressCataloging-in-PublicationData Deitel, Paul J. Java : how to program / P.J. Deitel, H.M. Deitel. -- 9th ed. p. cm. H.M. Deitel's name appears on the earlier editions. Includes index. ISBN 978-0-13-257566-9 1. Java (Computer program language) I. Deitel, Paul J. II. Deitel, Harvey M. III. Title. QA76.73.J38D45 2012 005.13'3--dc22 2011000244 10 9 8 7 6 5 4 3 2 1 ISBN-10: 0-13-257566-3 ISBN-13: 978-0-13-257566-9 In memory of Sargent Shriver, The first director of the Peace Corps and founder of numerous social organizations: For a lifetime of making a difference. Pauland HarveyDeitel Trademarks DEITEL,thedouble-thumbs-upbugandDIVEINTOareregisteredtrademarksofDeitelandAssociates, Inc. OracleandJavaareregisteredtrademarksofOracleand/oritsaffiliates.Othernamesmaybetrademarks oftheirrespectiveowners. Microsoft,InternetExplorerandtheWindowslogoareeitherregisteredtrademarksortrademarksof MicrosoftCorporationintheUnitedStatesand/orothercountries. UNIXisaregisteredtrademarkofTheOpenGroup. ApacheisatrademarkofTheApacheSoftwareFoundation. CSS,XHTMLandXMLareregisteredtrademarksoftheWorldWideWebConsortium. FirefoxisaregisteredtrademarkoftheMozillaFoundation. GoogleisatrademarkofGoogle,Inc. Web2.0isaservicemarkofCMPMedia. Throughoutthisbook,trademarksareused.Ratherthanputatrademarksymbolineveryoccurrenceof atrademarkedname,westatethatweareusingthenamesinaneditorialfashiononlyandtothebenefit ofthetrademarkowner,withnointentionofinfringementofthetrademark. Contents AppendicesM–QarePDFdocumentspostedonlineatthebook’sCompanionWebsite (www.pearsonhighered.com/deitel/). Preface xxiii Before You Begin xxxiii 1 Introduction to Computers and Java 1 1.1 Introduction 2 1.2 Computers:HardwareandSoftware 5 1.3 DataHierarchy 6 1.4 ComputerOrganization 8 1.5 MachineLanguages,AssemblyLanguagesandHigh-LevelLanguages 10 1.6 IntroductiontoObjectTechnology 11 1.7 OperatingSystems 13 1.8 ProgrammingLanguages 16 1.9 JavaandaTypicalJavaDevelopmentEnvironment 18 1.10 Test-DrivingaJavaApplication 22 1.11 Web2.0:GoingSocial 26 1.12 SoftwareTechnologies 29 1.13 KeepingUp-to-DatewithInformationTechnologies 31 1.14 Wrap-Up 32 2 Introduction to Java Applications 37 2.1 Introduction 38 2.2 YourFirstPrograminJava:PrintingaLineofText 38 2.3 ModifyingYourFirstJavaProgram 44 2.4 DisplayingTextwithprintf 46 2.5 AnotherApplication:AddingIntegers 47 2.6 MemoryConcepts 52 viii Contents 2.7 Arithmetic 53 2.8 DecisionMaking:EqualityandRelationalOperators 56 2.9 Wrap-Up 60 3 Introduction to Classes, Objects, Methods and Strings 71 3.1 Introduction 72 3.2 DeclaringaClasswithaMethodandInstantiatinganObjectofaClass 72 3.3 DeclaringaMethodwithaParameter 76 3.4 InstanceVariables,setMethodsandgetMethods 79 3.5 PrimitiveTypesvs.ReferenceTypes 84 3.6 InitializingObjectswithConstructors 85 3.7 Floating-PointNumbersandTypedouble 88 3.8 (Optional)GUIandGraphicsCaseStudy:UsingDialogBoxes 92 3.9 Wrap-Up 95 4 Control Statements: Part 1 102 4.1 Introduction 103 4.2 Algorithms 103 4.3 Pseudocode 104 4.4 ControlStructures 104 4.5 ifSingle-SelectionStatement 107 4.6 if…elseDouble-SelectionStatement 107 4.7 whileRepetitionStatement 112 4.8 FormulatingAlgorithms:Counter-ControlledRepetition 113 4.9 FormulatingAlgorithms:Sentinel-ControlledRepetition 118 4.10 FormulatingAlgorithms:NestedControlStatements 125 4.11 CompoundAssignmentOperators 130 4.12 IncrementandDecrementOperators 130 4.13 PrimitiveTypes 134 4.14 (Optional)GUIandGraphicsCaseStudy:CreatingSimpleDrawings 134 4.15 Wrap-Up 138 5 Control Statements: Part 2 151 5.1 Introduction 152 5.2 EssentialsofCounter-ControlledRepetition 152 5.3 forRepetitionStatement 154 5.4 ExamplesUsingtheforStatement 158 5.5 do…whileRepetitionStatement 162 5.6 switchMultiple-SelectionStatement 164 5.7 breakandcontinueStatements 172 5.8 LogicalOperators 173 5.9 StructuredProgrammingSummary 179