web programming with java 5 index

33
ABSOLUTE JAVA TM 5 th EditionThis page intentionally left blankABSOLUTE JAVA TM 5 th Edition Walter Savitch University of California, San Diego Contributor Kenrick Mock University of Alaska Anchorage Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montréal Toronto Delhi Mexico City São Paulo Sydney Hong Kong Seoul Singapore Taipei TokyoVice President and Editorial Director, ECS: Marcia Horton Editor in Chief: Michael Hirsch Executive Editor: Matt Goldstein Editorial Assistant: Emma Snider Vice President Marketing: Patrice Jones Marketing Manager: Yez Alayan Marketing Coordinator: Kathryn Ferranti Vice President and Director of Production: Vince O’Brien Managing Editor: Jeff Holcomb Senior Production Project Manager: Marilyn Lloyd Manufacturing Manager: Nick Skilitis Operations Specialist: Lisa McDowell Text Designer: Joyce Cosentino Wells Cover Designer: Anthony Gemmellaro Cover Image: B0NGR1 Alamy Media Editor: Dan Sandin Text Permissions—assessment: Dana Weightman Text Permissions—clearance: Jenn Kennett/Creative Compliance Full-Service Vendor: GEX Publishing Services Project Management: GEX Publishing Services Printer/Binder: Edwards Brothers

Upload: albertin84

Post on 27-Dec-2015

29 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Web Programming With Java 5 Index

ABSOLUTEJAVATM5 th EditionThis page intentionally left blankABSOLUTEJAVATM5 th EditionWalter SavitchUniversity of California, San DiegoContributorKenrick MockUniversity of Alaska AnchorageBoston Columbus Indianapolis New York San Francisco Upper Saddle RiverAmsterdam Cape Town Dubai London Madrid Milan Munich Paris Montréal TorontoDelhi Mexico City São Paulo Sydney Hong Kong Seoul Singapore Taipei TokyoVice President and EditorialDirector, ECS: Marcia HortonEditor in Chief: Michael HirschExecutive Editor: Matt GoldsteinEditorial Assistant: Emma SniderVice President Marketing: Patrice JonesMarketing Manager: Yez AlayanMarketing Coordinator: Kathryn FerrantiVice President and Director ofProduction: Vince O’BrienManaging Editor: Jeff HolcombSenior Production Project Manager: Marilyn LloydManufacturing Manager: Nick SkilitisOperations Specialist: Lisa McDowellText Designer: Joyce Cosentino WellsCover Designer: Anthony GemmellaroCover Image: B0NGR1 AlamyMedia Editor: Dan SandinText Permissions—assessment: Dana WeightmanText Permissions—clearance: Jenn Kennett/CreativeComplianceFull-Service Vendor: GEX Publishing ServicesProject Management: GEX Publishing ServicesPrinter/Binder: Edwards BrothersCover Printer: Lehigh-Phoenix ColorThis book was composed in InDesign. Basal font is Adobe Garamond 10/12. Display font is Optima LT Std.Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbookappear on the appropriate page within text.Copyright © 2013, 2010, 2008, 2006, 2004 by Pearson Education, Inc., publishing as Addison-Wesley. Allrights reserved. Manufactured in the United States of America. This publication is protected by Copyright, and

Page 2: Web Programming With Java 5 Index

permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrievalsystem, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, orlikewise. To obtain permission(s) to use material from this work, please submit a written request to PearsonEducation, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or youmay fax your request to 201-236-3290.Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks.Where those designations appear in this book, and the publisher was aware of a trademark claim, the designa-tions have been printed in initial caps or all caps.CIP data available upon request10 9 8 7 6 5 4 3 2 1ISBN 10: 0-13-283031-0ISBN 13: 978-0-13-283031-7PrefaceThis book is designed to serve as a textbook and reference for programming in theJava language. Although it does include programming techniques, it is organizedaround the features of the Java language rather than any particular curriculum ofprogramming techniques. The main audience I had in mind when writing this bookwas undergraduate students who have not had extensive programming experience withthe Java language. As such, it would be a suitable Java text or reference for either a firstprogramming course or a later computer science course that uses Java. This book isdesigned to accommodate a wide range of users. The introductory chapters are writtenat a level that is accessible to beginners, while the boxed sections of those chaptersserve to quickly introduce more experienced programmers to basic Java syntax. Laterchapters are still designed to be accessible, but are written at a level suitable for studentswho have progressed to these more advanced topics.CHANGES IN THIS EDITIONThis fifth edition presents the same programming philosophy as the fourth edition.For instructors, you can teach the same course, presenting the same topics in the sameorder with no changes in the material covered or the chapters assigned. The changes tothis edition consist almost exclusively of supplementary material added to the chaptersof the previous edition, namely:■■■■■■■■■Updates have been made for language changes in Java 7, such as allowing strings inswitch statements.Twenty-five new programming projects have been added. By request, some of theseare longer and less prescriptive projects to give the student more practice designing

Page 3: Web Programming With Java 5 Index

