This is an electronic version of the print textbook. Due to electronic rights restrictions, some third party content may be suppressed. Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. The publisher reserves the right to remove content from this title at any time if subsequent rights restrictions require it. For valuable information on pricing, previous editions, changes to current editions, and alternate formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for materials in your areas of interest. 1019763_FM_VOL-I.qxp 9/17/07 4:22 PM Page viii 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 S 50 R 51 1st Pass Pages JavaProgramming:FromProblemAnalysis ª2012CourseTechnology,CengageLearning toProgramDesign,FifthEdition ALLRIGHTSRESERVED.Nopartofthisworkcoveredbythe D.S.Malik copyrighthereinmaybereproduced,transmitted,storedorused inanyformorbyanymeansgraphic,electronic,ormechanical, ExecutiveEditor:MarieLee includingbutnotlimitedtophotocopying,recording,scanning, AcquisitionsEditor:BrandiShailer digitizing,taping,Webdistribution,informationnetworks,or SeniorProductManager:AlyssaPratt informationstorageandretrievalsystems,exceptaspermitted EditorialAssistant:JacquelineLacaire underSection107or108ofthe1976UnitedStatesCopyrightAct, withoutthepriorwrittenpermissionofthepublisher. ContentProjectManager:LisaWeidenfeld AssociateMarketingManager:Shanna Forproductinformationandtechnologyassistance,contactusat Shelton CengageLearningCustomer&SalesSupport,1-800-354-9706 ArtDirector:FaithBrosnan Forpermissiontousematerialfromthistextorproduct,submit allrequestsonlineat www.cengage.com/permissions Proofreader:AndreaSchein Furtherpermissionsquestionscanbeemailedto Indexer:AlexandraNickerson [email protected] PrintBuyer:JulioEsperas CoverDesigner:RoycroftDesign/ LibraryofCongressControlNumber:2010940363 www.roycroftdesign.com CoverPhoto:ªphotolibrary/Richard ISBN-13:978-1-111-53053-2 Cummins ISBN-10:1-111-53053-x Compositor:Integra CourseTechnology 20ChannelCenterStreet Boston,MA02210 Someoftheproductnamesandcompany USA namesusedinthisbookhavebeenusedfor identificationpurposesonlyandmaybe trademarksorregisteredtrademarksoftheir CengageLearningisaleadingproviderofcustomized respectivemanufacturersandsellers. learningsolutionswithofficelocationsaroundtheglobe, includingSingapore,theUnitedKingdom,Australia,Mexico, Anyfictionaldatarelatedtopersonsor BrazilandJapan.Locateyourlocalofficeat: companiesorURLsusedthroughoutthis www.cengage.com/global bookisintendedforinstructionalpurposes only.Atthetimethisbookwasprinted,any CengageLearningproductsarerepresentedinCanadaby suchdatawasfictionalandnotbelongingto NelsonEducation,Ltd. anyrealpersonsorcompanies. TolearnmoreaboutCourseTechnology,visit CourseTechnology,apartofCengage www.cengage.com/coursetechnology Learning,reservestherighttorevisethis Purchaseanyofourproductsatyourlocalcollegestore publicationandmakechangesfromtimeto oratourpreferredonlinestorewww.cengagebrain.com timeinitscontentwithoutnotice. Theprogramsinthisbookarefor instructionalpurposesonly.Theyhavebeen testedwithcare,butarenotguaranteedfor anyparticularintentbeyondeducational purposes.Theauthorandthepublisherdo notofferanywarrantiesorrepresentations, nordotheyacceptanyliabilitieswithrespect totheprograms. PrintedintheUnitedStatesofAmerica 1 2 3 4 5 6 7 16 15 14 13 12 11 10 J P AVA ROGRAMMING F P A P D ROM ROBLEM NALYSIS TO ROGRAM ESIGN F E IFTH DITION D.S. M ALIK Australia(cid:2)Brazil(cid:2)Japan(cid:2)Korea(cid:2)Mexico(cid:2)Singapore(cid:2)Spain(cid:2)UnitedKingdom(cid:2)UnitedStates TO My Daughter Shelly Malik B C RIEF ONTENTS PREFACE xix 1. An Overview of Computers and Programming Languages 1 2. Basic Elements of Java 25 3. Introduction to Objects and Input/Output 113 4. Control Structures I: Selection 177 5. Control Structures II: Repetition 249 6. Graphical User Interface (GUI) and Object-Oriented Design (OOD) 327 7. User-Defined Methods 383 8. User-Defined Classes and ADTs 465 9. Arrays 551 10. Inheritance and Polymorphism 639 11. Handling Exceptions and Events 723 12. Advanced GUIs and Graphics 783 13. Recursion 873 14. Searching and Sorting 907 APPENDIX A Java Reserved Words 939 APPENDIX B Operator Precedence 941 APPENDIX C Character Sets 945 APPENDIX D Additional Java Topics 949 APPENDIX E Answers to Odd-Numbered Exercises 997 INDEX 1023 T C ABLE OF ONTENTS Preface xix AN OVERVIEW OF COMPUTERS AND 1 PROGRAMMING LANGUAGES 1 Introduction 2 An Overview of the History of Computers 2 Elements of a Computer System 4 Hardware 4 Software 6 Language of a Computer 6 Evolution of Programming Languages 8 Processing a Java Program 10 Internet, World Wide Web, Browser, and Java 13 Programming with the Problem Analysis–Coding–Execution Cycle 13 Programming Methodologies 19 Structured Programming 19 Object-Oriented Programming 19 Quick Review 21 Exercises 23 TableofContents | vii BASIC ELEMENTS OF JAVA 25 2 A Java Program 26 Basics of a Java Program 28 Comments 29 Special Symbols 30 Reserved Words (Keywords) 30 Identifiers 31 Data Types 32 Primitive Data Types 32 Arithmetic Operators and Operator Precedence 36 Order of Precedence 39 Expressions 40 Mixed Expressions 41 Type Conversion (Casting) 43 class String 45 Strings and the Operator + 46 Input 48 Allocating Memory with Named Constants and Variables 48 Putting Data into Variables 51 Declaring and Initializing Variables 55 Input (Read) Statement 56 Reading a Single Character 61 Increment and Decrement Operators 64 Output 66 Packages, Classes, Methods, and the import Statement 71 Creating a Java Application Program 72 Debugging: Understanding and Fixing Syntax Errors 77 Programming Style and Form 80 Syntax 80 Avoiding Bugs: Consistent, Proper Formatting and Code Walk-Through 84 viii | JavaProgramming:FromProblemAnalysistoProgramDesign,FifthEdition More on Assignment Statements (Optional) 85 Quick Review 94 Exercises 97 Programming Exercises 106 INTRODUCTION TO OBJECTS AND INPUT/OUTPUT 113 3 Objects and Reference Variables 114 Using Predefined Classes and Methods in a Program 118 Dot Between Class (Object) Name and Class Member: A Precaution 120 class String 121 Input/Output 129 Formatting Output with printf 129 Using Dialog Boxes for Input/Output 139 Formatting the Output Using the String Method format 146 File Input/Output 149 Storing (Writing) Output to a File 152 Debugging: Understanding Logic Errors and Debugging with print or println Statements 163 Quick Review 165 Exercises 167 Programming Exercises 171 CONTROL STRUCTURES I: SELECTION 177 4 Control Structures 178 Relational Operators 180 Relational Operators and Primitive Data Types 181 Logical (Boolean) Operators and Logical Expressions 183 Order of Precedence 185 boolean Data Type and Logical (Boolean) Expressions 189