21
Preface The newly revised Building Java Programs textbook is designed for use in an intro- ductory course in computer science. The new chapters in this edition will make it use- ful in a more advanced course in computer science as well. We have class-tested it with thousands of undergraduates at the University of Washington, most of whom were not computer science majors. Introductory computer science courses have a long history at many universities of being “killer” courses with high failure rates. But as Douglas Adams says in The Hitchhiker’s Guide to the Galaxy, “Don’t panic.” Students can master this material if they can learn it gradually. The introductory courses at the University of Washington are experiencing record enrollments and other schools that have adopted our textbook report that students are succeeding with our approach. Since the publication of our first edition, there has been a movement toward the “objects later” approach that we have championed (as opposed to the “objects early” approach). We know from years of experience that a broad range of scientists, engi- neers, and others can learn how to program in a procedural manner. Once we have built a solid foundation of procedural techniques, we turn to object-oriented pro- gramming. By the end of the course, students will have learned about both styles of programming. Here are some of the changes that we have made in the second edition: Three new chapters. We have created three new chapters that extend the coverage of the book, using material that we present in our second course in computer science. Chapter 15 explores the issues that arise in the course of implementing a robust and powerful collection class. Chapter 16 explores pro- gramming with linked lists, and Chapter 17 explores programming with binary trees. Improved case studies. Chapters 6 and 7 contain new case studies that are more interesting than those included in the first edition. The other case studies throughout the textbook have been expanded to better explain subtle points with which students often struggle. Reorganization of “using objects” material. Material in Chapters 3, 4, and 6 has been reorganized into a new section in Chapter 7 on “reference semantics.” We have found that this approach works better for explaining these important concepts. iii