programming solutions.15 new video notes have been created for a total of 46 video notes. These videos coverspecific topics and offer solutions to the programming projects; they have been added tothe book’s website. The solutions walk students through the process of problem solvingand coding to reinforce key programming concepts. An icon appears in the margin ofthe book when a video is available regarding the corresponding topic in the text.Chapter 2 now describes how to use the Scanner class to read from a text file so data-based programming projects can be explored prior to detailed coverage of File I/O inChapter 10.A brief introduction to the Random class has been added to Chapter 3.Chapter 9 on exception handling begins with a new introduction of try/catchfor handling input mismatch exceptions before discussing how to throw customexceptions.A recursive algorithm to search the file system has been added to Chapter 11.Material on race conditions and thread synchronization has been added toChapter 19.Ten new self-test exercises have been added along with the new material.vviPrefaceNO NONSTANDARD SOFTWAREOnly classes in the standard Java libraries are used. No nonstandard software is usedanywhere in the book.JAVA COVERAGEAll programs have been tested with Java 7. Oracle is not proposing any changes tofuture versions of Java that would affect the approach in this book.OBJECT-ORIENTED PROGRAMMINGThis book gives extensive coverage of encapsulation, inheritance, and polymorphismas realized in the Java language. The chapters on Swing GUIs provide coverage of andextensive practice with event driven programming. A chapter on UML and patternsgives additional coverage of OOP-related material.FLEXIBILITY IN TOPIC ORDERINGThis book allows instructors wide latitude in reordering the material. This is importantif a book is to serve as a reference. It is also in keeping with my philosophy of writingbooks that accommodate themselves to an instructor’s style rather than tying theinstructor to an author’s personal preference of topic ordering. With this in mind, eachchapter has a prerequisite section at the beginning; this section explains what materialmust be covered before doing each section of the chapter. Starred sections, which areexplained next, further add to flexibility.STARRED SECTIONSEach chapter has a number of starred ( ) sections, which can be considered optional.★These sections contain material that beginners might find difficult and that can beomitted or delayed without hurting the continuity of the text. It is hoped that eventuallythe reader would return and cover this material. For more advanced students, thestarred sections should not be viewed as optional.ACCESSIBLE TO STUDENTSIt is not enough for a book to present the right topics in the right order. It is not evenenough for it to be clear and correct when read by an instructor or other expert. Thematerial needs to be presented in a way that is accessible to the person who does not yetknow the content. Like my other textbooks that have proven to be very popular, this

Page 4: Web Programming With Java 5 Index

book was written to be friendly and accessible to the student.SUMMARY BOXESEach major point is summarized in a short boxed section. These boxed sections arespread throughout each chapter. They serve as summaries of the material, as a quickreference source, and as a way to quickly learn the Java syntax for features the readerknows about in general but for which he or she needs to know the Java particulars.PrefaceSELF-TEST EXERCISESEach chapter contains numerous Self-Test Exercises at strategic points in the chapter.Complete answers for all the Self-Test Exercises are given at the end of each chapter.VIDEO NOTESVideoNoteVideoNotes are step-by-step videos that guide readers through the solution to an end-of-chapter problem or further illuminate a concept presented in the text. Icons in thetext indicate where a VideoNote enhances a topic. Fully navigable problems allow forself-paced instruction. VideoNotes are located at www.pearsonhighered.com/savitch.OTHER FEATURESPitfall sections, programming tip sections, and examples of complete programs withsample I/O are given throughout each chapter. Each chapter ends with a summarysection and a collection of programming projects suitable to assign to students.ONLINE PRACTICE AND ASSESSMENT WITHMyProgrammingLabMyProgrammingLab helps students fully grasp the logic, semantics, and syntax ofprogramming. Through practice exercises and immediate, personalized feedback,MyProgrammingLab improves the programming competence of beginning studentswho often struggle with the basic concepts and paradigms of popular high-levelprogramming languages.A self-study and homework tool, a MyProgrammingLab course consists of hundredsof small practice problems organized around the structure of this textbook. Forstudents, the system automatically detects errors in the logic and syntax of their codesubmissions and offers targeted hints that enable students to figure out what wentwrong—and why. For instructors, a comprehensive gradebook tracks correct andincorrect answers and stores the code inputted by students for review.MyProgrammingLab is offered to users of this book in partnership with Turing’sCraft, the makers of the CodeLab interactive programming exercise system. For a fulldemonstration, to see feedback from instructors and students, or to get started usingMyProgrammingLab in your course, visit www.myprogramminglab.com.SUPPORT MATERIALThe following support materials are available to all users of this book at www.pearsonhighered.com/cssupport:■Source code from the bookThe following resources are available to qualifi ed instructors only at www. pearsonhighered.com/irc. Please contact your local sales representative for access information:■■Instructor’s Manual with SolutionsPowerPoint ® slidesviiviiiPreface

Page 5: Web Programming With Java 5 Index

