J ™ P AVA FOR ROGRAMMERS S E ECOND DITION D D S EITEL® EVELOPER ERIES Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarks. Wherethosedesignationsappearinthisbook,andthepublisherwasawareofatrademarkclaim,thedesignationshave beenprintedwithinitialcapitallettersorinallcapitals. Theauthorsandpublisherhavetakencareinthepreparationofthisbook,butmakenoexpressedorimpliedwarranty ofanykindandassumenoresponsibilityforerrorsoromissions.Noliabilityisassumedforincidentalorconsequential damagesinconnectionwithorarisingoutoftheuseoftheinformationorprogramscontainedherein. Thepublisheroffersexcellentdiscountsonthisbookwhenorderedinquantityforbulkpurchasesorspecialsales, whichmayincludeelectronicversionsand/orcustomcoversandcontentparticulartoyourbusiness,traininggoals, marketingfocus,andbrandinginterests.Formoreinformation,pleasecontact: U.S.CorporateandGovernmentSales (800)382-3419 [email protected] ForsalesoutsidetheU.S.,pleasecontact: InternationalSales [email protected] VisitusontheWeb:informit.com/ph LibraryofCongressCataloging-in-PublicationData On file ©2012PearsonEducation,Inc. Allrightsreserved.PrintedintheUnitedStatesofAmerica.Thispublicationisprotectedbycopyright,andpermission mustbeobtainedfromthepublisherpriortoanyprohibitedreproduction,storageinaretrievalsystem,ortransmis- sioninanyformorbyanymeans,electronic,mechanical,photocopying,recording,orlikewise.Forinformationre- gardingpermissions,writeto: PearsonEducation,Inc. RightsandContractsDepartment 501BoylstonStreet,Suite900 Boston,MA02116 Fax(617)671-3447 ISBN-13:978-0-13282154-4 ISBN-10:0-13-282154-0 TextprintedintheUnitedStatesonrecycledpaperatRRDonnelleyinCrawfordsville,Indiana. Firstprinting,March2012 J ™ P AVA FOR ROGRAMMERS S E ECOND DITION D D S EITEL® EVELOPER ERIES Paul Deitel Deitel & Associates, Inc. Harvey Deitel Deitel & Associates, Inc. Upper SaddleRiver,NJ• Boston• Indianapolis • SanFrancisco New York• Toronto•Montreal•London •Munich • Paris• Madrid Capetown • Sydney •Tokyo• Singapore• MexicoCity 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. In memory of Clifford “Spike” Stephens, A dear friend who will be greatly missed. Pauland HarveyDeitel This page intentionally left blank Contents Preface xxi Before You Begin xxix 1 Introduction 1 1.1 Introduction 2 1.2 IntroductiontoObjectTechnology 2 1.3 OpenSourceSoftware 5 1.4 JavaandaTypicalJavaDevelopmentEnvironment 7 1.5 Test-DrivingaJavaApplication 11 1.6 Web2.0:GoingSocial 15 1.7 SoftwareTechnologies 18 1.8 KeepingUptoDatewithInformationTechnologies 20 1.9 Wrap-Up 21 2 Introduction to Java Applications 22 2.1 Introduction 23 2.2 YourFirstPrograminJava:PrintingaLineofText 23 2.3 ModifyingYourFirstJavaProgram 27 2.4 DisplayingTextwithprintf 29 2.5 AnotherApplication:AddingIntegers 30 2.6 Arithmetic 34 2.7 DecisionMaking:EqualityandRelationalOperators 35 2.8 Wrap-Up 38 3 Introduction to Classes, Objects, Methods and Strings 39 3.1 Introduction 40 3.2 DeclaringaClasswithaMethodandInstantiatinganObjectofaClass 40 3.3 DeclaringaMethodwithaParameter 44 3.4 InstanceVariables,setMethodsandgetMethods 47 3.5 PrimitiveTypesvs.ReferenceTypes 52 3.6 InitializingObjectswithConstructors 53 viii Contents 3.7 Floating-PointNumbersandTypedouble 56 3.8 Wrap-Up 60 4 Control Statements: Part 1 61 4.1 Introduction 62 4.2 ControlStructures 62 4.3 ifSingle-SelectionStatement 64 4.4 if…elseDouble-SelectionStatement 65 4.5 whileRepetitionStatement 68 4.6 Counter-ControlledRepetition 70 4.7 Sentinel-ControlledRepetition 73 4.8 NestedControlStatements 78 4.9 CompoundAssignmentOperators 81 4.10 IncrementandDecrementOperators 82 4.11 PrimitiveTypes 85 4.12 Wrap-Up 85 5 Control Statements: Part 2 86 5.1 Introduction 87 5.2 EssentialsofCounter-ControlledRepetition 87 5.3 forRepetitionStatement 89 5.4 ExamplesUsingtheforStatement 92 5.5 do…whileRepetitionStatement 96 5.6 switchMultiple-SelectionStatement 98 5.7 breakandcontinueStatements 105 5.8 LogicalOperators 107 5.9 Wrap-Up 113 6 Methods: A Deeper Look 114 6.1 Introduction 115 6.2 ProgramModulesinJava 115 6.3 staticMethods,staticFieldsandClassMath 115 6.4 DeclaringMethodswithMultipleParameters 118 6.5 NotesonDeclaringandUsingMethods 121 6.6 ArgumentPromotionandCasting 122 6.7 JavaAPIPackages 123 6.8 CaseStudy:Random-NumberGeneration 125 6.8.1 GeneralizedScalingandShiftingofRandomNumbers 129 6.8.2 Random-NumberRepeatabilityforTestingandDebugging 129 6.9 CaseStudy:AGameofChance;IntroducingEnumerations 130 6.10 ScopeofDeclarations 134 6.11 MethodOverloading 137 6.12 Wrap-Up 139 Contents ix 7 Arrays and ArrayLists 140 7.1 Introduction 141 7.2 Arrays 141 7.3 DeclaringandCreatingArrays 143 7.4 ExamplesUsingArrays 144 7.5 CaseStudy:CardShufflingandDealingSimulation 153 7.6 EnhancedforStatement 157 7.7 PassingArraystoMethods 159 7.8 CaseStudy:ClassGradeBookUsinganArraytoStoreGrades 162 7.9 MultidimensionalArrays 167 7.10 CaseStudy:ClassGradeBookUsingaTwo-DimensionalArray 171 7.11 Variable-LengthArgumentLists 177 7.12 UsingCommand-LineArguments 178 7.13 ClassArrays 180 7.14 IntroductiontoCollectionsandClassArrayList 183 7.15 Wrap-Up 186 8 Classes and Objects: A Deeper Look 187 8.1 Introduction 188 8.2 TimeClassCaseStudy 188 8.3 ControllingAccesstoMembers 192 8.4 ReferringtotheCurrentObject’sMemberswiththethisReference 193 8.5 TimeClassCaseStudy:OverloadedConstructors 195 8.6 DefaultandNo-ArgumentConstructors 201 8.7 NotesonSetandGetMethods 202 8.8 Composition 203 8.9 Enumerations 206 8.10 GarbageCollectionandMethodfinalize 209 8.11 staticClassMembers 210 8.12 staticImport 213 8.13 finalInstanceVariables 214 8.14 TimeClassCaseStudy:CreatingPackages 215 8.15 PackageAccess 221 8.16 Wrap-Up 222 9 Object-Oriented Programming: Inheritance 224 9.1 Introduction 225 9.2 SuperclassesandSubclasses 226 9.3 protectedMembers 228 9.4 RelationshipbetweenSuperclassesandSubclasses 228 9.4.1 CreatingandUsingaCommissionEmployeeClass 229 9.4.2 CreatingandUsingaBasePlusCommissionEmployeeClass 235 9.4.3 CreatingaCommissionEmployee–BasePlusCommissionEmployee InheritanceHierarchy 240