A01 REGE1813 02 SE FMcatalogue.pearsoned.ca/assets/hip/ca/hip_ca_pearsonhighered/prefa… · iv Preface • New section on procedural design heuristics. Chapter 4 now includes a dis-cussion

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

  • Preface

    The newly revised Building Java Programs textbook is designed for use in an intro-ductory course in computer science. The new chapters in this edition will make it use-ful in a more advanced course in computer science as well. We have class-tested itwith thousands of undergraduates at the University of Washington, most of whomwere not computer science majors.

    Introductory computer science courses have a long history at many universities ofbeing “killer” courses with high failure rates. But as Douglas Adams says in TheHitchhiker’s Guide to the Galaxy, “Don’t panic.” Students can master this material ifthey can learn it gradually. The introductory courses at the University of Washingtonare experiencing record enrollments and other schools that have adopted our textbookreport that students are succeeding with our approach.

    Since the publication of our first edition, there has been a movement toward the“objects later” approach that we have championed (as opposed to the “objects early”approach). We know from years of experience that a broad range of scientists, engi-neers, and others can learn how to program in a procedural manner. Once we havebuilt a solid foundation of procedural techniques, we turn to object-oriented pro-gramming. By the end of the course, students will have learned about both styles ofprogramming.

    Here are some of the changes that we have made in the second edition:

    • Three new chapters. We have created three new chapters that extend thecoverage of the book, using material that we present in our second course incomputer science. Chapter 15 explores the issues that arise in the course ofimplementing a robust and powerful collection class. Chapter 16 explores pro-gramming with linked lists, and Chapter 17 explores programming with binarytrees.

    • Improved case studies. Chapters 6 and 7 contain new case studies that are moreinteresting than those included in the first edition. The other case studies throughoutthe textbook have been expanded to better explain subtle points with which studentsoften struggle.

    • Reorganization of “using objects” material. Material in Chapters 3, 4, and 6has been reorganized into a new section in Chapter 7 on “reference semantics.”We have found that this approach works better for explaining these importantconcepts.

    iii

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page iii

  • iv Preface

    • New section on procedural design heuristics. Chapter 4 now includes a dis-cussion of design guidelines for procedural programming.

    • New section on de Morgan’s laws. Chapter 5 has been updated to include asection on de Morgan’s laws and their application to programming withboolean expressions.

    • Rebalancing of object coverage. We have adjusted Chapters 8 and 9, whichcover objects and inheritance, to provide more coherent coverage of thesetopics.

    • New appendix on Java language features. A new appendix describes languagedetails not covered in the chapters such as enumerated types and packages.

    • Arrays class coverage. A new section in Chapter 7 includes coverage of theutility methods available from the Arrays class.

    • Expanded self-checks and programming exercises. We have significantlyincreased the number and quality of self-check exercises and programming exer-cises incorporating new problems in each chapter.

    The following features have been retained from the first edition:

    • Focus on problem solving. Many textbooks focus on language details whenthey introduce new constructs. We focus instead on problem solving. Whatnew problems can be solved with each construct? What pitfalls are noviceslikely to encounter along the way? What are the most common ways to use anew construct?

    • Emphasis on algorithmic thinking. Our procedural approach allows us toemphasize algorithmic problem solving: breaking a large problem into smallerproblems, using pseudocode to refine an algorithm, and grappling with the chal-lenge of expressing a large program algorithmically.

    • Layered approach. Programming in Java involves many concepts that are diffi-cult to learn all at once. Teaching Java to a novice is like trying to build a houseof cards. Each new card has to be placed carefully. If the process is rushed andyou try to place too many cards at once, the entire structure collapses. We teachnew concepts gradually, layer by layer, allowing students to expand their under-standing at a manageable pace.

    • Case studies. We end most chapters with a significant case study that showsstudents how to develop a complex program in stages and how to test it as itis being developed. This structure allows us to demonstrate each new pro-gramming construct in a rich context that can’t be achieved with short codeexamples.

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page iv

  • Layers and Dependencies

    Many introductory computer science books are language-oriented, but the early chap-ters of our book are layered. For example, Java has many control structures (includingfor loops, while loops, and if/else statements), and many books include all ofthese control structures in a single chapter. While that might make sense to someonewho already knows how to program, it can be overwhelming for a novice who islearning how to program. We find that it is much more effective to spread these controlstructures into different chapters so that students learn one structure at a time ratherthan trying to learn them all at once.

    The following table shows how the layered approach works in the first six chapters:

    Preface v

    The Layers

    Programming

    Chapter Control flow Data techniques Input/Output

    1 methods String literals procedural println, print

    decomposition

    2 definite loops (for) variables local variables

    expressions class constants

    int, double pseudocode

    3 return values using objects parameters console input

    graphics (optional)

    4 conditional char pre/post conditions printf

    (if/else) throwing exceptions

    5 indefinite loops boolean assertions

    (while) robust programs

    6 Scanner token-based processing file input/output

    line-based processing

    Chapters 1–6 are designed to be worked through in order, with greater flexibil-ity of study then beginning in Chapter 7. Chapter 6 may be skipped, although thecase study in Chapter 7 involves reading from a file, a topic that is covered inChapter 6.

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page v

  • vi Preface

    The following is a dependency chart for the book:

    Supplements

    Answers to all self-check problems appear in Appendix A. In addition, students canaccess the following resources at http://www.pearsonhighered.com/regesstepp/ or ourweb site at http://www.buildingjavaprograms.com/:

    • Source code and data files for all case studies and other complete programexamples.

    • The DrawingPanel class used in the optional graphics Supplement 3G.

    • The Practice-It! web programming practice system.

    Chapters 1–6Programming Fundamentals

    Chapter 9Inheritance and Interfaces

    Chapter 13Searching and Sorting

    Chapter 14Graphical User Interfaces

    Chapter 10ArrayLists

    Chapter 12Recursion

    Chapter 8Classes

    Chapter 7Arrays

    Chapter 11Java Collections Framework

    Chapter 15Implementing a Collection Class

    Chapter 16Linked Lists

    Chapter 17Binary Trees

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page vi

  • Preface vii

    Instructors can access the following resources from our web site at http://www.buildingjavaprograms.com/:

    • PowerPoint slides suitable for lectures.

    • Solutions to exercises and programming projects, along with homework specifi-cation documents for many projects.

    • Sample Exams and solution keys.

    • Additional Lab Exercises and Programming Exercises with solution keys.

    To access protected instructor resources, contact us at [email protected]. The same materials are also available at http://www.pearsonhighered.com/regesstepp/. To receive a password for this site or to ask other questions relatedto resources, contact your Addison-Wesley sales representative or send email to [email protected].

    Practice-It!

    For the second edition, we have written a web application called Practice-It! that isavailable from our web site at http://www.buildingjavaprograms.com/practice/. Thisapplication allows students to practice the exercises from the book and from ourintroductory programming courses. The system presents a menu of exercises andallows the user to type a solution to a problem and submit it to our server. The systemwill test the solution and report whether the code solves the problem correctly. Forself-checks and University of Washington problems, you may also view the instructor’ssolutions. Many of our own students have reported that they find this system useful,especially when they are studying for exams.

    VideoNotesWe have recorded a series of instructional videos to accompany the second edition ofthe textbook. They are available at http://www.pearsonhighered.com/regesstepp.Roughly 3–4 videos are posted for each chapter. An icon in the margin of the pageindicates when a VideoNote is available for a given topic. In each video, we spend5–15 minutes walking through a particular concept or problem, talking about the chal-lenges and methods necessary to solve it. These videos make a good supplement to theinstruction given in lecture classes and in the textbook. Your new copy of the secondedition has an access code that will allow you to view the videos.

    Acknowledgments

    First, we would like to thank the many students and teaching assistants who have usedand commented on early drafts of this text. We could not have written this book with-out their input. Special thanks go to Hélène Martin, who pored over early versions ofthese chapters to find errors and to identify rough patches that needed work. We would

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page vii

  • viii Preface

    also like to thank instructor Benson Limketkai for spending many hours performing atechnical proofread of the second edition.

    Second, we would like to thank the talented pool of reviewers who guided us inthe process of creating this textbook:

    • Greg Anderson, Weber State University

    • Delroy A. Brinkerhoff, Weber State University

    • Ed Brunjes, Miramar Community College

    • Tom Capaul, Eastern Washington University

    • Tom Cortina, Carnegie Mellon University

    • Charles Dierbach, Towson University

    • H.E. Dunsmore, Purdue University

    • Michael Eckmann, Skidmore College

    • Mary Anne Egan, Siena College

    • Leonard J. Garrett, Temple University

    • Ahmad Ghafarian, North Georgia College & State University

    • Raj Gill, Anne Arundel Community College

    • Michael Hostetler, Park University

    • David Hovemeyer, York College of Pennsylvania

    • Chenglie Hu, Carroll College

    • Philip Isenhour, Virginia Polytechnic Institute

    • Andree Jacobson, University of New Mexico

    • David C. Kamper, Sr., Northeastern Illinois University

    • Simon G.M. Koo, University of San Diego

    • Evan Korth, New York University

    • Joan Krone, Denison University

    • John H.E.F. Lasseter, Fairfield University

    • Eric Matson, Wright State University

    • Kathryn S. McKinley, University of Texas, Austin

    • Jerry Mead, Bucknell University

    • George Medelinskas, Northern Essex Community College

    • John Neitzke, Truman State University

    • Dale E. Parson, Kutztown University

    • Richard E. Pattis, Carnegie Mellon University

    • Frederick Pratter, Eastern Oregon University

    • Roger Priebe, University of Texas, Austin

    • Dehu Qi, Lamar University

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page viii

  • Preface ix

    • John Rager, Amherst College

    • Amala V.S. Rajan, Middlesex University

    • Craig Reinhart, California Lutheran University

    • Mike Scott, University of Texas, Austin

    • Alexa Sharp, Oberlin College

    • Tom Stokke, University of North Dakota

    • Leigh Ann Sudol, Fox Lane High School

    • Ronald F. Taylor, Wright State University

    • Andy Ray Terrel, University of Chicago

    • Scott Thede, DePauw University

    • Megan Thomas, California State University, Stanislaus

    • Dwight Tuinstra, SUNY Potsdam

    • Jeannie Turner, Sayre School

    • Tammy VanDeGrift, University of Portland

    • Thomas John VanDrunen, Wheaton College

    • Neal R. Wagner, University of Texas, San Antonio

    • Jiangping Wang, Webster University

    • Yang Wang, Missouri State University

    • Stephen Weiss, University of North Carolina at Chapel Hill

    • Laurie Werner, Miami University

    • Dianna Xu, Bryn Mawr College

    • Carol Zander, University of Washington, Bothell

    We would also like to thank the dedicated University of Washington teachingassistants who have added many problems to our Practice-It system: Robert Baxter,Whitaker Brand, Leslie Ferguson, Lisa Fiedler, Jason Ganzhorn, Stefanie Hatcher,Roy McElmurry, Jeff Prouty, Stephanie Smallman, Eric Spishak, and Kimberly Todd.

    Finally, we would like to thank the great staff at Addison-Wesley who helped pro-duce the book. Michelle Brown, Jeff Holcomb, Maurene Goo, Patty Mahtani, NancyKotary, and Kathleen Kenny did great work preparing the first edition. Our copy edi-tors and the staff of Aptara Corp, including Heather Sisan, Brian Baker, BrendanShort, and Rachel Head, caught many errors and improved the quality of the writing.Marilyn Lloyd and Chelsea Bell served well as project manager and editorial assis-tant respectively. Special thanks go to our editor Matt Goldstein, who has believed inthe concept of our book from day one. We couldn’t have finished this job without allof their support.

    Stuart Reges

    Marty Stepp

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page ix

  • LOCATION OF VIDEO NOTES IN THE TEXTwww.pearsonhighered.com/regesstepp

    Chapter 1 Pages, 31, 40

    Chapter 2 Pages, 63, 72, 87, 95, 108

    Chapter 3 Pages, 136, 151, 156, 162

    Chapter 3G Pages, 189, 205

    Chapter 4 Pages, 231, 239, 266

    Chapter 5 Pages, 310, 313, 315, 319, 342

    Chapter 6 Pages, 382, 395, 409

    Chapter 7 Pages, 440, 447, 464, 481

    Chapter 8 Pages, 505, 517, 525, 538

    Chapter 9 Pages, 565, 578, 594

    Chapter 10 Pages, 638, 643, 652

    Chapter 11 Pages, 680, 693, 701

    Chapter 12 Pages, 728, 736, 756

    Chapter 13 Pages, 776, 779, 785

    Chapter 14 Pages, 823, 836, 855

    Chapter 15 Pages, 894, 900, 904

    Chapter 16 Pages, 936, 943, 956

    Chapter 17 Pages, 1001, 1002, 1012

    x

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page x

  • Brief Contents

    Preface iiiChapter 1 Introduction to Java Programming 1Chapter 2 Primitive Data and Definite Loops 61Chapter 3 Introduction to Parameters and Objects 132Supplement 3G Graphics (Optional) 188Chapter 4 Conditional Execution 226Chapter 5 Program Logic and Indefinite Loops 301Chapter 6 File Processing 373Chapter 7 Arrays 425Chapter 8 Classes 500Chapter 9 Inheritance and Interfaces 555Chapter 10 ArrayLists 628Chapter 11 Java Collections Framework 679Chapter 12 Recursion 718Chapter 13 Searching and Sorting 774Chapter 14 Graphical User Interfaces 822Chapter 15 Implementing a Collection Class 886Chapter 16 Linked Lists 929Chapter 17 Binary Trees 981Appendix A Answers to Self-Check Problems 1035Appendix B Java Summary 1107Appendix C Javadoc Comments and the Java API Specification 1122Appendix D Additional Java Syntax 1128

    Index 1137

    xi

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xi

  • A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xii

  • Contents

    Preface iii

    Chapter 1 Introduction to Java Programming 1

    1.1 Basic Computing Concepts 2Why Programming? 2Hardware and Software 3The Digital Realm 4The Process of Programming 6Why Java? 7The Java Programming Environment 8

    1.2 And Now—Java 10String Literals (Strings) 14System.out.println 15Escape Sequences 15print versus println 17Identifiers and Keywords 18A Complex Example: DrawFigures1 20Comments and Readability 21

    1.3 Program Errors 24Syntax Errors 24Logic Errors (Bugs) 28

    1.4 Procedural Decomposition 28Static Methods 31Flow of Control 34Methods that Call Other Methods 36An Example Runtime Error 39

    1.5 Case Study: DrawFigures 40Structured Version 41Final Version without Redundancy 43Analysis of Flow of Execution 44

    xiii

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xiii

  • Chapter 2 Primitive Data and Definite Loops 61

    2.1 Basic Data Concepts 62Primitive Types 62Expressions 63Literals 65Arithmetic Operators 66Precedence 68Mixing Types and Casting 71

    2.2 Variables 72Assignment/Declaration Variations 77String Concatenation 80Increment/Decrement Operators 82Variables and Mixing Types 85

    2.3 The for Loop 87Tracing for Loops 89for Loop Patterns 93Nested for Loops 95

    2.4 Managing Complexity 97Scope 97Pseudocode 103Class Constants 106

    2.5 Case Study: Hourglass Figure 108Problem Decomposition and Pseudocode 109Initial Structured Version 111Adding a Class Constant 112Further Variations 115

    Chapter 3 Introduction to Parameters and Objects 132

    3.1 Parameters 133The Mechanics of Parameters 136Limitations of Parameters 140Multiple Parameters 143Parameters versus Constants 146Overloading of Methods 146

    3.2 Methods That Return Values 147The Math Class 148Defining Methods That Return Values 151

    xiv Contents

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xiv

  • 3.3 Using Objects 155String Objects 156Interactive Programs and Scanner Objects 162Sample Interactive Program 165

    3.4 Case Study: Projectile Trajectory 168Unstructured Solution 172Structured Solution 174

    Supplement 3G Graphics (Optional) 188

    3G.1 Introduction to Graphics 189DrawingPanel 189Drawing Lines and Shapes 190Colors 195Drawing with Loops 198Text and Fonts 202

    3G.2 Procedural Decomposition with Graphics 205A Larger Example: DrawDiamonds 206

    3G.3 Case Study: Pyramids 209Unstructured Partial Solution 210Generalizing the Drawing of Pyramids 212Complete Structured Solution 213

    Chapter 4 Conditional Execution 226

    4.1 if/else Statements 227Relational Operators 229Nested if/else Statements 231Object Equality 238Factoring if/else Statements 239Multiple Conditions 241

    4.2 Cumulative Algorithms 242Cumulative Sum 242Min/Max Loops 244Cumulative Sum with if 248Roundoff Errors 250

    4.3 Text Processing 253The char Type 253char versus int 254

    Contents xv

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xv

  • Cumulative Text Algorithms 255System.out.printf 257

    4.4 Methods with Conditional Execution 262Preconditions and Postconditions 262Throwing Exceptions 262Revisiting Return Values 266Reasoning about Paths 271

    4.5 Case Study: Body Mass Index 273One-Person Unstructured Solution 274Two-Person Unstructured Solution 277Two-Person Structured Solution 279Procedural Design Heuristics 283

    Chapter 5 Program Logic and Indefinite Loops 301

    5.1 The while Loop 302A Loop to Find the Smallest Divisor 303Random Numbers 306Simulations 310do/while Loop 311

    5.2 Fencepost Algorithms 313Sentinel Loops 315Fencepost with if 316

    5.3 The booleanType 319Logical Operators 321Short-Circuited Evaluation 324boolean Variables and Flags 328Boolean Zen 330Negating Boolean Expressions 333

    5.4 User Errors 334Scanner Lookahead 335Handling User Errors 337

    5.5 Assertions and Program Logic 339Reasoning about Assertions 341A Detailed Assertions Example 342

    5.6 Case Study: NumberGuess 347Initial Version without Hinting 347Randomized Version with Hinting 349Final Robust Version 353

    xvi Contents

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xvi

  • Chapter 6 File Processing 373

    6.1 File-Reading Basics 374Data, Data Everywhere 374Files and File Objects 374Reading a File with a Scanner 377

    6.2 Details of Token-Based Processing 382Structure of Files and Consuming Input 384Scanner Parameters 389Paths and Directories 390A More Complex Input File 393

    6.3 Line-Based Processing 395String Scanners and Line/Token Combinations 396

    6.4 Advanced File Processing 401Output Files with PrintStream 401Guaranteeing That Files Can Be Read 406

    6.5 Case Study: Zip Code Lookup 409

    Chapter 7 Arrays 425

    7.1 Array Basics 426Constructing and Traversing an Array 426Accessing an Array 430A Complete Array Program 433Random Access 437Arrays and Methods 440The For-Each Loop 443Initializing Arrays 445The Arrays Class 446

    7.2 Array-Traversal Algorithms 447Printing an Array 448Searching and Replacing 450Testing for Equality 453Reversing an Array 454String Traversal Algorithms 459

    7.3 Reference Semantics 460Multiple Objects 462

    Contents xvii

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xvii

  • 7.4 Advanced Array Techniques 464Shifting Values in an Array 464Arrays of Objects 469Command-Line Arguments 470Nested Loop Algorithms 471

    7.5 Multidimensional Arrays 473Rectangular Two-Dimensional Arrays 473Jagged Arrays 475

    7.6 Case Study: Benford’s Law 479Tallying Values 481Completing the Program 485

    Chapter 8 Classes 500

    8.1 Object-Oriented Programming 501Classes and Objects 502Point Objects 504

    8.2 Object State and Behavior 505Object State: Fields 506Object Behavior: Methods 508The Implicit Parameter 511Mutators and Accessors 513The toString Method 515

    8.3 Object Initialization: Constructors 517The Keyword this 522Multiple Constructors 524

    8.4 Encapsulation 525Private Fields 526Class Invariants 532Changing Internal Implementations 536

    8.5 Case Study: Designing a Stock Class 538Object-Oriented Design Heuristics 539Stock Fields and Method Headers 541Stock Method and Constructor Implementation 543

    Chapter 9 Inheritance and Interfaces 555

    9.1 Inheritance Basics 556Nonprogramming Hierarchies 557

    xviii Contents

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xviii

  • Extending a Class 559Overriding Methods 563

    9.2 Interacting with the Superclass 565Calling Overridden Methods 565Accessing Inherited Fields 566Calling a Superclass’s Constructor 568DividendStock Behavior 570The Object Class 572The equals Method 573The instanceof Keyword 576

    9.3 Polymorphism 578Polymorphism Mechanics 581Interpreting Inheritance Code 583Interpreting Complex Calls 585

    9.4 Inheritance and Design 588A Misuse of Inheritance 588Is-a Versus Has-a Relationships 591Graphics2D 592

    9.5 Interfaces 594An Interface for Shapes 595Implementing an Interface 597Benefits of Interfaces 600

    9.6 Case Study: Financial Class Hierarchy 602Designing the Classes 603Redundant Implementation 607Abstract Classes 610

    Chapter 10 ArrayLists 628

    10.1 ArrayLists 629Basic ArrayList Operations 630ArrayList Searching Methods 633A Complete ArrayList Program 636Adding to and Removing from an ArrayList 638Using the For-Each Loop with ArrayLists 642Wrapper Classes 643

    10.2 The Comparable Interface 646Natural Ordering and compareTo 648Implementing the Comparable Interface 652

    Contents xix

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xix

  • 10.3 Case Study: Vocabulary Comparison 656Some Efficiency Considerations 657Version 1: Compute Vocabulary 659Version 2: Compute Overlap 664Version 3: Complete Program 669

    Chapter 11 Java Collections Framework 679

    11.1 Lists 680Collections 680LinkedList versus ArrayList 681Iterators 684Abstract Data Types (ADTs) 687LinkedList Case Study: Sieve 690

    11.2 Sets 693Set Concepts 694TreeSet versus HashSet 696Set Operations 697Set Case Study: Lottery 699

    11.3 Maps 701Basic Map Operations 702Map Views (keySet and values) 704TreeMap versus HashMap 705Map Case Study: WordCount 706Collection Overview 709

    Chapter 12 Recursion 718

    12.1 Thinking Recursively 719A Nonprogramming Example 719An Iterative Solution Converted to Recursion 722Structure of Recursive Solutions 724

    12.2 A Better Example of Recursion 726Mechanics of Recursion 728

    12.3 Recursive Functions and Data 736Integer Exponentiation 736Greatest Common Divisor 739Directory Crawler 745Helper Methods 749

    12.4 Recursive Graphics (Optional) 752

    xx Contents

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xx

  • 12.5 Case Study: Prefix Evaluator 756Infix, Prefix, and Postfix Notation 757Evaluating Prefix Expressions 757Complete Program 761

    Chapter 13 Searching and Sorting 774

    13.1 Searching and Sorting in the Java Class Libraries 775Binary Search 776Sorting 779Shuffling 780Custom Ordering with Comparators 781

    13.2 Program Complexity 785Empirical Analysis 788Complexity Classes 792

    13.3 Implementing Searching and Sorting Algorithms 794Sequential Search 795Binary Search 796Recursive Binary Search 799Searching Objects 802Selection Sort 803

    13.4 Case Study: Implementing Merge Sort 806Splitting and Merging Arrays 807Recursive Merge Sort 810Complete Program 813

    Chapter 14 Graphical User Interfaces 822

    14.1 GUI Basics 823Graphical Input and Output with Option Panes 823Working with Frames 826Buttons, Text Fields, and Labels 831Changing a Frame’s Layout 833Handling an Event 834

    14.2 Laying Out Components 836Layout Managers 837Composite Layouts 840

    14.3 Interaction Between Components 845Example 1: BMI GUI 845

    Contents xxi

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xxi

  • Object-Oriented GUIs 846Example 2: Credit Card GUI 850

    14.4 Additional Components and Events 855Text Areas, Scrollbars, and Fonts 856Icons 858Mouse Events 860

    14.5 Two-Dimensional Graphics 865Drawing onto Panels 865Animation with Timers 867

    14.6 Case Study: Implementing DrawingPanel 872Initial Version without Events 872Second Version with Events 874

    Chapter 15 Implementing a Collection Class 886

    15.1 Simple ArrayIntList 887Adding and Printing 887Thinking about Encapsulation 893Dealing with the Middle of the List 894Another Constructor and a Constant 899Preconditions and Postconditions 900

    15.2 A More Complete ArrayIntList 904Throwing Exceptions 904Convenience Methods 907

    15.3 Advanced Features 910Resizing When Necessary 910Adding an Iterator 912

    15.4 ArrayList 918

    Chapter 16 Linked Lists 929

    16.1 Working with Nodes 930Constructing a List 931List Basics 933Manipulating Nodes 936Traversing a List 939

    16.2 A Linked List Class 943Simple LinkedIntList 943

    xxii Contents

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xxii

  • Appending add 945The Middle of the List 949

    16.3 A Complex List Operation 956Inchworm Approach 961

    16.4 An IntList Interface 962

    16.5 LinkedList 965Linked List Variations 966Linked List Iterators 969Other Code Details 971

    Chapter 17 Binary Trees 981

    17.1 Binary Tree Basics 982Node and Tree Classes 985

    17.2 Tree Traversals 986Constructing and Viewing a Tree 992

    17.3 Common Tree Operations 1001Sum of a Tree 1001Counting Levels 1002Counting Leaves 1004

    17.4 Binary Search Trees 1005The Binary Search Tree Property 1006Building a Binary Search Tree 1008The Pattern x = change(x) 1012Searching the Tree 1015Binary Search Tree Complexity 1019

    17.5 SearchTree 1020

    Appendix A Answers to Self-Check Problems 1035

    Appendix B Java Summary 1107

    Appendix C Javadoc Comments and the Java API Specification 1122

    Appendix D Additional Java Syntax 1128

    Index 1137

    Contents xxiii

    A01_REGE1813_02_SE_FM.qxd 2/10/10 5:49 PM Page xxiii