Integrated Development Environment Resource KitsProfessors who adopt this text can order it for students with a kit containing seven popularJava IDEs (the most recent JDK from Oracle, Eclipse, NetBeans, jGRASP, DrJava, BlueJ,and TextPad). The kit also includes access to a website containing written and videotutorials for getting started in each IDE. For ordering information, please contact yourcampus Pearson Education representative or visit www.pearsonhighered.com.ACKNOWLEDGMENTSNumerous individuals have contributed invaluable help and support in making thisbook happen: My former editor, Susan Hartman at Addison-Wesley, fi rst conceivedof the idea for this book and worked with me on the fi rst editions; My current edi-tor, Matt Goldstein, provided support and inspiration for getting subsequent editionsreviewed, revised, and out the door; Chelsea Kharakozova, Marilyn Lloyd, Yez Alayan,and the other fi ne people at Pearson also provided valuable assistance and encourage-ment. Thanks also to GEX Publishing Services for their expert work in producing thefi nal typeset book.The following reviewers provided corrections and suggestions for this book. Theircontributions were a great help. I thank them all. In alphabetical order they are:Jim AdamsGerald W. AdkinsDr. Bay ArinzeProf. Richard G. BaldwinKevin BierreJon BjornstadJanet Brown-SederbergTom BrownCharlotte BuschStephen ChandlerKY Daisy FanAdrienne DeckerBrian DownsKeith FrikkenAhmad GhafarianArthur GeisMassoud GhyamSusan G. GlennNigel GweeJudy HankinsMay HouChandler-Gilbert Community CollegeGeorgia College & State UniversityDrexel UniversityAustin Community CollegeRochester Institute of TechnologyGavilan CollegeMassasoit Community CollegeTexas A&M University, CommerceTexas A&M University, Corpus ChristiNW Shoals Community CollegeCornell University

Page 6: Web Programming With Java 5 Index

University of BuffaloCentury CollegeMiami UniversityNorth Georgia College & State UniversityCollege of DuPageUniversity of Southern CaliforniaGordon CollegeLouisiana State UniversityMiddle Tennessee State UniversityNorfolk State UniversityPrefaceSterling HoughChris HowardEliot JacobsonBalaji JanamanchiSuresh KalathurEdwin KayDr. Clifford R. KettemboroughFrank LeveyXia LinMark M. MeysenburgSridhar P. NerurHoang M. NguyenRick OrdProf. Bryson R. PayneDavid PrimeauxNeil RhodesW. Brent SealesLili ShashaaniRiyaz SikoraJeff SixDonald J SmithTom SmithXueqing (Clare) TangRonald F. TaylorThomas VanDrunenShon VickNatalie S. WearDale WelchDavid A. WheelerWook-Sung YooNHTIDeVry UniversityUniversity of California, Santa BarbaraTexas Tech UniversityBoston UniversityLehigh UniversityIT Consultant and ProfessorManatee Community CollegeDrexel University

Page 7: Web Programming With Java 5 Index

Doane CollegeThe University of Texas at ArlingtonDeanza CollegeUniversity of California, San DiegoNorth Georgia College & State UniversityVirginia Commonwealth UniversityUniversity of California, San DiegoUniversity of KentuckyDuquesne UniversityThe University of Texas at ArlingtonUniversity of DelawareCommunity College of Allegheny CountySkidmore CollegeGovernors State UniversityWright State UniversityWheaton CollegeUniversity of Maryland, Baltimore CountyUniversity of South FloridaUniversity of West FloridaGannon UniversitySpecial thanks goes to Kenrick Mock (University of Alaska Anchorage) whoexecuted the updating of this edition. He once again had the difficult job of satisfyingme, the editor, and himself. I thank him for a truly excellent job.Walter SavitchixLOCATION OF VIDEONOTES IN THE TEXTVideoNotewww.pearsonhighered.com/savitchChapter 1 Compiling a Java Program, page 10Solution to Programming Project 1.7, page 56Chapter 2 Pitfalls Involving nextLine() , page 83Solution to Programming Project 2.11, page 97Solution to Programming Project 2.12, page 98Chapter 3 Nested Loop Example, page 145Debugging Walkthrough, page 152Solution to Programming Project 3.9, page 170Solution to Programming Project 3.13, page 171Chapter 4 Information Hiding Example, page 207Example Using the StringTokenizer Class on a CSV File, page 247Solution to Programming Project 4.9, page 255Chapter 5 Deep Copy vs. Shallow Copy Example, page 321Solution to Programming Project 5.9, page 344Chapter 6 Arrays of Objects, page 358Solution to Programming Project 6.8, page 422Solution to Programming Project 6.15, page 424Chapter 7 Inheritance Walkthrough, page 432Solution to Programming Project 7.3, page 477Solution to Programming Project 7.5, page 479Chapter 8 Late Binding Example, page 486Solution to Programming Project 8.1, page 518

Page 8: Web Programming With Java 5 Index

Solution to Programming Project 8.9, page 521Chapter 9 Solution to Programming Project 9.1, page 574Solution to Programming Project 9.7, page 576Chapter 10 Reading a Text File, page 589Solution to Programming Project 10.1, page 643Solution to Programming Project 10.8, page 645Chapter 11 Recursion and the Stack, page 660Solution to Programming Project 11.3, page 684Chapter 12 Solution to Programming Project 12.9, page 710Chapter 13 Solution to Programming Project 13.1, page 754Solution to Programming Project 13.11, page 757Chapter 14 Solution to Programming Project 14.7, page 801Chapter 15 Walkthrough of the Hash Table Class, page 868Solution to Programming Project 15.1, page 893Chapter 16 Solution to Programming Project 16.3, page 937Solution to Programming Project 16.5, page 938Chapter 17 GUI Layout Using an IDE, page 969Solution to Programming Project 17.1, page 1013Chapter 18 Walkthrough of a Simple Drawing Program, page 1042Solution to Programming Project 18.7, page 1077Chapter 19 Walkthrough of a Program with Race Conditions, page 1094Solution to Programming Project 19.3, page 1135Solution to Programming Project 19.11, page 1136Chapter 20 No video notes (Chapter on website)This page intentionally left blankBrief ContentsChapter 1Chapter 2Chapter 3Chapter 4Chapter 5Chapter 6Chapter 7Chapter 8Chapter 9Chapter 10Chapter 11Chapter 12Chapter 13Chapter 14Chapter 15Chapter 16Chapter 17Chapter 18Chapter 19Chapter 20Appendix 1Appendix 2Appendix 3Appendix 4Appendix 5

Page 9: Web Programming With Java 5 Index

GETTING STARTED1CONSOLE INPUT AND OUTPUT 57FLOW OF CONTROL 99DEFINING CLASSES I 173DEFINING CLASSES II 259ARRAYS 345INHERITANCE427POLYMORPHISM AND ABSTRACT CLASSES 483EXCEPTION HANDLING 523FILE I/O577RECURSION 647UML AND PATTERNS 689INTERFACES AND INNER CLASSES 711GENERICS AND THE ArrayList CLASS 759LINKED DATA STRUCTURES 801COLLECTIONS, MAPS AND ITERATORS 897SWING ISWING II9411017JAVA NEVER ENDS1079APPLETS AND HTML 1137KEYWORDS 1139PRECEDENCE AND ASSOCIATIVITY RULES 1141ASCII CHARACTER SET 1143FORMAT SPECIFICATIONS FOR printf1145SUMMARY OF CLASSES AND INTERFACES 1147INDEX 1215xiiiThis page intentionally left blankContentsChapter 11.11.2Getting Started 1INTRODUCTION TO JAVA 2Origins of the Java Language 2★Objects and Methods 3Applets 4★A Sample Java Application Program 5Byte-Code and the Java Virtual Machine 8Class Loader 10★Compiling a Java Program or Class 10Running a Java Program 11TIP: Error Messages 12EXPRESSIONS AND ASSIGNMENT STATEMENTS 13

Page 10: Web Programming With Java 5 Index

Identifi ers 13Variables 15Assignment Statements 16TIP: Initialize Variables 18More Assignment Statements 19★Assignment Compatibility 20Constants 21Arithmetic Operators and Expressions 23Parentheses and Precedence Rules 24★Integer and Floating-Point Division 26PITFALL: Round-Off Errors in Floating-Point NumbersPITFALL: Division with Whole Numbers 28Type Casting 29Increment and Decrement Operators 301.327THE CLASS String 33String Constants and Variables 33Concatenation of Strings 34Classes 35String Methods 37Escape Sequences 42String Processing 43The Unicode Character Set 43★xvxviContents1.4PROGRAM STYLE46Naming Constants 46Java Spelling Conventions 48Comments 49Indenting 50Chapter Summary 51Answers to Self-Test Exercises 52Programming Projects 54Chapter 22.1Console Input and OutputSCREEN OUTPUT575858TIP: Different Approaches to Formatting Output 61Formatting Output with printf 61TIP: Formatting Monetary Amounts with printf 65TIP: Legacy Code 66Money Formats Using NumberFormat 67★Importing Packages and Classes 70

Page 11: Web Programming With Java 5 Index

The DecimalFormat Class 72★System.out.println2.2CONSOLE INPUT USING THE Scanner CLASSThe Scanner Class 76PITFALL: Dealing with the Line Terminator, '\n'The Empty String 84TIP: Prompt for Input 84TIP: Echo Input 84EXAMPLE: Self-Service Checkout 86Other Input Delimiters 872.3INTRODUCTION TO FILE INPUT 89The Scanner Class for Text File InputChapter Summary 92Answers to Self-Test Exercises 92Programming Projects 95Chapter 33.1Flow of Control99BRANCHING MECHANISMif-else Statements 100Omitting the else 101Compound Statements 102TIP: Placing of Braces 103Nested Statements 104100898376ContentsMultiway if-else Statement 104EXAMPLE: State Income Tax 105The switch Statement 107PITFALL: Forgetting a break in a switch StatementThe Conditional Operator 112★3.2111BOOLEAN EXPRESSIONS 113Simple Boolean Expressions 113PITFALL: Using = in Place of == 114PITFALL: Using == with Strings 115Lexicographic and Alphabetical Order 116Building Boolean Expressions 119PITFALL: Strings of Inequalities 120Evaluating Boolean Expressions 120TIP: Naming Boolean Variables 123Short-Circuit and Complete Evaluation 124Precedence and Associativity Rules 125

Page 12: Web Programming With Java 5 Index

3.3LOOPS132while Statement and do-while Statement132Algorithms and Pseudocode 134EXAMPLE: Averaging a List of Scores 137The for Statement 138The Comma in for Statements 141TIP: Repeat N Times Loops 143PITFALL: Extra Semicolon in a for Statement 143PITFALL: Infi nite Loops 144Nested Loops 145The break and continue Statements 148★The exit Statement 1493.4DEBUGGING150Loop Bugs 150Tracing Variables 150General Debugging Techniques 151EXAMPLE: Debugging an Input Validation LoopPreventive Coding 156Assertion Checks 157★3.5RANDOM NUMBER GENERATION ★The Random Object 160The Math.random() Method 161Chapter Summary 162Answers to Self-Test ExercisesProgramming Projects 168162159152xviixviiiContentsChapter 44.1Defi ning Classes I173CLASS DEFINITIONS 174Instance Variables and Methods 177More about Methods 180TIP: Any Method Can Be Used as a void Method 184Local Variables 186Blocks 187TIP: Declaring Variables in a for Statement 188Parameters of a Primitive Type 188PITFALL: Use of the Terms “Parameter” and “Argument” 195

Page 13: Web Programming With Java 5 Index

Simple Cases with Class Parameters 197The this Parameter 197Methods That Return a Boolean Value 199The Methods equals and toString 202Recursive Methods 205TIP: Testing Methods 2054.2INFORMATION HIDING AND ENCAPSULATION 207public and private Modifi ers208EXAMPLE: Yet Another Date Class 209Accessor and Mutator Methods 210TIP: A Class Has Access to Private Members of All Objects of the Class 215TIP: Mutator Methods Can Return a Boolean Value 216★Preconditions and Postconditions 2174.3OVERLOADING 218Rules for Overloading 218PITFALL: Overloading and Automatic Type Conversion 222PITFALL: You Cannot Overload Based on the Type Returned 2244.4CONSTRUCTORS226Constructor Defi nitions 226TIP: You Can Invoke Another Method in a Constructor 234TIP: A Constructor Has a this Parameter 234TIP: Include a No-Argument Constructor 235EXAMPLE: The Final Date Class 236Default Variable Initializations 237An Alternative Way to Initialize Instance Variables 237EXAMPLE: A Pet Record Class 238The StringTokenizer Class 242★Chapter Summary 247Answers to Self-Test Exercises 248Programming Projects 253ContentsChapter 55.1Defi ning Classes II 259STATIC METHODS AND STATIC VARIABLES 261Static Methods 261PITFALL: Invoking a Nonstatic Method Within a Static Method 263TIP: You Can Put a main in Any Class 264Static Variables 268The Math Class 273Wrapper Classes 277Automatic Boxing and Unboxing 278Static Methods in Wrapper Classes 280PITFALL: A Wrapper Class Does Not Have a No-Argument Constructor5.2

Page 14: Web Programming With Java 5 Index

REFERENCES AND CLASS PARAMETERS 284Variables and Memory 285References 286Class Parameters 291PITFALL: Use of = and == with Variables of a Class Type 295The Constant null 297PITFALL: Null Pointer Exception 298The new Operator and Anonymous Objects 298EXAMPLE: Another Approach to Keyboard Input 299★TIP: Use Static Imports 301★5.3USING AND MISUSING REFERENCES 303EXAMPLE: A Person Class 304PITFALL: null Can Be an Argument to a Method 309Copy Constructors 313PITFALL: Privacy Leaks 315Mutable and Immutable Classes 319TIP: Deep Copy versus Shallow Copy 321TIP: Assume Your Coworkers Are Malicious 3225.4PACKAGES AND javadoc 322Packages and import Statements 323The Package java.lang 324Package Names and Directories 324PITFALL: Subdirectories Are Not Automatically Imported 327The Default Package 327PITFALL: Not Including the Current Directory in Your Class PathSpecifying a Class Path When You Compile 328★Name Clashes 329★Introduction to javadoc 330★Commenting Classes for javadoc 330★Running javadoc 332★328283xixxxContentsChapter Summary 334Answers to Self-Test ExercisesProgramming Projects 339Chapter 66.1Arrays335345INTRODUCTION TO ARRAYS 346Creating and Accessing Arrays 347The length Instance Variable 350TIP: Use for Loops with Arrays 352PITFALL: Array Indices Always Start with Zero 352

Page 15: Web Programming With Java 5 Index

PITFALL: Array Index Out of Bounds 352Initializing Arrays 353PITFALL: An Array of Characters Is Not a String 3556.2ARRAYS AND REFERENCES 356Arrays Are Objects 356PITFALL: Arrays with a Class Base Type 358Array Parameters 358PITFALL: Use of = and == with Arrays 360Arguments for the Method main 365★Methods that Return an Array 3676.3PROGRAMMING WITH ARRAYS 368Partially Filled Arrays 369EXAMPLE: A Class for Partially Filled Arrays 372TIP: Accessor Methods Need Not Simply Return Instance Variables 376The “for-each” Loop 376★Methods with a Variable Number of Parameters 380★EXAMPLE: A String Processing Example 383★Privacy Leaks with Array Instance Variables 384Enumerated Types 386★EXAMPLE: Sorting an Array 388TIP: Enumerated Types in switch Statements 397★6.4MULTIDIMENSIONAL ARRAYS 399Multidimensional Array Basics 399Using the length Instance Variable 402Ragged Arrays 403★Multidimensional Array Parameters and Returned ValuesEXAMPLE: A Grade Book Class 404Chapter Summary 410Answers to Self-Test ExercisesProgramming Projects 418411403ContentsChapter 77.1Inheritance 427INHERITANCE BASICS 428Derived Classes 429Overriding a Method Defi nition 439Changing the Return Type of an Overridden Method 439Changing the Access Permission of an Overridden Method 440PITFALL: Overriding versus Overloading 441The super Constructor 442The this Constructor 444TIP: An Object of a Derived Class Has More than One Type 445PITFALL: The Terms Subclass and Superclass 448EXAMPLE: An Enhanced StringTokenizer Class 449★

Page 16: Web Programming With Java 5 Index

7.2ENCAPSULATION AND INHERITANCE 452PITFALL: Use of Private Instance Variables from the Base Class 453PITFALL: Private Methods Are Effectively Not Inherited 454Protected and Package Access 455PITFALL: Forgetting about the Default Package 458PITFALL: A Restriction on Protected Access 458★7.3PROGRAMMING WITH INHERITANCE 461TIP: Static Variables Are Inherited 461TIP: “is a” versus “has a” 461Access to a Redefi ned Base Method 461PITFALL: You Cannot Use Multiple super s 463The Class Object 464The Right Way to Defi ne equals 465TIP: getClass versus instanceof 467★Chapter Summary 472Answers to Self-Test ExercisesProgramming Projects 476Chapter 88.1473Polymorphism and Abstract Classes 483POLYMORPHISM484Late Binding 485The final Modifi er 487EXAMPLE: Sales Records 488Late Binding with toString 495PITFALL: No Late Binding for Static MethodsDowncasting and Upcasting 497PITFALL: Downcasting 501496xxixxiiContentsTIP: Checking to See Whether Downcasting Is Legitimate 501★A First Look at the clone Method 504PITFALL: Sometimes the clone Method Return Type Is Object 505PITFALL: Limitations of Copy Constructors 506★8.2ABSTRACT CLASSES509Abstract Classes 510PITFALL: You Cannot Create Instances of an Abstract ClassTIP: An Abstract Class Is a Type 515514Chapter Summary 516Answers to Self-Test Exercises 516Programming Projects 518

Page 17: Web Programming With Java 5 Index

Chapter 99.1Exception Handling 523EXCEPTION HANDLING BASICS 525try-catch Mechanism525Exception Handling with the Scanner Class 527TIP: Exception Controlled Loops 528Throwing Exceptions 530EXAMPLE: A Toy Example of Exception Handling 532Exception Classes 537Exception Classes from Standard Packages 538Defi ning Exception Classes 540TIP: Preserve getMessage 544TIP: An Exception Class Can Carry a Message of Any TypeMultiple catch Blocks 551PITFALL: Catch the More Specifi c Exception First 5539.2546THROWING EXCEPTIONS IN METHODS 556Throwing an Exception in a Method 556Declaring Exceptions in a throws Clause 558Exceptions to the Catch or Declare Rule 561throws Clause in Derived Classes 562When to Use Exceptions 563Event-Driven Programming 564★9.3MORE PROGRAMMING TECHNIQUES FOR EXCEPTIONHANDLING 566PITFALL: Nested try-catch Blocks 566The finally Block 566★Rethrowing an Exception 568★The AssertionError Class 568★ArrayIndexOutOfBoundsException 569ContentsChapter Summary 569Answers to Self-Test ExercisesProgramming Projects 574Chapter 1010.1File I/O577INTRODUCTION TO FILE I/O 578Streams 578Text Files and Binary Files10.2570TEXT FILES579580

Page 18: Web Programming With Java 5 Index

Writing to a Text File 580PITFALL: A try Block Is a Block 586PITFALL: Overwriting an Output File 586Appending to a Text File 587TIP: toString Helps with Text File Output 588Reading from a Text File 589Reading a Text File Using Scanner 589Testing for the End of a Text File with Scanner 592Reading a Text File Using BufferedReader 599TIP: Reading Numbers with BufferedReader 603Testing for the End of a Text File with BufferedReader 603Path Names 605Nested Constructor Invocations 606System.in, System.out, and System.err 60710.3THE File CLASS 609Programming with the File Class10.4BINARY FILES ★609613Writing Simple Data to a Binary File 614UTF and writeUTF 618Reading Simple Data from a Binary File 619Checking for the End of a Binary File 624PITFALL: Checking for the End of a File in the Wrong WayBinary I/O of Objects 626The Serializable Interface 627PITFALL: Mixing Class Types in the Same File 630Array Objects in Binary Files 63010.5RANDOM ACCESS TO BINARY FILES ★632Reading and Writing to the Same File 632PITFALL: RandomAccessFile Need Not Start Empty638625xxiiixxivContentsChapter Summary 638Answers to Self-Test Exercises 639Programming Projects 643Chapter 1111.1Recursion 647RECURSIVE Void METHODS 649EXAMPLE: Vertical Numbers 649Tracing a Recursive Call 652A Closer Look at Recursion 655

Page 19: Web Programming With Java 5 Index

PITFALL: Infi nite Recursion 657Stacks for Recursion 658★PITFALL: Stack Overfl ow 660★Recursion versus Iteration 66011.2RECURSIVE METHODS THAT RETURN A VALUE 661General Form for a Recursive Method That Returns a ValueEXAMPLE: Another Powers Method 66211.3THINKING RECURSIVELY 667Recursive Design Techniques 667Binary Search 668★Effi ciency of Binary Search 674★EXAMPLE: Finding a File 676Chapter Summary 679Answers to Self-Test Exercises 679Programming Projects 684Chapter 1212.1UML and PatternsUML689690History of UML 691UML Class Diagrams 691Class Interactions 692Inheritance Diagrams 692More UML 69412.2PATTERNS ★695Adaptor Pattern 695★The Model-View-Controller Pattern 696★EXAMPLE: A Sorting Pattern 697Restrictions on the Sorting Pattern 703Effi ciency of the Sorting Pattern 703★662ContentsTIP: Pragmatics and PatternsPattern Formalism 704Chapter Summary 705Answers to Self-Test ExercisesProgramming Projects 707Chapter 1313.1704705Interfaces and Inner Classes 711INTERFACES 713Interfaces 713

Page 20: Web Programming With Java 5 Index

Abstract Classes Implementing Interfaces 715Derived Interfaces 715PITFALL: Interface Semantics Are Not Enforced 717The Comparable Interface 719EXAMPLE: Using the Comparable Interface 720Defi ned Constants in Interfaces 725PITFALL: Inconsistent Interfaces 726The Serializable Interface 729★The Cloneable Interface 72913.2SIMPLE USES OF INNER CLASSES734Helping Classes 734TIP: Inner and Outer Classes Have Access to Each Other’s Private Members 735EXAMPLE: A Bank Account Class 735The .class File for an Inner Class 739PITFALL: Other Uses of Inner Classes 74013.3MORE ABOUT INNER CLASSES740Static Inner Classes 740Public Inner Classes 741TIP: Referring to a Method of the Outer ClassNesting Inner Classes 745Inner Classes and Inheritance 745Anonymous Classes 746TIP: Why Use Inner Classes? 748Chapter Summary 749Answers to Self-Test ExercisesProgramming Projects 754Chapter 1414.1743749Generics and the ArrayList Class 759THE ArrayList CLASS 761Using the ArrayList Class 762TIP: Summary of Adding to an ArrayList 766xxvxxviContentsMethods in the Class ArrayList 767The “for-each” Loop 770EXAMPLE: Golf Scores 773TIP: Use trimToSize to Save Memory 776PITFALL: The clone Method Makes a Shallow Copy 776★The Vector Class 777Parameterized Classes and Generics 778PITFALL: Nonparameterized ArrayList and Vector Classes 77814.2

Page 21: Web Programming With Java 5 Index

GENERICS778Generic Basics 779TIP: Compile with the -Xlint Option 781EXAMPLE: A Generic Class for Ordered Pairs 781PITFALL: A Generic Constructor Name Has No Type Parameter 784PITFALL: You Cannot Plug in a Primitive Type for a Type Parameter 785PITFALL: A Type Parameter Cannot Be Used Everywhere a Type NameCan Be Used 785PITFALL: An Instantiation of a Generic Class Cannot be an Array Base Type 786TIP: A Class Defi nition Can Have More Than One Type Parameter 787PITFALL: A Generic Class Cannot Be an Exception Class 788Bounds for Type Parameters 789TIP: Generic Interfaces 792Generic Methods 792★Inheritance with Generic Classes 794★Chapter Summary 796Answers to Self-Test ExercisesProgramming Projects 799Chapter 1515.1796Linked Data Structures 801JAVA LINKED LISTS804EXAMPLE: A Simple Linked List Class 804Working with Linked Lists 808PITFALL: Privacy Leaks 813Node Inner Classes 814EXAMPLE: A Generic Linked List 817PITFALL: Using Node Instead of Node<T> 822The equals Method for Linked Lists 82215.2COPY CONSTRUCTORS AND THE clone METHOD ★Simple Copy Constructors and clone Methods 824★Exceptions 825★824ContentsPITFALL: The clone Method Is Protected in object 827★TIP: Use a Type Parameter Bound for a Better clone 828★EXAMPLE: A Linked List with a Deep Copy clone Method 832★TIP: Cloning Is an “All or Nothing” Affair 83515.3ITERATORS835Defi ning an Iterator Class 836Adding and Deleting Nodes 84115.4VARIATIONS ON A LINKED LIST 846

Page 22: Web Programming With Java 5 Index

Doubly Linked List 846The Stack Data Structure 855The Queue Data Structure 857Running Times and Big- O NotationEffi ciency of Linked Lists 86515.5HASH TABLES WITH CHAINING860866A Hash Function for Strings 867Effi ciency of Hash Tables 87015.6SETS871Fundamental Set Operations 872Effi ciency of Sets Using Linked Lists15.7TREES877878Tree Properties 878EXAMPLE: A Binary Search Tree Class 881★Effi ciency of Binary Search Trees 886★Chapter Summary 887Answers to Self-Test ExercisesProgramming Projects 893Chapter 1616.1888Collections, Maps and Iterators 897COLLECTIONS 898Wildcards 900The Collection Framework 900PITFALL: Optional Operations 906TIP: Dealing with All Those Exceptions 907Concrete Collection Classes 908Differences between ArrayList<T> and Vector<T> 918Nonparameterized Version of the Collection Framework ★PITFALL: Omitting the <T> 919918xxviixxviiiContents16.2MAPS919Concrete Map Classes16.3ITERATORS922

Page 23: Web Programming With Java 5 Index

926The Iterator Concept 926The Iterator<T> Interface 926TIP: For-Each Loops as Iterators 929List Iterators 930PITFALL: next Can Return a Reference 932TIP: Defi ning Your Own Iterator Classes 934Chapter Summary 935Answers to Self-Test Exercises 935Programming Projects 936Chapter 1717.1Swing I941EVENT-DRIVEN PROGRAMMING 943Events and Listeners17.2943BUTTONS, EVENTS, AND OTHER SWING BASICS 944EXAMPLE: A Simple Window 945PITFALL: Forgetting to Program the Close-Window Button 950Buttons 951Action Listeners and Action Events 952PITFALL: Changing the Heading for actionPerformed 954TIP: Ending a Swing Program 954EXAMPLE: A Better Version of Our First Swing GUI 955Labels 958Color 959EXAMPLE: A GUI with a Label and Color 96017.3CONTAINERS AND LAYOUT MANAGERS962Border Layout Managers 963Flow Layout Managers 966Grid Layout Managers 967Panels 971EXAMPLE: A Tricolor Built with Panels 972The Container Class 976TIP: Code a GUI’s Look and Actions Separately 979The Model-View-Controller Pattern 980Contents★17.4MENUS AND BUTTONS 981EXAMPLE: A GUI with a Menu 981Menu Bars, Menus, and Menu Items 981Nested Menus 986★The AbstractButton Class 986The setActionCommand Method 989Listeners as Inner Classes 990★17.5

Page 24: Web Programming With Java 5 Index

TEXT FIELDS AND TEXT AREAS 993Text Areas and Text Fields 994TIP: Labeling a Text Field 1000TIP: Inputting and Outputting NumbersA Swing Calculator 1001Chapter Summary 1006Answers to Self-Test ExercisesProgramming Projects 1013Chapter 1818.1Swing II100010071017WINDOW LISTENERS 1018EXAMPLE: A Window Listener Inner Class 1020The dispose Method 1023PITFALL: Forgetting to Invoke setDefaultCloseOperation 1024The WindowAdapter Class 102418.2ICONS AND SCROLL BARS1026Icons 1026Scroll Bars 1032EXAMPLE: Components with Changing Visibility18.3THE Graphics CLASS1041Coordinate System for Graphics Objects 1041The Method paint and the Class Graphics 1042Drawing Ovals 1047Drawing Arcs 1047Rounded Rectangles 1051★paintComponent for Panels 1052Action Drawings and repaint 1052Some More Details on Updating a GUI 1058★1037xxixxxxContents18.4COLORS 1058Specifying a Drawing Color 1059Defi ning Colors 1060PITFALL: Using doubles to Defi ne a Color 1061The JColorChooser Dialog Window 106218.5FONTS AND THE drawString METHODThe drawString MethodFonts 1068

Page 25: Web Programming With Java 5 Index

Chapter Summary 1071Answers to Self-Test ExercisesProgramming Projects 1075Chapter 1919.1106510651071Java Never Ends 1079MULTITHREADING 1080EXAMPLE: A Nonresponsive GUI 1081Thread.sleep 1081The getGraphics Method 1085Fixing a Nonresponsive Program Using Threads 1086EXAMPLE: A Multithreaded Program 1086The Class Thread 1087The Runnable Interface 1090★Race Conditions and Thread Synchronization 1093★19.2NETWORKING WITH STREAM SOCKETS 1098Sockets 1098Sockets and Threading19.3JAVABEANS11021103The Component Model 1103The JavaBeans Model 110419.4JAVA AND DATABASE CONNECTIONS1105Relational Databases 1105Java DB and JDBC 1105SQL 110719.5WEB PROGRAMMING WITH JAVA SERVER PAGES 1118Applets, Servlets, and Java Server Pages 1118Oracle GlassFish Enterprise Server 1120HTML Forms—the Common Gateway Interface 1121JSP Declarations, Expressions, Scriptlets, and Directives 1123ContentsChapter Summary 1132Answers to Self-Test ExercisesProgramming Projects 1134Chapter 20Applets and HTMLAppendix 1 Keywords1133(online at www.aw.com/savitch)1139

Page 26: Web Programming With Java 5 Index

Appendix 2 Precedence and Associativity RulesAppendix 3 ASCII Character Set11411143Appendix 4 Format Specifi cations for printf 1145Appendix 5 Summary of Classes and Interfaces 1147